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