Magicsig.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * A sample module to show best practices for StatusNet plugins
  7. *
  8. * PHP version 5
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @package StatusNet
  24. * @author James Walker <james@status.net>
  25. * @copyright 2010 StatusNet, Inc.
  26. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  27. * @link http://status.net/
  28. */
  29. if (!defined('STATUSNET')) {
  30. exit(1);
  31. }
  32. require_once 'Crypt/RSA.php';
  33. class Magicsig extends Managed_DataObject
  34. {
  35. const PUBLICKEYREL = 'magic-public-key';
  36. const DEFAULT_KEYLEN = 1024;
  37. const DEFAULT_SIGALG = 'RSA-SHA256';
  38. public $__table = 'magicsig';
  39. /**
  40. * Key to user.id/profile.id for the local user whose key we're storing.
  41. *
  42. * @var int
  43. */
  44. public $user_id;
  45. /**
  46. * Flattened string representation of the key pair; callers should
  47. * usually use $this->publicKey and $this->privateKey directly,
  48. * which hold live Crypt_RSA key objects.
  49. *
  50. * @var string
  51. */
  52. public $keypair;
  53. /**
  54. * Crypto algorithm used for this key; currently only RSA-SHA256 is supported.
  55. *
  56. * @var string
  57. */
  58. public $alg;
  59. /**
  60. * Public RSA key; gets serialized in/out via $this->keypair string.
  61. *
  62. * @var Crypt_RSA
  63. */
  64. public $publicKey;
  65. /**
  66. * PrivateRSA key; gets serialized in/out via $this->keypair string.
  67. *
  68. * @var Crypt_RSA
  69. */
  70. public $privateKey;
  71. public function __construct($alg=self::DEFAULT_SIGALG)
  72. {
  73. $this->alg = $alg;
  74. }
  75. /**
  76. * Fetch a Magicsig object from the cache or database on a field match.
  77. *
  78. * @param string $k
  79. * @param mixed $v
  80. * @return Magicsig
  81. */
  82. static function getKV($k, $v=null)
  83. {
  84. $obj = parent::getKV($k, $v);
  85. if ($obj instanceof Magicsig) {
  86. $obj->importKeys(); // Loads Crypt_RSA objects etc.
  87. // Throw out a big fat warning for keys of less than 1024 bits. (
  88. // The only case these show up in would be imported or
  89. // legacy very-old-StatusNet generated keypairs.
  90. if (strlen($obj->publicKey->modulus->toBits()) < 1024) {
  91. common_log(LOG_WARNING, sprintf('Salmon key with <1024 bits (%d) belongs to profile with id==%d',
  92. strlen($obj->publicKey->modulus->toBits()),
  93. $obj->user_id));
  94. }
  95. }
  96. return $obj;
  97. }
  98. public static function schemaDef()
  99. {
  100. return array(
  101. 'fields' => array(
  102. 'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user id'),
  103. 'keypair' => array('type' => 'text', 'description' => 'keypair text representation'),
  104. 'alg' => array('type' => 'varchar', 'length' => 64, 'description' => 'algorithm'),
  105. ),
  106. 'primary key' => array('user_id'),
  107. 'foreign keys' => array(
  108. 'magicsig_user_id_fkey' => array('profile', array('user_id' => 'id')),
  109. ),
  110. );
  111. }
  112. /**
  113. * Save this keypair into the database.
  114. *
  115. * Overloads default insert behavior to encode the live key objects
  116. * as a flat string for storage.
  117. *
  118. * @return mixed
  119. */
  120. function insert()
  121. {
  122. $this->keypair = $this->toString(true);
  123. return parent::insert();
  124. }
  125. /**
  126. * Generate a new keypair for a local user and store in the database.
  127. *
  128. * Warning: this can be very slow on systems without the GMP module.
  129. * Runtimes of 20-30 seconds are not unheard-of.
  130. *
  131. * FIXME: More than 1024 bits please. But StatusNet _discards_ non-1024 bits,
  132. * so we'll have to wait the last mohican out before switching defaults.
  133. *
  134. * @param User $user the local user (since we don't have remote private keys)
  135. */
  136. public static function generate(User $user, $bits=self::DEFAULT_KEYLEN, $alg=self::DEFAULT_SIGALG)
  137. {
  138. $magicsig = new Magicsig($alg);
  139. $magicsig->user_id = $user->id;
  140. $rsa = new Crypt_RSA();
  141. $keypair = $rsa->createKey($bits);
  142. $magicsig->privateKey = new Crypt_RSA();
  143. $magicsig->privateKey->loadKey($keypair['privatekey']);
  144. $magicsig->publicKey = new Crypt_RSA();
  145. $magicsig->publicKey->loadKey($keypair['publickey']);
  146. $magicsig->insert(); // will do $this->keypair = $this->toString(true);
  147. $magicsig->importKeys(); // seems it's necessary to re-read keys from text keypair
  148. return $magicsig;
  149. }
  150. /**
  151. * Encode the keypair or public key as a string.
  152. *
  153. * @param boolean $full_pair set to true to include the private key.
  154. * @return string
  155. */
  156. public function toString($full_pair=false, $base64url=true)
  157. {
  158. $base64_func = $base64url ? 'Magicsig::base64_url_encode' : 'base64_encode';
  159. $mod = call_user_func($base64_func, $this->publicKey->modulus->toBytes());
  160. $exp = call_user_func($base64_func, $this->publicKey->exponent->toBytes());
  161. $private_exp = '';
  162. if ($full_pair && $this->privateKey instanceof Crypt_RSA && $this->privateKey->exponent->toBytes()) {
  163. $private_exp = '.' . call_user_func($base64_func, $this->privateKey->exponent->toBytes());
  164. }
  165. return 'RSA.' . $mod . '.' . $exp . $private_exp;
  166. }
  167. public function toFingerprint()
  168. {
  169. // This assumes a specific behaviour from toString, to format as such:
  170. // "RSA." + base64(pubkey.modulus_as_bytes) + "." + base64(pubkey.exponent_as_bytes)
  171. // We don't want the base64 string to be the "url encoding" version because it is not
  172. // as common in programming libraries. And we want it to be base64 encoded since ASCII
  173. // representation avoids any problems with NULL etc. in less forgiving languages and also
  174. // just easier to debug...
  175. return strtolower(hash('sha256', $this->toString(false, false)));
  176. }
  177. public function exportPublicKey($format=CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  178. {
  179. $this->publicKey->setPublicKey();
  180. return $this->publicKey->getPublicKey($format);
  181. }
  182. /**
  183. * importKeys will load the object's keypair string, which initiates
  184. * loadKey() and configures Crypt_RSA objects.
  185. *
  186. * @param string $keypair optional, otherwise the object's "keypair" property will be used
  187. */
  188. public function importKeys($keypair=null)
  189. {
  190. $this->keypair = $keypair===null ? $this->keypair : preg_replace('/\s+/', '', $keypair);
  191. // parse components
  192. if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(\.([^\.]+))?/', $this->keypair, $matches)) {
  193. common_debug('Magicsig error: RSA key not found in provided string.');
  194. throw new ServerException('RSA key not found in keypair string.');
  195. }
  196. $mod = $matches[1];
  197. $exp = $matches[2];
  198. if (!empty($matches[4])) {
  199. $private_exp = $matches[4];
  200. } else {
  201. $private_exp = false;
  202. }
  203. $this->loadKey($mod, $exp, 'public');
  204. if ($private_exp) {
  205. $this->loadKey($mod, $private_exp, 'private');
  206. }
  207. }
  208. /**
  209. * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
  210. * representing the give key (as mod/exponent pair).
  211. *
  212. * @param string $mod base64url-encoded
  213. * @param string $exp base64url-encoded exponent
  214. * @param string $type one of 'public' or 'private'
  215. */
  216. public function loadKey($mod, $exp, $type = 'public')
  217. {
  218. $rsa = new Crypt_RSA();
  219. $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  220. $rsa->setHash($this->getHash());
  221. $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
  222. $rsa->k = strlen($rsa->modulus->toBytes());
  223. $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
  224. if ($type == 'private') {
  225. $this->privateKey = $rsa;
  226. } else {
  227. $this->publicKey = $rsa;
  228. }
  229. }
  230. public function loadPublicKeyPKCS1($key)
  231. {
  232. $rsa = new Crypt_RSA();
  233. if (!$rsa->setPublicKey($key, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)) {
  234. throw new ServerException('Could not load PKCS1 public key. We probably got this from a remote Diaspora node as the profile public key.');
  235. }
  236. $this->publicKey = $rsa;
  237. }
  238. /**
  239. * Returns the name of the crypto algorithm used for this key.
  240. *
  241. * @return string
  242. */
  243. public function getName()
  244. {
  245. return $this->alg;
  246. }
  247. /**
  248. * Returns the name of a hash function to use for signing with this key.
  249. *
  250. * @return string
  251. */
  252. public function getHash()
  253. {
  254. switch ($this->alg) {
  255. case 'RSA-SHA256':
  256. return 'sha256';
  257. }
  258. throw new ServerException('Unknown or unsupported hash algorithm for Salmon');
  259. }
  260. /**
  261. * Generate base64-encoded signature for the given byte string
  262. * using our private key.
  263. *
  264. * @param string $bytes as raw byte string
  265. * @return string base64url-encoded signature
  266. */
  267. public function sign($bytes)
  268. {
  269. $sig = $this->privateKey->sign($bytes);
  270. if ($sig === false) {
  271. throw new ServerException('Could not sign data');
  272. }
  273. return Magicsig::base64_url_encode($sig);
  274. }
  275. /**
  276. *
  277. * @param string $signed_bytes as raw byte string
  278. * @param string $signature as base64url encoded
  279. * @return boolean
  280. */
  281. public function verify($signed_bytes, $signature)
  282. {
  283. $signature = self::base64_url_decode($signature);
  284. return $this->publicKey->verify($signed_bytes, $signature);
  285. }
  286. /**
  287. * URL-encoding-friendly base64 variant encoding.
  288. *
  289. * @param string $input
  290. * @return string
  291. */
  292. public static function base64_url_encode($input)
  293. {
  294. return strtr(base64_encode($input), '+/', '-_');
  295. }
  296. /**
  297. * URL-encoding-friendly base64 variant decoding.
  298. *
  299. * @param string $input
  300. * @return string
  301. */
  302. public static function base64_url_decode($input)
  303. {
  304. return base64_decode(strtr($input, '-_', '+/'));
  305. }
  306. }