]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
Check for 0.9.0 bad keys from old Crypt_RSA library
[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 class Magicsig extends Memcached_DataObject
31 {
32
33     const PUBLICKEYREL = 'magic-public-key';
34     
35     public $__table = 'magicsig';
36
37     public $user_id;
38     public $keypair;
39     public $alg;
40     
41     public $publicKey;
42     public $privateKey;
43     
44     public function __construct($alg = 'RSA-SHA256')
45     {
46         $this->alg = $alg;
47     }
48     
49     public /*static*/ function staticGet($k, $v=null)
50     {
51         $obj =  parent::staticGet(__CLASS__, $k, $v);
52         if (!empty($obj)) {
53             $obj = Magicsig::fromString($obj->keypair);
54
55             // Double check keys: Crypt_RSA did not
56             // consistently generate good keypairs.
57             // We've also moved to 1024 bit keys.
58             if (strlen($obj->publicKey->modulus->toBits()) != 1024) {
59                 $obj->delete();
60                 return false;
61             }
62         }
63
64         return $obj;
65     }
66
67
68     function table()
69     {
70         return array(
71             'user_id' => DB_DATAOBJECT_INT,
72             'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
73             'alg'     => DB_DATAOBJECT_STR
74         );
75     }
76
77     static function schemaDef()
78     {
79         return array(new ColumnDef('user_id', 'integer',
80                                    null, false, 'PRI'),
81                      new ColumnDef('keypair', 'text',
82                                    false, false),
83                      new ColumnDef('alg', 'varchar',
84                                    64, false));
85     }
86
87
88     function keys()
89     {
90         return array_keys($this->keyTypes());
91     }
92
93     function keyTypes()
94     {
95         return array('user_id' => 'K');
96     }
97
98     function sequenceKey() {
99         return array(false, false, false);
100     }
101
102     function insert()
103     {
104         $this->keypair = $this->toString();
105
106         return parent::insert();
107     }
108
109     public function generate($user_id)
110     {
111         $rsa = new SafeCrypt_RSA();
112         
113         $keypair = $rsa->createKey();
114
115         $rsa->loadKey($keypair['privatekey']);
116
117         $this->privateKey = new SafeCrypt_RSA();
118         $this->privateKey->loadKey($keypair['privatekey']);
119
120         $this->publicKey = new SafeCrypt_RSA();
121         $this->publicKey->loadKey($keypair['publickey']);
122         
123         $this->user_id = $user_id;
124         $this->insert();
125     }
126
127
128     public function toString($full_pair = true)
129     {
130         $mod = base64_url_encode($this->publicKey->modulus->toBytes());
131         $exp = base64_url_encode($this->publicKey->exponent->toBytes());
132         $private_exp = '';
133         if ($full_pair && $this->privateKey->exponent->toBytes()) {
134             $private_exp = '.' . base64_url_encode($this->privateKey->exponent->toBytes());
135         }
136
137         return 'RSA.' . $mod . '.' . $exp . $private_exp; 
138     }
139     
140     public static function fromString($text)
141     {
142         $magic_sig = new Magicsig();
143         
144         // remove whitespace
145         $text = preg_replace('/\s+/', '', $text);
146
147         // parse components
148         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
149             return false;
150         }
151         
152         $mod = $matches[1];
153         $exp = $matches[2];
154         if (!empty($matches[4])) {
155             $private_exp = $matches[4];
156         } else {
157             $private_exp = false;
158         }
159
160         $magic_sig->loadKey($mod, $exp, 'public');
161         if ($private_exp) {
162             $magic_sig->loadKey($mod, $private_exp, 'private');
163         }
164
165         return $magic_sig;
166     }
167
168     public function loadKey($mod, $exp, $type = 'public')
169     {
170         common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
171
172         $rsa = new SafeCrypt_RSA();
173         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
174         $rsa->setHash('sha256');
175         $rsa->modulus = new Math_BigInteger(base64_url_decode($mod), 256);
176         $rsa->k = strlen($rsa->modulus->toBytes());
177         $rsa->exponent = new Math_BigInteger(base64_url_decode($exp), 256);
178
179         if ($type == 'private') {
180             $this->privateKey = $rsa;
181         } else {
182             $this->publicKey = $rsa;
183         }
184     }
185     
186     public function getName()
187     {
188         return $this->alg;
189     }
190
191     public function getHash()
192     {
193         switch ($this->alg) {
194
195         case 'RSA-SHA256':
196             return 'sha256';
197         }
198
199     }
200     
201     public function sign($bytes)
202     {
203         $sig = $this->privateKey->sign($bytes);
204         return base64_url_encode($sig);
205     }
206
207     public function verify($signed_bytes, $signature)
208     {
209         $signature = base64_url_decode($signature);
210         return $this->publicKey->verify($signed_bytes, $signature);
211     }
212         
213 }
214
215 function base64_url_encode($input)
216 {
217     return strtr(base64_encode($input), '+/', '-_');
218 }
219
220 function base64_url_decode($input)
221 {
222     return base64_decode(strtr($input, '-_', '+/'));
223 }