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