3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * A sample module to show best practices for StatusNet plugins
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.
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.
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/>.
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/
31 const ENCODING = 'base64url';
33 const NS = 'http://salmon-protocol.org/ns/magic-env';
35 private function normalizeUser($user_id)
37 if (substr($user_id, 0, 5) == 'http:' ||
38 substr($user_id, 0, 6) == 'https:' ||
39 substr($user_id, 0, 5) == 'acct:') {
43 if (strpos($user_id, '@') !== FALSE) {
44 return 'acct:' . $user_id;
47 return 'http://' . $user_id;
50 public function getKeyPair($signer_uri)
52 $disco = new Discovery();
55 $xrd = $disco->lookup($signer_uri);
56 } catch (Exception $e) {
60 if ($link = Discovery::getService($xrd->links, Magicsig::PUBLICKEYREL)) {
62 $parts = explode(',', $link['href']);
63 if (count($parts) == 2) {
66 // Backwards compatibility check for separator bug in 0.9.0
67 $parts = explode(';', $link['href']);
68 if (count($parts) == 2) {
79 throw new Exception(_m('Unable to locate signer public key.'));
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.
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'])));
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
105 public function signMessage($text, $mimetype, $keypair)
107 $signature_alg = Magicsig::fromString($keypair);
108 $armored_text = Magicsig::base64_url_encode($text);
110 'data' => $armored_text,
111 'encoding' => MagicEnvelope::ENCODING,
112 'data_type' => $mimetype,
114 'alg' => $signature_alg->getName()
117 $env['sig'] = $signature_alg->sign($this->signingText($env));
123 * Create an <me:env> XML representation of the envelope.
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
129 public function toXML($env) {
130 $xs = new XMLStringer();
132 $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::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');
139 $string = $xs->getString();
140 common_debug($string);
145 * Extract the contained XML payload, and insert a copy of the envelope
146 * signature data as an <me:provenance> section.
148 * @param array $env associative array with envelope data
149 * @return string representation of modified XML document
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
154 public function unfold($env)
156 $dom = new DOMDocument();
157 $dom->loadXML(Magicsig::base64_url_decode($env['data']));
159 if ($dom->documentElement->tagName != 'entry') {
163 $prov = $dom->createElementNS(MagicEnvelope::NS, 'me:provenance');
164 $prov->setAttribute('xmlns:me', MagicEnvelope::NS);
165 $data = $dom->createElementNS(MagicEnvelope::NS, 'me:data', $env['data']);
166 $data->setAttribute('type', $env['data_type']);
167 $prov->appendChild($data);
168 $enc = $dom->createElementNS(MagicEnvelope::NS, 'me:encoding', $env['encoding']);
169 $prov->appendChild($enc);
170 $alg = $dom->createElementNS(MagicEnvelope::NS, 'me:alg', $env['alg']);
171 $prov->appendChild($alg);
172 $sig = $dom->createElementNS(MagicEnvelope::NS, 'me:sig', $env['sig']);
173 $prov->appendChild($sig);
175 $dom->documentElement->appendChild($prov);
177 return $dom->saveXML();
181 * Find the author URI referenced in the given Atom entry.
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
186 * @fixme XML parsing failures will spew to error logs/output
188 public function getAuthor($text) {
189 $doc = new DOMDocument();
190 if (!$doc->loadXML($text)) {
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 $this->normalizeUser($uri->nodeValue);
206 * Check if the author in the Atom entry fragment claims to match
207 * the given identifier URI.
209 * @param string $text string containing Atom entry XML
210 * @param string $signer_uri
213 public function checkAuthor($text, $signer_uri)
215 return ($this->getAuthor($text) == $signer_uri);
219 * Attempt to verify cryptographic signing for parsed envelope data.
220 * Requires network access to retrieve public key referenced by the envelope signer.
222 * Details of failure conditions are dumped to output log and not exposed to caller.
224 * @param array $env array representation of magic envelope data, as returned from MagicEnvelope::parse()
227 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
229 public function verify($env)
231 if ($env['alg'] != 'RSA-SHA256') {
232 common_log(LOG_DEBUG, "Salmon error: bad algorithm");
236 if ($env['encoding'] != MagicEnvelope::ENCODING) {
237 common_log(LOG_DEBUG, "Salmon error: bad encoding");
241 $text = Magicsig::base64_url_decode($env['data']);
242 $signer_uri = $this->getAuthor($text);
245 $keypair = $this->getKeyPair($signer_uri);
246 } catch (Exception $e) {
247 common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
251 $verifier = Magicsig::fromString($keypair);
254 common_log(LOG_DEBUG, "Salmon error: unable to parse keypair");
258 return $verifier->verify($this->signingText($env), $env['sig']);
262 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
264 * @param string XML source
265 * @return mixed associative array of envelope data, or false on unrecognized input
267 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
268 * @fixme will spew errors to logs or output in case of XML parse errors
269 * @fixme may give fatal errors if some elements are missing or invalid XML
270 * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
272 public function parse($text)
274 $dom = DOMDocument::loadXML($text);
275 return $this->fromDom($dom);
279 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
281 * @param DOMDocument $dom
282 * @return mixed associative array of envelope data, or false on unrecognized input
284 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
285 * @fixme may give fatal errors if some elements are missing
287 public function fromDom($dom)
289 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'env')->item(0);
291 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'provenance')->item(0);
298 $data_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'data')->item(0);
299 $sig_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'sig')->item(0);
301 'data' => preg_replace('/\s/', '', $data_element->nodeValue),
302 'data_type' => $data_element->getAttribute('type'),
303 'encoding' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'encoding')->item(0)->nodeValue,
304 'alg' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'alg')->item(0)->nodeValue,
305 'sig' => preg_replace('/\s/', '', $sig_element->nodeValue),
311 * Variant of MagicEnvelope using the earlier signature form listed in the MagicEnvelope
312 * spec in early 2010; this was used in StatusNet up through 0.9.6, so for backwards compatiblity
313 * we still need to accept and sometimes send this format.
315 class MagicEnvelopeCompat extends MagicEnvelope {
318 * StatusNet through 0.9.6 used an earlier version of the MagicEnvelope spec
319 * which used only the input data, without the additional fields, as the plaintext
325 public function signingText($env) {