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