]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
1ef913792bd983bcf9ad6bae8845904a5432f889
[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
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     static function getKV($k, $v=null)
92     {
93         $obj =  parent::getKV($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     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('user', 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();
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      * @param int $user_id id of local user we're creating a key for
146      */
147     public function generate($user_id)
148     {
149         $rsa = new Crypt_RSA();
150
151         $keypair = $rsa->createKey();
152
153         $rsa->loadKey($keypair['privatekey']);
154
155         $this->privateKey = new Crypt_RSA();
156         $this->privateKey->loadKey($keypair['privatekey']);
157
158         $this->publicKey = new Crypt_RSA();
159         $this->publicKey->loadKey($keypair['publickey']);
160
161         $this->user_id = $user_id;
162         $this->insert();
163     }
164
165     /**
166      * Encode the keypair or public key as a string.
167      *
168      * @param boolean $full_pair set to false to leave out the private key.
169      * @return string
170      */
171     public function toString($full_pair = true)
172     {
173         $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
174         $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
175         $private_exp = '';
176         if ($full_pair && $this->privateKey->exponent->toBytes()) {
177             $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
178         }
179
180         return 'RSA.' . $mod . '.' . $exp . $private_exp;
181     }
182
183     /**
184      * Decode a string representation of an RSA public key or keypair
185      * as a Magicsig object which can be used to sign or verify.
186      *
187      * @param string $text
188      * @return Magicsig
189      */
190     public static function fromString($text)
191     {
192         $magic_sig = new Magicsig();
193
194         // remove whitespace
195         $text = preg_replace('/\s+/', '', $text);
196
197         // parse components
198         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
199             return false;
200         }
201
202         $mod = $matches[1];
203         $exp = $matches[2];
204         if (!empty($matches[4])) {
205             $private_exp = $matches[4];
206         } else {
207             $private_exp = false;
208         }
209
210         $magic_sig->loadKey($mod, $exp, 'public');
211         if ($private_exp) {
212             $magic_sig->loadKey($mod, $private_exp, 'private');
213         }
214
215         return $magic_sig;
216     }
217
218     /**
219      * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
220      * representing the give key (as mod/exponent pair).
221      *
222      * @param string $mod base64-encoded
223      * @param string $exp base64-encoded exponent
224      * @param string $type one of 'public' or 'private'
225      */
226     public function loadKey($mod, $exp, $type = 'public')
227     {
228         common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
229
230         $rsa = new Crypt_RSA();
231         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
232         $rsa->setHash('sha256');
233         $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
234         $rsa->k = strlen($rsa->modulus->toBytes());
235         $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
236
237         if ($type == 'private') {
238             $this->privateKey = $rsa;
239         } else {
240             $this->publicKey = $rsa;
241         }
242     }
243
244     /**
245      * Returns the name of the crypto algorithm used for this key.
246      *
247      * @return string
248      */
249     public function getName()
250     {
251         return $this->alg;
252     }
253
254     /**
255      * Returns the name of a hash function to use for signing with this key.
256      *
257      * @return string
258      * @fixme is this used? doesn't seem to be called by name.
259      */
260     public function getHash()
261     {
262         switch ($this->alg) {
263
264         case 'RSA-SHA256':
265             return 'sha256';
266         }
267     }
268
269     /**
270      * Generate base64-encoded signature for the given byte string
271      * using our private key.
272      *
273      * @param string $bytes as raw byte string
274      * @return string base64-encoded signature
275      */
276     public function sign($bytes)
277     {
278         $sig = $this->privateKey->sign($bytes);
279         return Magicsig::base64_url_encode($sig);
280     }
281
282     /**
283      *
284      * @param string $signed_bytes as raw byte string
285      * @param string $signature as base64
286      * @return boolean
287      */
288     public function verify($signed_bytes, $signature)
289     {
290         $signature = Magicsig::base64_url_decode($signature);
291         return $this->publicKey->verify($signed_bytes, $signature);
292     }
293
294     /**
295      * URL-encoding-friendly base64 variant encoding.
296      *
297      * @param string $input
298      * @return string
299      */
300     public static function base64_url_encode($input)
301     {
302         return strtr(base64_encode($input), '+/', '-_');
303     }
304
305     /**
306      * URL-encoding-friendly base64 variant decoding.
307      *
308      * @param string $input
309      * @return string
310      */
311     public static function base64_url_decode($input)
312     {
313         return base64_decode(strtr($input, '-_', '+/'));
314     }
315 }