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