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