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