Magicsig.php 11 KB

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