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