]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/magicenvelope.php
checkAuthor not used anywhere
[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      * Attempt to verify cryptographic signing for parsed envelope data.
222      * Requires network access to retrieve public key referenced by the envelope signer.
223      *
224      * Details of failure conditions are dumped to output log and not exposed to caller.
225      *
226      * @param array $env array representation of magic envelope data, as returned from MagicEnvelope::parse()
227      * @return boolean
228      *
229      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
230      */
231     public function verify($env)
232     {
233         if ($env['alg'] != 'RSA-SHA256') {
234             common_log(LOG_DEBUG, "Salmon error: bad algorithm");
235             return false;
236         }
237
238         if ($env['encoding'] != MagicEnvelope::ENCODING) {
239             common_log(LOG_DEBUG, "Salmon error: bad encoding");
240             return false;
241         }
242
243         $text = Magicsig::base64_url_decode($env['data']);
244         $signer_uri = $this->getAuthor($text);
245
246         try {
247             $magicsig = $this->getKeyPair($signer_uri);
248         } catch (Exception $e) {
249             common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
250             return false;
251         }
252
253         return $magicsig->verify($this->signingText($env), $env['sig']);
254     }
255
256     /**
257      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
258      *
259      * @param string XML source
260      * @return mixed associative array of envelope data, or false on unrecognized input
261      *
262      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
263      * @fixme will spew errors to logs or output in case of XML parse errors
264      * @fixme may give fatal errors if some elements are missing or invalid XML
265      * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
266      */
267     public function parse($text)
268     {
269         $dom = DOMDocument::loadXML($text);
270         return $this->fromDom($dom);
271     }
272
273     /**
274      * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
275      *
276      * @param DOMDocument $dom
277      * @return mixed associative array of envelope data, or false on unrecognized input
278      *
279      * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
280      * @fixme may give fatal errors if some elements are missing
281      */
282     public function fromDom($dom)
283     {
284         $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'env')->item(0);
285         if (!$env_element) {
286             $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'provenance')->item(0);
287         }
288
289         if (!$env_element) {
290             return false;
291         }
292
293         $data_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'data')->item(0);
294         $sig_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'sig')->item(0);
295         return array(
296             'data' => preg_replace('/\s/', '', $data_element->nodeValue),
297             'data_type' => $data_element->getAttribute('type'),
298             'encoding' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'encoding')->item(0)->nodeValue,
299             'alg' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'alg')->item(0)->nodeValue,
300             'sig' => preg_replace('/\s/', '', $sig_element->nodeValue),
301         );
302     }
303 }
304
305 /**
306  * Variant of MagicEnvelope using the earlier signature form listed in the MagicEnvelope
307  * spec in early 2010; this was used in StatusNet up through 0.9.6, so for backwards compatiblity
308  * we still need to accept and sometimes send this format.
309  */
310 class MagicEnvelopeCompat extends MagicEnvelope {
311
312     /**
313      * StatusNet through 0.9.6 used an earlier version of the MagicEnvelope spec
314      * which used only the input data, without the additional fields, as the plaintext
315      * for signing.
316      *
317      * @param array $env
318      * @return string
319      */
320     public function signingText($env) {
321         return $env['data'];
322     }
323 }