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