3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * A sample module to show best practices for StatusNet plugins
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.
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.
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/>.
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/
30 if (!defined('STATUSNET')) {
34 require_once 'Crypt/RSA.php';
36 class Magicsig extends Managed_DataObject
38 const PUBLICKEYREL = 'magic-public-key';
40 public $__table = 'magicsig';
43 * Key to user.id/profile.id for the local user whose key we're storing.
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.
59 * Crypto algorithm used for this key; currently only RSA-SHA256 is supported.
66 * Public RSA key; gets serialized in/out via $this->keypair string.
73 * PrivateRSA key; gets serialized in/out via $this->keypair string.
79 public function __construct($alg = 'RSA-SHA256')
85 * Fetch a Magicsig object from the cache or database on a field match.
91 static function getKV($k, $v=null)
93 $obj = parent::getKV($k, $v);
94 if ($obj instanceof Magicsig) {
95 $obj->importKeys(); // Loads Crypt_RSA objects etc.
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()),
110 public static function schemaDef()
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'),
118 'primary key' => array('user_id'),
119 'foreign keys' => array(
120 'magicsig_user_id_fkey' => array('profile', array('user_id' => 'id')),
126 * Save this keypair into the database.
128 * Overloads default insert behavior to encode the live key objects
129 * as a flat string for storage.
135 $this->keypair = $this->toString(true);
137 return parent::insert();
141 * Generate a new keypair for a local user and store in the database.
143 * Warning: this can be very slow on systems without the GMP module.
144 * Runtimes of 20-30 seconds are not unheard-of.
146 * @param User $user the local user (since we don't have remote private keys)
148 public static function generate(User $user, $bits=1024, $alg='RSA-SHA256')
150 $magicsig = new Magicsig($alg);
151 $magicsig->user_id = $user->id;
153 $rsa = new Crypt_RSA();
155 $keypair = $rsa->createKey($bits);
157 $magicsig->privateKey = new Crypt_RSA();
158 $magicsig->privateKey->loadKey($keypair['privatekey']);
160 $magicsig->publicKey = new Crypt_RSA();
161 $magicsig->publicKey->loadKey($keypair['publickey']);
163 $magicsig->insert(); // will do $this->keypair = $this->toString(true);
164 $magicsig->importKeys(); // seems it's necessary to re-read keys from text keypair
170 * Encode the keypair or public key as a string.
172 * @param boolean $full_pair set to true to include the private key.
175 public function toString($full_pair=false)
177 $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
178 $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
180 if ($full_pair && $this->privateKey instanceof Crypt_RSA && $this->privateKey->exponent->toBytes()) {
181 $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
184 return 'RSA.' . $mod . '.' . $exp . $private_exp;
188 * importKeys will load the object's keypair string, which initiates
189 * loadKey() and configures Crypt_RSA objects.
191 * @param string $keypair optional, otherwise the object's "keypair" property will be used
193 public function importKeys($keypair=null)
195 $this->keypair = $keypair===null ? $this->keypair : preg_replace('/\s+/', '', $keypair);
198 if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(\.([^\.]+))?/', $this->keypair, $matches)) {
199 common_debug('Magicsig error: RSA key not found in provided string.');
200 throw new ServerException('RSA key not found in keypair string.');
205 if (!empty($matches[4])) {
206 $private_exp = $matches[4];
208 $private_exp = false;
211 $this->loadKey($mod, $exp, 'public');
213 $this->loadKey($mod, $private_exp, 'private');
218 * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
219 * representing the give key (as mod/exponent pair).
221 * @param string $mod base64-encoded
222 * @param string $exp base64-encoded exponent
223 * @param string $type one of 'public' or 'private'
225 public function loadKey($mod, $exp, $type = 'public')
227 common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
229 $rsa = new Crypt_RSA();
230 $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
231 $rsa->setHash($this->getHash());
232 $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
233 $rsa->k = strlen($rsa->modulus->toBytes());
234 $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
236 if ($type == 'private') {
237 $this->privateKey = $rsa;
239 $this->publicKey = $rsa;
244 * Returns the name of the crypto algorithm used for this key.
248 public function getName()
254 * Returns the name of a hash function to use for signing with this key.
258 public function getHash()
260 switch ($this->alg) {
264 throw new ServerException('Unknown or unsupported hash algorithm for Salmon');
268 * Generate base64-encoded signature for the given byte string
269 * using our private key.
271 * @param string $bytes as raw byte string
272 * @return string base64url-encoded signature
274 public function sign($bytes)
276 $sig = $this->privateKey->sign($bytes);
277 if ($sig === false) {
278 throw new ServerException('Could not sign data');
280 return Magicsig::base64_url_encode($sig);
285 * @param string $signed_bytes as raw byte string
286 * @param string $signature as base64url encoded
289 public function verify($signed_bytes, $signature)
291 $signature = self::base64_url_decode($signature);
292 return $this->publicKey->verify($signed_bytes, $signature);
296 * URL-encoding-friendly base64 variant encoding.
298 * @param string $input
301 public static function base64_url_encode($input)
303 return strtr(base64_encode($input), '+/', '-_');
307 * URL-encoding-friendly base64 variant decoding.
309 * @param string $input
312 public static function base64_url_decode($input)
314 return base64_decode(strtr($input, '-_', '+/'));