]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
Magicsig importKeys finetuning and getHash() use
[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 ($obj instanceof Magicsig) {
95             $obj->importKeys(); // Loads Crypt_RSA objects etc.
96
97             // Throw out a big fat warning for keys of less than 1024 bits. (
98             // The only case these show up in would be imported or
99             // legacy very-old-StatusNet generated keypairs.
100             if (strlen($obj->publicKey->modulus->toBits()) < 1024) {
101                 common_log(LOG_WARNING, sprintf('Salmon key with <1024 bits (%d) belongs to profile with id==%d',
102                                             strlen($obj->publicKey->modulus->toBits()),
103                                             $obj->user_id));
104             }
105         }
106
107         return $obj;
108     }
109
110     public static function schemaDef()
111     {
112         return array(
113             'fields' => array(
114                 'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user id'),
115                 'keypair' => array('type' => 'text', 'description' => 'keypair text representation'),
116                 'alg' => array('type' => 'varchar', 'length' => 64, 'description' => 'algorithm'),
117             ),
118             'primary key' => array('user_id'),
119             'foreign keys' => array(
120                 'magicsig_user_id_fkey' => array('profile', array('user_id' => 'id')),
121             ),
122         );
123     }
124
125     /**
126      * Save this keypair into the database.
127      *
128      * Overloads default insert behavior to encode the live key objects
129      * as a flat string for storage.
130      *
131      * @return mixed
132      */
133     function insert()
134     {
135         $this->keypair = $this->toString();
136
137         return parent::insert();
138     }
139
140     /**
141      * Generate a new keypair for a local user and store in the database.
142      *
143      * Warning: this can be very slow on systems without the GMP module.
144      * Runtimes of 20-30 seconds are not unheard-of.
145      *
146      * @param int $user_id id of local user we're creating a key for
147      */
148     public function generate($user_id, $bits=1024)
149     {
150         $rsa = new Crypt_RSA();
151
152         $keypair = $rsa->createKey($bits);
153
154         $this->privateKey = new Crypt_RSA();
155         $this->privateKey->loadKey($keypair['privatekey']);
156
157         $this->publicKey = new Crypt_RSA();
158         $this->publicKey->loadKey($keypair['publickey']);
159
160         $this->user_id = $user_id;
161         $this->insert();
162     }
163
164     /**
165      * Encode the keypair or public key as a string.
166      *
167      * @param boolean $full_pair set to false to leave out the private key.
168      * @return string
169      */
170     public function toString($full_pair = true)
171     {
172         $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
173         $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
174         $private_exp = '';
175         if ($full_pair && $this->privateKey->exponent->toBytes()) {
176             $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
177         }
178
179         return 'RSA.' . $mod . '.' . $exp . $private_exp;
180     }
181
182     /**
183      * Decode a string representation of an RSA public key or keypair
184      * as a Magicsig object which can be used to sign or verify.
185      *
186      * @param string $text
187      * @return Magicsig
188      */
189     public static function fromString($text)
190     {
191         $magic_sig = new Magicsig();
192
193         // remove whitespace
194         $text = preg_replace('/\s+/', '', $text);
195         $magic_sig->importKeys($text);
196
197         // Please note this object will be missing the user_id field
198         return $magic_sig;
199     }
200
201     /**
202      * importKeys will load the object's keypair string, which initiates
203      * loadKey() and configures Crypt_RSA objects.
204      *
205      * @param string $keypair optional, otherwise the object's "keypair" property will be used
206      */
207     public function importKeys($keypair=null)
208     {
209         $keypair = $keypair ?: $this->keypair;
210
211         // parse components
212         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(\.([^\.]+))?/', $keypair, $matches)) {
213             common_debug('Magicsig error: RSA key not found in provided string.');
214             throw new ServerException('RSA key not found in keypair string.');
215         }
216
217         $mod = $matches[1];
218         $exp = $matches[2];
219         if (!empty($matches[4])) {
220             $private_exp = $matches[4];
221         } else {
222             $private_exp = false;
223         }
224
225         $this->loadKey($mod, $exp, 'public');
226         if ($private_exp) {
227             $this->loadKey($mod, $private_exp, 'private');
228         }
229     }
230
231     /**
232      * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
233      * representing the give key (as mod/exponent pair).
234      *
235      * @param string $mod base64-encoded
236      * @param string $exp base64-encoded exponent
237      * @param string $type one of 'public' or 'private'
238      */
239     public function loadKey($mod, $exp, $type = 'public')
240     {
241         common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
242
243         $rsa = new Crypt_RSA();
244         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
245         $rsa->setHash($this->getHash());
246         $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
247         $rsa->k = strlen($rsa->modulus->toBytes());
248         $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
249
250         if ($type == 'private') {
251             $this->privateKey = $rsa;
252         } else {
253             $this->publicKey = $rsa;
254         }
255     }
256
257     /**
258      * Returns the name of the crypto algorithm used for this key.
259      *
260      * @return string
261      */
262     public function getName()
263     {
264         return $this->alg;
265     }
266
267     /**
268      * Returns the name of a hash function to use for signing with this key.
269      *
270      * @return string
271      */
272     public function getHash()
273     {
274         switch ($this->alg) {
275         case 'RSA-SHA256':
276             return 'sha256';
277         }
278         throw new ServerException('Unknown or unsupported hash algorithm for Salmon');
279     }
280
281     /**
282      * Generate base64-encoded signature for the given byte string
283      * using our private key.
284      *
285      * @param string $bytes as raw byte string
286      * @return string base64url-encoded signature
287      */
288     public function sign($bytes)
289     {
290         $sig = $this->privateKey->sign($bytes);
291         if ($sig === false) {
292             throw new ServerException('Could not sign data');
293         }
294         return Magicsig::base64_url_encode($sig);
295     }
296
297     /**
298      *
299      * @param string $signed_bytes as raw byte string
300      * @param string $signature as base64url encoded
301      * @return boolean
302      */
303     public function verify($signed_bytes, $signature)
304     {
305         $signature = self::base64_url_decode($signature);
306         return $this->publicKey->verify($signed_bytes, $signature);
307     }
308
309     /**
310      * URL-encoding-friendly base64 variant encoding.
311      *
312      * @param string $input
313      * @return string
314      */
315     public static function base64_url_encode($input)
316     {
317         return strtr(base64_encode($input), '+/', '-_');
318     }
319
320     /**
321      * URL-encoding-friendly base64 variant decoding.
322      *
323      * @param string $input
324      * @return string
325      */
326     public static function base64_url_decode($input)
327     {
328         return base64_decode(strtr($input, '-_', '+/'));
329     }
330 }