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