]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
Added doc comments on Salmon magicsig-related stuff to help in figuring out what...
[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 Memcached_DataObject
37 {
38     const PUBLICKEYREL = 'magic-public-key';
39
40     public $__table = 'magicsig';
41
42     /**
43      * Key to user.id/profile.id for the local user whose key we're storing.
44      *
45      * @var int
46      */
47     public $user_id;
48
49     /**
50      * Flattened string representation of the key pair; callers should
51      * usually use $this->publicKey and $this->privateKey directly,
52      * which hold live Crypt_RSA key objects.
53      *
54      * @var string
55      */
56     public $keypair;
57
58     /**
59      * Crypto algorithm used for this key; currently only RSA-SHA256 is supported.
60      *
61      * @var string
62      */
63     public $alg;
64
65     /**
66      * Public RSA key; gets serialized in/out via $this->keypair string.
67      *
68      * @var Crypt_RSA
69      */
70     public $publicKey;
71
72     /**
73      * PrivateRSA key; gets serialized in/out via $this->keypair string.
74      *
75      * @var Crypt_RSA
76      */
77     public $privateKey;
78
79     public function __construct($alg = 'RSA-SHA256')
80     {
81         $this->alg = $alg;
82     }
83
84     /**
85      * Fetch a Magicsig object from the cache or database on a field match.
86      *
87      * @param string $k
88      * @param mixed $v
89      * @return Magicsig
90      */
91     public /*static*/ function staticGet($k, $v=null)
92     {
93         $obj =  parent::staticGet(__CLASS__, $k, $v);
94         if (!empty($obj)) {
95             $obj = Magicsig::fromString($obj->keypair);
96
97             // Double check keys: Crypt_RSA did not
98             // consistently generate good keypairs.
99             // We've also moved to 1024 bit keys.
100             if (strlen($obj->publicKey->modulus->toBits()) != 1024) {
101                 $obj->delete();
102                 return false;
103             }
104         }
105
106         return $obj;
107     }
108
109
110     function table()
111     {
112         return array(
113             'user_id' => DB_DATAOBJECT_INT,
114             'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
115             'alg'     => DB_DATAOBJECT_STR
116         );
117     }
118
119     static function schemaDef()
120     {
121         return array(new ColumnDef('user_id', 'integer',
122                                    null, false, 'PRI'),
123                      new ColumnDef('keypair', 'text',
124                                    false, false),
125                      new ColumnDef('alg', 'varchar',
126                                    64, false));
127     }
128
129     function keys()
130     {
131         return array_keys($this->keyTypes());
132     }
133
134     function keyTypes()
135     {
136         return array('user_id' => 'K');
137     }
138
139     function sequenceKey() {
140         return array(false, false, false);
141     }
142
143     /**
144      * Save this keypair into the database.
145      *
146      * Overloads default insert behavior to encode the live key objects
147      * as a flat string for storage.
148      *
149      * @return mixed
150      */
151     function insert()
152     {
153         $this->keypair = $this->toString();
154
155         return parent::insert();
156     }
157
158     /**
159      * Generate a new keypair for a local user and store in the database.
160      *
161      * Warning: this can be very slow on systems without the GMP module.
162      * Runtimes of 20-30 seconds are not unheard-of.
163      *
164      * @param int $user_id id of local user we're creating a key for
165      */
166     public function generate($user_id)
167     {
168         $rsa = new Crypt_RSA();
169
170         $keypair = $rsa->createKey();
171
172         $rsa->loadKey($keypair['privatekey']);
173
174         $this->privateKey = new Crypt_RSA();
175         $this->privateKey->loadKey($keypair['privatekey']);
176
177         $this->publicKey = new Crypt_RSA();
178         $this->publicKey->loadKey($keypair['publickey']);
179
180         $this->user_id = $user_id;
181         $this->insert();
182     }
183
184     /**
185      * Encode the keypair or public key as a string.
186      *
187      * @param boolean $full_pair set to false to leave out the private key.
188      * @return string
189      */
190     public function toString($full_pair = true)
191     {
192         $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
193         $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
194         $private_exp = '';
195         if ($full_pair && $this->privateKey->exponent->toBytes()) {
196             $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
197         }
198
199         return 'RSA.' . $mod . '.' . $exp . $private_exp;
200     }
201
202     /**
203      * Decode a string representation of an RSA public key or keypair
204      * as a Magicsig object which can be used to sign or verify.
205      *
206      * @param string $text
207      * @return Magicsig
208      */
209     public static function fromString($text)
210     {
211         $magic_sig = new Magicsig();
212
213         // remove whitespace
214         $text = preg_replace('/\s+/', '', $text);
215
216         // parse components
217         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
218             return false;
219         }
220
221         $mod = $matches[1];
222         $exp = $matches[2];
223         if (!empty($matches[4])) {
224             $private_exp = $matches[4];
225         } else {
226             $private_exp = false;
227         }
228
229         $magic_sig->loadKey($mod, $exp, 'public');
230         if ($private_exp) {
231             $magic_sig->loadKey($mod, $private_exp, 'private');
232         }
233
234         return $magic_sig;
235     }
236
237     /**
238      * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
239      * representing the give key (as mod/exponent pair).
240      *
241      * @param string $mod base64-encoded
242      * @param string $exp base64-encoded exponent
243      * @param string $type one of 'public' or 'private'
244      */
245     public function loadKey($mod, $exp, $type = 'public')
246     {
247         common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
248
249         $rsa = new Crypt_RSA();
250         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
251         $rsa->setHash('sha256');
252         $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
253         $rsa->k = strlen($rsa->modulus->toBytes());
254         $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
255
256         if ($type == 'private') {
257             $this->privateKey = $rsa;
258         } else {
259             $this->publicKey = $rsa;
260         }
261     }
262
263     /**
264      * Returns the name of the crypto algorithm used for this key.
265      *
266      * @return string
267      */
268     public function getName()
269     {
270         return $this->alg;
271     }
272
273     /**
274      * Returns the name of a hash function to use for signing with this key.
275      *
276      * @return string
277      * @fixme is this used? doesn't seem to be called by name.
278      */
279     public function getHash()
280     {
281         switch ($this->alg) {
282
283         case 'RSA-SHA256':
284             return 'sha256';
285         }
286     }
287
288     /**
289      * Generate base64-encoded signature for the given byte string
290      * using our private key.
291      *
292      * @param string $bytes as raw byte string
293      * @return string base64-encoded signature
294      */
295     public function sign($bytes)
296     {
297         $sig = $this->privateKey->sign($bytes);
298         return Magicsig::base64_url_encode($sig);
299     }
300
301     /**
302      *
303      * @param string $signed_bytes as raw byte string
304      * @param string $signature as base64
305      * @return boolean
306      */
307     public function verify($signed_bytes, $signature)
308     {
309         $signature = Magicsig::base64_url_decode($signature);
310         return $this->publicKey->verify($signed_bytes, $signature);
311     }
312
313     /**
314      * URL-encoding-friendly base64 variant encoding.
315      *
316      * @param string $input
317      * @return string
318      */
319     public static function base64_url_encode($input)
320     {
321         return strtr(base64_encode($input), '+/', '-_');
322     }
323
324     /**
325      * URL-encoding-friendly base64 variant decoding.
326      *
327      * @param string $input
328      * @return string
329      */
330     public static function base64_url_decode($input)
331     {
332         return base64_decode(strtr($input, '-_', '+/'));
333     }
334 }