]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/magicenvelope.php
Move around some code related to Magic_envelope and signing
[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() {
209         $xs = new XMLStringer();
210         $xs->startXML();
211         $xs->elementStart('me:env', array('xmlns:me' => self::NS));
212         $xs->element('me:data', array('type' => $this->data_type), $this->data);
213         $xs->element('me:encoding', null, $this->encoding);
214         $xs->element('me:alg', null, $this->alg);
215         $xs->element('me:sig', null, $this->getSignature());
216         $xs->elementEnd('me:env');
217
218         $string =  $xs->getString();
219         return $string;
220     }
221
222     /*
223      * Extract the contained XML payload, and insert a copy of the envelope
224      * signature data as an <me:provenance> section.
225      *
226      * @return DOMDocument of Atom entry
227      *
228      * @fixme in case of XML parsing errors, this will spew to the error log or output
229      */
230     public function getPayload()
231     {
232         $dom = new DOMDocument();
233         if (!$dom->loadXML(Magicsig::base64_url_decode($this->data))) {
234             throw new ServerException('Malformed XML in Salmon payload');
235         }
236
237         switch ($this->data_type) {
238         case 'application/atom+xml':
239             if ($dom->documentElement->namespaceURI !== Activity::ATOM
240                     || $dom->documentElement->tagName !== 'entry') {
241                 throw new ServerException(_m('Salmon post must be an Atom entry.'));
242             }
243             $prov = $dom->createElementNS(self::NS, 'me:provenance');
244             $prov->setAttribute('xmlns:me', self::NS);
245             $data = $dom->createElementNS(self::NS, 'me:data', $this->data);
246             $data->setAttribute('type', $this->data_type);
247             $prov->appendChild($data);
248             $enc = $dom->createElementNS(self::NS, 'me:encoding', $this->encoding);
249             $prov->appendChild($enc);
250             $alg = $dom->createElementNS(self::NS, 'me:alg', $this->alg);
251             $prov->appendChild($alg);
252             $sig = $dom->createElementNS(self::NS, 'me:sig', $this->getSignature());
253             $prov->appendChild($sig);
254     
255             $dom->documentElement->appendChild($prov);
256             break;
257         default:
258             throw new ServerException('Unknown Salmon payload data type');
259         }
260         return $dom;
261     }
262
263     public function getSignature()
264     {
265         return $this->sig;
266     }
267
268     /**
269      * Find the author URI referenced in the payload Atom entry.
270      *
271      * @return string URI for author
272      * @throws ServerException on failure
273      */
274     public function getAuthorUri() {
275         $doc = $this->getPayload();
276
277         $authors = $doc->documentElement->getElementsByTagName('author');
278         foreach ($authors as $author) {
279             $uris = $author->getElementsByTagName('uri');
280             foreach ($uris as $uri) {
281                 return $uri->nodeValue;
282             }
283         }
284         throw new ServerException('No author URI found in Salmon payload data');
285     }
286
287     /**
288      * Attempt to verify cryptographic signing for parsed envelope data.
289      * Requires network access to retrieve public key referenced by the envelope signer.
290      *
291      * Details of failure conditions are dumped to output log and not exposed to caller.
292      *
293      * @param Profile $profile profile used to get locally cached public signature key
294      *                         or if necessary perform discovery on.
295      *
296      * @return boolean
297      */
298     public function verify(Profile $profile)
299     {
300         if ($this->alg != 'RSA-SHA256') {
301             common_log(LOG_DEBUG, "Salmon error: bad algorithm");
302             return false;
303         }
304
305         if ($this->encoding != self::ENCODING) {
306             common_log(LOG_DEBUG, "Salmon error: bad encoding");
307             return false;
308         }
309
310         try {
311             $magicsig = $this->getKeyPair($profile, true);    // Do discovery too if necessary
312         } catch (Exception $e) {
313             common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
314             return false;
315         }
316
317         if (!$magicsig->verify($this->signingText(), $this->getSignature())) {
318             // TRANS: Client error when incoming salmon slap signature does not verify cryptographically.
319             throw new ClientException(_m('Salmon signature verification failed.'));
320         }
321         $this->setActor($profile);
322         return true;
323     }
324
325     /**
326      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
327      *
328      * @param DOMDocument $dom
329      * @return mixed associative array of envelope data, or false on unrecognized input
330      *
331      * @fixme may give fatal errors if some elements are missing
332      */
333     protected function fromDom(DOMDocument $dom)
334     {
335         $env_element = $dom->getElementsByTagNameNS(self::NS, 'env')->item(0);
336         if (!$env_element) {
337             $env_element = $dom->getElementsByTagNameNS(self::NS, 'provenance')->item(0);
338         }
339
340         if (!$env_element) {
341             return false;
342         }
343
344         $data_element = $env_element->getElementsByTagNameNS(self::NS, 'data')->item(0);
345         $sig_element = $env_element->getElementsByTagNameNS(self::NS, 'sig')->item(0);
346
347         $this->data      = preg_replace('/\s/', '', $data_element->nodeValue);
348         $this->data_type = $data_element->getAttribute('type');
349         $this->encoding  = $env_element->getElementsByTagNameNS(self::NS, 'encoding')->item(0)->nodeValue;
350         $this->alg       = $env_element->getElementsByTagNameNS(self::NS, 'alg')->item(0)->nodeValue;
351         $this->sig       = preg_replace('/\s/', '', $sig_element->nodeValue);
352         return true;
353     }
354
355     public function setActor(Profile $actor)
356     {
357         if ($this->actor instanceof Profile) {
358             throw new ServerException('Cannot set a new actor profile for MagicEnvelope object.');
359         }
360         $this->actor = $actor;
361     }
362
363     public function getActor()
364     {
365         if (!$this->actor instanceof Profile) {
366             throw new ServerException('No actor set for this magic envelope.');
367         }
368         return $this->actor;
369     }
370
371     /**
372      * Encode the given string as a signed MagicEnvelope XML document,
373      * using the keypair for the given local user profile. We can of
374      * course not sign a remote profile's slap, since we don't have the
375      * private key.
376      *
377      * Side effects: will create and store a keypair on-demand if one
378      * hasn't already been generated for this user. This can be very slow
379      * on some systems.
380      *
381      * @param string $text XML fragment to sign, assumed to be Atom
382      * @param User $user User who cryptographically signs $text
383      *
384      * @return MagicEnvelope object complete with signature
385      *
386      * @throws Exception on bad profile input or key generation problems
387      */
388     public static function signAsUser($text, User $user)
389     {
390         $magic_env = new MagicEnvelope(null, $user->getProfile());
391         $magic_env->signMessage($text, 'application/atom+xml');
392
393         return $magic_env;
394     }
395 }