Don't accept non-objects before testing with "instanceof".
[quix0rs-gnu-social.git] / plugins / OStatus / lib / magicenvelope.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 class MagicEnvelope
30 {
31     const ENCODING = 'base64url';
32
33     const NS = 'http://salmon-protocol.org/ns/magic-env';
34
35     protected $actor = null;    // Profile of user who has signed the envelope
36
37     protected $data      = null;    // When stored here it is _always_ base64url encoded
38     protected $data_type = null;
39     protected $encoding  = null;
40     protected $alg       = null;
41     protected $sig       = null;
42
43     /**
44      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
45      *
46      * @param string XML source
47      * @return mixed associative array of envelope data, or false on unrecognized input
48      *
49      * @fixme will spew errors to logs or output in case of XML parse errors
50      * @fixme may give fatal errors if some elements are missing or invalid XML
51      * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
52      */
53     public function __construct($xml=null, Profile $actor=null) {
54         if (!empty($xml)) {
55             $dom = new DOMDocument();
56             if (!$dom->loadXML($xml)) {
57                 throw new ServerException('Tried to load malformed XML as DOM');
58             } elseif (!$this->fromDom($dom)) {
59                 throw new ServerException('Could not load MagicEnvelope from DOM');
60             }
61         } elseif ($actor instanceof Profile) {
62             // So far we only allow setting with _either_ $xml _or_ $actor as that's
63             // all our circumstances require. But it may be confusing for new developers.
64             // The idea is that feeding XML must be followed by interpretation and then
65             // running $magic_env->verify($profile), just as in SalmonAction->prepare(...)
66             // and supplying an $actor (which right now has to be a User) will require
67             // defining the $data, $data_type etc. attributes manually afterwards before
68             // signing the envelope..
69             $this->setActor($actor);
70         }
71     }
72
73     /**
74      * Retrieve Salmon keypair first by checking local database, but
75      * if it's not found, attempt discovery if it has been requested.
76      *
77      * @param Profile $profile      The profile we're looking up keys for.
78      * @param boolean $discovery    Network discovery if no local cache?
79      */
80     public function getKeyPair(Profile $profile, $discovery=false) {
81         if (!$profile->isLocal()) common_debug('Getting magic-public-key for non-local profile id=='.$profile->getID());
82         $magicsig = Magicsig::getKV('user_id', $profile->getID());
83
84         if ($discovery && !$magicsig instanceof Magicsig) {
85             if (!$profile->isLocal()) common_debug('magic-public-key not found, will do discovery for profile id=='.$profile->getID());
86             // Throws exception on failure, but does not try to _load_ the keypair string.
87             $keypair = $this->discoverKeyPair($profile);
88
89             $magicsig = new Magicsig();
90             $magicsig->user_id = $profile->getID();
91             $magicsig->importKeys($keypair);
92             // save the public key for this profile in our database.
93             // TODO: If the profile generates a new key remotely, we must be able to replace
94             //       this (of course after callback-verification).
95             $magicsig->insert();
96         } elseif (!$magicsig instanceof Magicsig) { // No discovery request, so we'll give up.
97             throw new ServerException(sprintf('No public key found for profile (id==%d)', $profile->id));
98         }
99
100         assert($magicsig->publicKey instanceof Crypt_RSA);
101
102         return $magicsig;
103     }
104
105     /**
106      * Get the Salmon keypair from a URI, uses XRD Discovery etc. Reasonably
107      * you'll only get the public key ;)
108      *
109      * The string will (hopefully) be formatted as described in Magicsig specification:
110      * https://salmon-protocol.googlecode.com/svn/trunk/draft-panzer-magicsig-01.html#anchor13
111      *
112      * @return string formatted as Magicsig keypair
113      */
114     public function discoverKeyPair(Profile $profile)
115     {
116         $signer_uri = $profile->getUri();
117         if (empty($signer_uri)) {
118             throw new ServerException(sprintf('Profile missing URI (id==%d)', $profile->getID()));
119         }
120
121         $disco = new Discovery();
122
123         // Throws exception on lookup problems
124         try {
125             $xrd = $disco->lookup($signer_uri);
126         } catch (Exception $e) {
127             // Diaspora seems to require us to request the acct: uri
128             $xrd = $disco->lookup($profile->getAcctUri());
129         }
130
131         common_debug('Will try to find magic-public-key from XRD of profile id=='.$profile->getID());
132         $pubkey = null;
133         if (Event::handle('MagicsigPublicKeyFromXRD', array($xrd, &$pubkey))) {
134             $link = $xrd->get(Magicsig::PUBLICKEYREL);
135             if (is_null($link)) {
136                 // TRANS: Exception.
137                 throw new Exception(_m('Unable to locate signer public key.'));
138             }
139             $pubkey = $link->href;
140         }
141         if (empty($pubkey)) {
142             throw new ServerException('Empty Magicsig public key. A bug?');
143         }
144
145         // We have a public key element, let's hope it has proper key data.
146         $keypair = false;
147         $parts = explode(',', $pubkey);
148         if (count($parts) == 2) {
149             $keypair = $parts[1];
150         } else {
151             // Backwards compatibility check for separator bug in 0.9.0
152             $parts = explode(';', $pubkey);
153             if (count($parts) == 2) {
154                 $keypair = $parts[1];
155             }
156         }
157
158         if ($keypair === false) {
159             // For debugging clarity. Keypair did not pass count()-check above. 
160             // TRANS: Exception when public key was not properly formatted.
161             throw new Exception(_m('Incorrectly formatted public key element.'));
162         }
163
164         return $keypair;
165     }
166
167     /**
168      * The current MagicEnvelope spec as used in StatusNet 0.9.7 and later
169      * includes both the original data and some signing metadata fields as
170      * the input plaintext for the signature hash.
171      *
172      * @return string
173      */
174     public function signingText() {
175         return implode('.', array($this->data, // this field is pre-base64'd
176                             Magicsig::base64_url_encode($this->data_type),
177                             Magicsig::base64_url_encode($this->encoding),
178                             Magicsig::base64_url_encode($this->alg)));
179     }
180
181     /**
182      *
183      * @param <type> $text
184      * @param <type> $mimetype
185      * @param Magicsig $magicsig    Magicsig with private key available.
186      *
187      * @return MagicEnvelope object with all properties set
188      *
189      * @throws Exception of various kinds on signing failure
190      */
191     public function signMessage($text, $mimetype)
192     {
193         if (!$this->actor instanceof Profile) {
194             throw new ServerException('No profile to sign message with is set.');
195         } elseif (!$this->actor->isLocal()) {
196             throw new ServerException('Cannot sign magic envelopes with remote users since we have no private key.');
197         }
198
199         // Find already stored key
200         $magicsig = Magicsig::getKV('user_id', $this->actor->getID());
201         if (!$magicsig instanceof Magicsig) {
202             // and if it doesn't exist, it is time to create one!
203             $magicsig = Magicsig::generate($this->actor->getUser());
204         }
205         assert($magicsig instanceof Magicsig);
206         assert($magicsig->privateKey instanceof Crypt_RSA);
207
208         // Prepare text and metadata for signing
209         $this->data = Magicsig::base64_url_encode($text);
210         $this->data_type = $mimetype;
211         $this->encoding  = self::ENCODING;
212         $this->alg       = $magicsig->getName();
213
214         // Get the actual signature
215         $this->sig = $magicsig->sign($this->signingText());
216     }
217
218     /**
219      * Create an <me:env> XML representation of the envelope.
220      *
221      * @return string representation of XML document
222      */
223     public function toXML(Profile $target=null, $flavour=null) {
224         $xs = new XMLStringer();
225         $xs->startXML();    // header, to point out it's not HTML or anything...
226         if (Event::handle('StartMagicEnvelopeToXML', array($this, $xs, $flavour, $target))) {
227             // fall back to our default, normal Magic Envelope XML.
228             // the $xs element _may_ have had elements added, or could get in the end event
229             $xs->elementStart('me:env', array('xmlns:me' => self::NS));
230             $xs->element('me:data', array('type' => $this->data_type), $this->data);
231             $xs->element('me:encoding', null, $this->encoding);
232             $xs->element('me:alg', null, $this->alg);
233             $xs->element('me:sig', null, $this->getSignature());
234             $xs->elementEnd('me:env');
235
236             Event::handle('EndMagicEnvelopeToXML', array($this, $xs, $flavour, $target));
237         }
238         return $xs->getString();
239     }
240
241     /*
242      * Extract the contained XML payload, and insert a copy of the envelope
243      * signature data as an <me:provenance> section.
244      *
245      * @return DOMDocument of Atom entry
246      *
247      * @fixme in case of XML parsing errors, this will spew to the error log or output
248      */
249     public function getPayload()
250     {
251         $dom = new DOMDocument();
252         if (!$dom->loadXML(Magicsig::base64_url_decode($this->data))) {
253             throw new ServerException('Malformed XML in Salmon payload');
254         }
255
256         switch ($this->data_type) {
257         case 'application/atom+xml':
258             if ($dom->documentElement->namespaceURI !== Activity::ATOM
259                     || $dom->documentElement->tagName !== 'entry') {
260                 throw new ServerException(_m('Salmon post must be an Atom entry.'));
261             }
262             $prov = $dom->createElementNS(self::NS, 'me:provenance');
263             $prov->setAttribute('xmlns:me', self::NS);
264             $data = $dom->createElementNS(self::NS, 'me:data', $this->data);
265             $data->setAttribute('type', $this->data_type);
266             $prov->appendChild($data);
267             $enc = $dom->createElementNS(self::NS, 'me:encoding', $this->encoding);
268             $prov->appendChild($enc);
269             $alg = $dom->createElementNS(self::NS, 'me:alg', $this->alg);
270             $prov->appendChild($alg);
271             $sig = $dom->createElementNS(self::NS, 'me:sig', $this->getSignature());
272             $prov->appendChild($sig);
273     
274             $dom->documentElement->appendChild($prov);
275             break;
276         default:
277             throw new ServerException('Unknown Salmon payload data type');
278         }
279         return $dom;
280     }
281
282     public function getSignature()
283     {
284         if (empty($this->sig)) {
285             throw new ServerException('You must first call signMessage before getSignature');
286         }
287         return $this->sig;
288     }
289
290     public function getSignatureAlgorithm()
291     {
292         return $this->alg;
293     }
294
295     public function getData()
296     {
297         return $this->data;
298     }
299
300     public function getDataType()
301     {
302         return $this->data_type;
303     }
304
305     public function getEncoding()
306     {
307         return $this->encoding;
308     }
309
310     /**
311      * Find the author URI referenced in the payload Atom entry.
312      *
313      * @return string URI for author
314      * @throws ServerException on failure
315      */
316     public function getAuthorUri() {
317         $doc = $this->getPayload();
318
319         $authors = $doc->documentElement->getElementsByTagName('author');
320         foreach ($authors as $author) {
321             $uris = $author->getElementsByTagName('uri');
322             foreach ($uris as $uri) {
323                 return $uri->nodeValue;
324             }
325         }
326         throw new ServerException('No author URI found in Salmon payload data');
327     }
328
329     /**
330      * Attempt to verify cryptographic signing for parsed envelope data.
331      * Requires network access to retrieve public key referenced by the envelope signer.
332      *
333      * Details of failure conditions are dumped to output log and not exposed to caller.
334      *
335      * @param Profile $profile profile used to get locally cached public signature key
336      *                         or if necessary perform discovery on.
337      *
338      * @return boolean
339      */
340     public function verify(Profile $profile)
341     {
342         if ($this->alg != 'RSA-SHA256') {
343             common_debug("Salmon error: bad algorithm");
344             return false;
345         }
346
347         if ($this->encoding != self::ENCODING) {
348             common_debug("Salmon error: bad encoding");
349             return false;
350         }
351
352         try {
353             $magicsig = $this->getKeyPair($profile, true);    // Do discovery too if necessary
354         } catch (Exception $e) {
355             common_debug("Salmon error: ".$e->getMessage());
356             return false;
357         }
358
359         if (!$magicsig->verify($this->signingText(), $this->getSignature())) {
360             // TRANS: Client error when incoming salmon slap signature does not verify cryptographically.
361             throw new ClientException(_m('Salmon signature verification failed.'));
362         }
363         $this->setActor($profile);
364         return true;
365     }
366
367     /**
368      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
369      *
370      * @param DOMDocument $dom
371      * @return mixed associative array of envelope data, or false on unrecognized input
372      *
373      * @fixme may give fatal errors if some elements are missing
374      */
375     protected function fromDom(DOMDocument $dom)
376     {
377         $env_element = $dom->getElementsByTagNameNS(self::NS, 'env')->item(0);
378         if (!$env_element) {
379             $env_element = $dom->getElementsByTagNameNS(self::NS, 'provenance')->item(0);
380         }
381
382         if (!$env_element) {
383             return false;
384         }
385
386         $data_element = $env_element->getElementsByTagNameNS(self::NS, 'data')->item(0);
387         $sig_element = $env_element->getElementsByTagNameNS(self::NS, 'sig')->item(0);
388
389         $this->data      = preg_replace('/\s/', '', $data_element->nodeValue);
390         $this->data_type = $data_element->getAttribute('type');
391         $this->encoding  = $env_element->getElementsByTagNameNS(self::NS, 'encoding')->item(0)->nodeValue;
392         $this->alg       = $env_element->getElementsByTagNameNS(self::NS, 'alg')->item(0)->nodeValue;
393         $this->sig       = preg_replace('/\s/', '', $sig_element->nodeValue);
394         return true;
395     }
396
397     public function setActor(Profile $actor)
398     {
399         if ($this->actor instanceof Profile) {
400             throw new ServerException('Cannot set a new actor profile for MagicEnvelope object.');
401         }
402         $this->actor = $actor;
403     }
404
405     public function getActor()
406     {
407         if (!$this->actor instanceof Profile) {
408             throw new ServerException('No actor set for this magic envelope.');
409         }
410         return $this->actor;
411     }
412
413     /**
414      * Encode the given string as a signed MagicEnvelope XML document,
415      * using the keypair for the given local user profile. We can of
416      * course not sign a remote profile's slap, since we don't have the
417      * private key.
418      *
419      * Side effects: will create and store a keypair on-demand if one
420      * hasn't already been generated for this user. This can be very slow
421      * on some systems.
422      *
423      * @param string $text XML fragment to sign, assumed to be Atom
424      * @param User $user User who cryptographically signs $text
425      *
426      * @return MagicEnvelope object complete with signature
427      *
428      * @throws Exception on bad profile input or key generation problems
429      */
430     public static function signAsUser($text, User $user)
431     {
432         $magic_env = new MagicEnvelope(null, $user->getProfile());
433         $magic_env->signMessage($text, 'application/atom+xml');
434
435         return $magic_env;
436     }
437 }