Magicsig.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 DIASPORA_PUBLICKEYREL = 'diaspora-public-key';
  37. const DEFAULT_KEYLEN = 1024;
  38. const DEFAULT_SIGALG = 'RSA-SHA256';
  39. public $__table = 'magicsig';
  40. /**
  41. * Key to user.id/profile.id for the local user whose key we're storing.
  42. *
  43. * @var int
  44. */
  45. public $user_id;
  46. /**
  47. * Flattened string representation of the key pair; callers should
  48. * usually use $this->publicKey and $this->privateKey directly,
  49. * which hold live Crypt_RSA key objects.
  50. *
  51. * @var string
  52. */
  53. public $keypair;
  54. /**
  55. * Crypto algorithm used for this key; currently only RSA-SHA256 is supported.
  56. *
  57. * @var string
  58. */
  59. public $alg;
  60. /**
  61. * Public RSA key; gets serialized in/out via $this->keypair string.
  62. *
  63. * @var Crypt_RSA
  64. */
  65. public $publicKey;
  66. /**
  67. * PrivateRSA key; gets serialized in/out via $this->keypair string.
  68. *
  69. * @var Crypt_RSA
  70. */
  71. public $privateKey;
  72. public function __construct($alg=self::DEFAULT_SIGALG)
  73. {
  74. $this->alg = $alg;
  75. }
  76. /**
  77. * Fetch a Magicsig object from the cache or database on a field match.
  78. *
  79. * @param string $k
  80. * @param mixed $v
  81. * @return Magicsig
  82. */
  83. static function getKV($k, $v=null)
  84. {
  85. $obj = parent::getKV($k, $v);
  86. if ($obj instanceof Magicsig) {
  87. $obj->importKeys(); // Loads Crypt_RSA objects etc.
  88. // Throw out a big fat warning for keys of less than 1024 bits. (
  89. // The only case these show up in would be imported or
  90. // legacy very-old-StatusNet generated keypairs.
  91. if (strlen($obj->publicKey->modulus->toBits()) < 1024) {
  92. common_log(LOG_WARNING, sprintf('Salmon key with <1024 bits (%d) belongs to profile with id==%d',
  93. strlen($obj->publicKey->modulus->toBits()),
  94. $obj->user_id));
  95. }
  96. }
  97. return $obj;
  98. }
  99. public static function schemaDef()
  100. {
  101. return array(
  102. 'fields' => array(
  103. 'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user id'),
  104. 'keypair' => array('type' => 'text', 'description' => 'keypair text representation'),
  105. 'alg' => array('type' => 'varchar', 'length' => 64, 'description' => 'algorithm'),
  106. ),
  107. 'primary key' => array('user_id'),
  108. 'foreign keys' => array(
  109. 'magicsig_user_id_fkey' => array('profile', array('user_id' => 'id')),
  110. ),
  111. );
  112. }
  113. /**
  114. * Save this keypair into the database.
  115. *
  116. * Overloads default insert behavior to encode the live key objects
  117. * as a flat string for storage.
  118. *
  119. * @return mixed
  120. */
  121. function insert()
  122. {
  123. $this->keypair = $this->toString(true);
  124. return parent::insert();
  125. }
  126. /**
  127. * Generate a new keypair for a local user and store in the database.
  128. *
  129. * Warning: this can be very slow on systems without the GMP module.
  130. * Runtimes of 20-30 seconds are not unheard-of.
  131. *
  132. * FIXME: More than 1024 bits please. But StatusNet _discards_ non-1024 bits,
  133. * so we'll have to wait the last mohican out before switching defaults.
  134. *
  135. * @param User $user the local user (since we don't have remote private keys)
  136. */
  137. public static function generate(User $user, $bits=self::DEFAULT_KEYLEN, $alg=self::DEFAULT_SIGALG)
  138. {
  139. $magicsig = new Magicsig($alg);
  140. $magicsig->user_id = $user->id;
  141. $rsa = new Crypt_RSA();
  142. $keypair = $rsa->createKey($bits);
  143. $magicsig->privateKey = new Crypt_RSA();
  144. $magicsig->privateKey->loadKey($keypair['privatekey']);
  145. $magicsig->publicKey = new Crypt_RSA();
  146. $magicsig->publicKey->loadKey($keypair['publickey']);
  147. $magicsig->insert(); // will do $this->keypair = $this->toString(true);
  148. $magicsig->importKeys(); // seems it's necessary to re-read keys from text keypair
  149. return $magicsig;
  150. }
  151. /**
  152. * Encode the keypair or public key as a string.
  153. *
  154. * @param boolean $full_pair set to true to include the private key.
  155. * @return string
  156. */
  157. public function toString($full_pair=false)
  158. {
  159. $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
  160. $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
  161. $private_exp = '';
  162. if ($full_pair && $this->privateKey instanceof Crypt_RSA && $this->privateKey->exponent->toBytes()) {
  163. $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
  164. }
  165. return 'RSA.' . $mod . '.' . $exp . $private_exp;
  166. }
  167. public function exportPublicKey($format=CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  168. {
  169. $this->publicKey->setPublicKey();
  170. return $this->publicKey->getPublicKey($format);
  171. }
  172. /**
  173. * importKeys will load the object's keypair string, which initiates
  174. * loadKey() and configures Crypt_RSA objects.
  175. *
  176. * @param string $keypair optional, otherwise the object's "keypair" property will be used
  177. */
  178. public function importKeys($keypair=null)
  179. {
  180. $this->keypair = $keypair===null ? $this->keypair : preg_replace('/\s+/', '', $keypair);
  181. // parse components
  182. if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(\.([^\.]+))?/', $this->keypair, $matches)) {
  183. common_debug('Magicsig error: RSA key not found in provided string.');
  184. throw new ServerException('RSA key not found in keypair string.');
  185. }
  186. $mod = $matches[1];
  187. $exp = $matches[2];
  188. if (!empty($matches[4])) {
  189. $private_exp = $matches[4];
  190. } else {
  191. $private_exp = false;
  192. }
  193. $this->loadKey($mod, $exp, 'public');
  194. if ($private_exp) {
  195. $this->loadKey($mod, $private_exp, 'private');
  196. }
  197. }
  198. /**
  199. * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
  200. * representing the give key (as mod/exponent pair).
  201. *
  202. * @param string $mod base64-encoded
  203. * @param string $exp base64-encoded exponent
  204. * @param string $type one of 'public' or 'private'
  205. */
  206. public function loadKey($mod, $exp, $type = 'public')
  207. {
  208. $rsa = new Crypt_RSA();
  209. $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  210. $rsa->setHash($this->getHash());
  211. $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
  212. $rsa->k = strlen($rsa->modulus->toBytes());
  213. $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
  214. if ($type == 'private') {
  215. $this->privateKey = $rsa;
  216. } else {
  217. $this->publicKey = $rsa;
  218. }
  219. }
  220. /**
  221. * Returns the name of the crypto algorithm used for this key.
  222. *
  223. * @return string
  224. */
  225. public function getName()
  226. {
  227. return $this->alg;
  228. }
  229. /**
  230. * Returns the name of a hash function to use for signing with this key.
  231. *
  232. * @return string
  233. */
  234. public function getHash()
  235. {
  236. switch ($this->alg) {
  237. case 'RSA-SHA256':
  238. return 'sha256';
  239. }
  240. throw new ServerException('Unknown or unsupported hash algorithm for Salmon');
  241. }
  242. /**
  243. * Generate base64-encoded signature for the given byte string
  244. * using our private key.
  245. *
  246. * @param string $bytes as raw byte string
  247. * @return string base64url-encoded signature
  248. */
  249. public function sign($bytes)
  250. {
  251. $sig = $this->privateKey->sign($bytes);
  252. if ($sig === false) {
  253. throw new ServerException('Could not sign data');
  254. }
  255. return Magicsig::base64_url_encode($sig);
  256. }
  257. /**
  258. *
  259. * @param string $signed_bytes as raw byte string
  260. * @param string $signature as base64url encoded
  261. * @return boolean
  262. */
  263. public function verify($signed_bytes, $signature)
  264. {
  265. $signature = self::base64_url_decode($signature);
  266. return $this->publicKey->verify($signed_bytes, $signature);
  267. }
  268. /**
  269. * URL-encoding-friendly base64 variant encoding.
  270. *
  271. * @param string $input
  272. * @return string
  273. */
  274. public static function base64_url_encode($input)
  275. {
  276. return strtr(base64_encode($input), '+/', '-_');
  277. }
  278. /**
  279. * URL-encoding-friendly base64 variant decoding.
  280. *
  281. * @param string $input
  282. * @return string
  283. */
  284. public static function base64_url_decode($input)
  285. {
  286. return base64_decode(strtr($input, '-_', '+/'));
  287. }
  288. }