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