]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/magicenvelope.php
MagicEnvelope class now throws exception on XRD fail
[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     private function normalizeUser($user_id)
36     {
37         if (substr($user_id, 0, 5) == 'http:' ||
38             substr($user_id, 0, 6) == 'https:' ||
39             substr($user_id, 0, 5) == 'acct:') {
40             return $user_id;
41         }
42
43         if (strpos($user_id, '@') !== FALSE) {
44             return 'acct:' . $user_id;
45         }
46
47         return 'http://' . $user_id;
48     }
49
50     /**
51      * Get the Salmon keypair from a URI, uses XRD Discovery etc.
52      *
53      * @return Magicsig with loaded keypair
54      */
55     public function getKeyPair($signer_uri)
56     {
57         $disco = new Discovery();
58
59         // Throws exception on lookup problems
60         $xrd = $disco->lookup($signer_uri);
61
62         $link = $xrd->get(Magicsig::PUBLICKEYREL);
63         if (is_null($link)) {
64             // TRANS: Exception.
65             throw new Exception(_m('Unable to locate signer public key.'));
66         }
67
68         // We have a public key element, let's hope it has proper key data.
69         $keypair = false;
70         $parts = explode(',', $link->href);
71         if (count($parts) == 2) {
72             $keypair = $parts[1];
73         } else {
74             // Backwards compatibility check for separator bug in 0.9.0
75             $parts = explode(';', $link->href);
76             if (count($parts) == 2) {
77                 $keypair = $parts[1];
78             }
79         }
80
81         if ($keypair === false) {
82             // For debugging clarity. Keypair did not pass count()-check above. 
83             // TRANS: Exception when public key was not properly formatted.
84             throw new Exception(_m('Incorrectly formatted public key element.'));
85         }
86
87         $magicsig = Magicsig::fromString($keypair);
88         if (!$magicsig instanceof Magicsig) {
89             common_debug('Salmon error: unable to parse keypair: '.var_export($keypair,true));
90             // TRANS: Exception when public key was properly formatted but not parsable.
91             throw new ServerException(_m('Retrieved Salmon keypair could not be parsed.'));
92         }
93
94         return $magicsig;
95     }
96
97     /**
98      * The current MagicEnvelope spec as used in StatusNet 0.9.7 and later
99      * includes both the original data and some signing metadata fields as
100      * the input plaintext for the signature hash.
101      *
102      * @param array $env
103      * @return string
104      */
105     public function signingText($env) {
106         return implode('.', array($env['data'], // this field is pre-base64'd
107                             Magicsig::base64_url_encode($env['data_type']),
108                             Magicsig::base64_url_encode($env['encoding']),
109                             Magicsig::base64_url_encode($env['alg'])));
110     }
111
112     /**
113      *
114      * @param <type> $text
115      * @param <type> $mimetype
116      * @param <type> $keypair
117      * @return array: associative array of envelope properties
118      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
119      */
120     public function signMessage($text, $mimetype, $keypair)
121     {
122         $signature_alg = Magicsig::fromString($keypair);
123         $armored_text = Magicsig::base64_url_encode($text);
124         $env = array(
125             'data' => $armored_text,
126             'encoding' => MagicEnvelope::ENCODING,
127             'data_type' => $mimetype,
128             'sig' => '',
129             'alg' => $signature_alg->getName()
130         );
131
132         $env['sig'] = $signature_alg->sign($this->signingText($env));
133
134         return $env;
135     }
136
137     /**
138      * Create an <me:env> XML representation of the envelope.
139      *
140      * @param array $env associative array with envelope data
141      * @return string representation of XML document
142      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
143      */
144     public function toXML($env) {
145         $xs = new XMLStringer();
146         $xs->startXML();
147         $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::NS));
148         $xs->element('me:data', array('type' => $env['data_type']), $env['data']);
149         $xs->element('me:encoding', null, $env['encoding']);
150         $xs->element('me:alg', null, $env['alg']);
151         $xs->element('me:sig', null, $env['sig']);
152         $xs->elementEnd('me:env');
153
154         $string =  $xs->getString();
155         common_debug($string);
156         return $string;
157     }
158
159     /**
160      * Extract the contained XML payload, and insert a copy of the envelope
161      * signature data as an <me:provenance> section.
162      *
163      * @param array $env associative array with envelope data
164      * @return string representation of modified XML document
165      *
166      * @fixme in case of XML parsing errors, this will spew to the error log or output
167      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
168      */
169     public function unfold($env)
170     {
171         $dom = new DOMDocument();
172         $dom->loadXML(Magicsig::base64_url_decode($env['data']));
173
174         if ($dom->documentElement->tagName != 'entry') {
175             return false;
176         }
177
178         $prov = $dom->createElementNS(MagicEnvelope::NS, 'me:provenance');
179         $prov->setAttribute('xmlns:me', MagicEnvelope::NS);
180         $data = $dom->createElementNS(MagicEnvelope::NS, 'me:data', $env['data']);
181         $data->setAttribute('type', $env['data_type']);
182         $prov->appendChild($data);
183         $enc = $dom->createElementNS(MagicEnvelope::NS, 'me:encoding', $env['encoding']);
184         $prov->appendChild($enc);
185         $alg = $dom->createElementNS(MagicEnvelope::NS, 'me:alg', $env['alg']);
186         $prov->appendChild($alg);
187         $sig = $dom->createElementNS(MagicEnvelope::NS, 'me:sig', $env['sig']);
188         $prov->appendChild($sig);
189
190         $dom->documentElement->appendChild($prov);
191
192         return $dom->saveXML();
193     }
194
195     /**
196      * Find the author URI referenced in the given Atom entry.
197      *
198      * @param string $text string containing Atom entry XML
199      * @return mixed URI string or false if XML parsing fails, or null if no author URI can be found
200      *
201      * @fixme XML parsing failures will spew to error logs/output
202      */
203     public function getAuthor($text) {
204         $doc = new DOMDocument();
205         if (!$doc->loadXML($text)) {
206             return FALSE;
207         }
208
209         if ($doc->documentElement->tagName == 'entry') {
210             $authors = $doc->documentElement->getElementsByTagName('author');
211             foreach ($authors as $author) {
212                 $uris = $author->getElementsByTagName('uri');
213                 foreach ($uris as $uri) {
214                     return $this->normalizeUser($uri->nodeValue);
215                 }
216             }
217         }
218     }
219
220     /**
221      * Check if the author in the Atom entry fragment claims to match
222      * the given identifier URI.
223      *
224      * @param string $text string containing Atom entry XML
225      * @param string $signer_uri
226      * @return boolean
227      */
228     public function checkAuthor($text, $signer_uri)
229     {
230         return ($this->getAuthor($text) == $signer_uri);
231     }
232
233     /**
234      * Attempt to verify cryptographic signing for parsed envelope data.
235      * Requires network access to retrieve public key referenced by the envelope signer.
236      *
237      * Details of failure conditions are dumped to output log and not exposed to caller.
238      *
239      * @param array $env array representation of magic envelope data, as returned from MagicEnvelope::parse()
240      * @return boolean
241      *
242      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
243      */
244     public function verify($env)
245     {
246         if ($env['alg'] != 'RSA-SHA256') {
247             common_log(LOG_DEBUG, "Salmon error: bad algorithm");
248             return false;
249         }
250
251         if ($env['encoding'] != MagicEnvelope::ENCODING) {
252             common_log(LOG_DEBUG, "Salmon error: bad encoding");
253             return false;
254         }
255
256         $text = Magicsig::base64_url_decode($env['data']);
257         $signer_uri = $this->getAuthor($text);
258
259         try {
260             $magicsig = $this->getKeyPair($signer_uri);
261         } catch (Exception $e) {
262             common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
263             return false;
264         }
265
266         return $magicsig->verify($this->signingText($env), $env['sig']);
267     }
268
269     /**
270      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
271      *
272      * @param string XML source
273      * @return mixed associative array of envelope data, or false on unrecognized input
274      *
275      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
276      * @fixme will spew errors to logs or output in case of XML parse errors
277      * @fixme may give fatal errors if some elements are missing or invalid XML
278      * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
279      */
280     public function parse($text)
281     {
282         $dom = DOMDocument::loadXML($text);
283         return $this->fromDom($dom);
284     }
285
286     /**
287      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
288      *
289      * @param DOMDocument $dom
290      * @return mixed associative array of envelope data, or false on unrecognized input
291      *
292      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
293      * @fixme may give fatal errors if some elements are missing
294      */
295     public function fromDom($dom)
296     {
297         $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'env')->item(0);
298         if (!$env_element) {
299             $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'provenance')->item(0);
300         }
301
302         if (!$env_element) {
303             return false;
304         }
305
306         $data_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'data')->item(0);
307         $sig_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'sig')->item(0);
308         return array(
309             'data' => preg_replace('/\s/', '', $data_element->nodeValue),
310             'data_type' => $data_element->getAttribute('type'),
311             'encoding' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'encoding')->item(0)->nodeValue,
312             'alg' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'alg')->item(0)->nodeValue,
313             'sig' => preg_replace('/\s/', '', $sig_element->nodeValue),
314         );
315     }
316 }
317
318 /**
319  * Variant of MagicEnvelope using the earlier signature form listed in the MagicEnvelope
320  * spec in early 2010; this was used in StatusNet up through 0.9.6, so for backwards compatiblity
321  * we still need to accept and sometimes send this format.
322  */
323 class MagicEnvelopeCompat extends MagicEnvelope {
324
325     /**
326      * StatusNet through 0.9.6 used an earlier version of the MagicEnvelope spec
327      * which used only the input data, without the additional fields, as the plaintext
328      * for signing.
329      *
330      * @param array $env
331      * @return string
332      */
333     public function signingText($env) {
334         return $env['data'];
335     }
336 }