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