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) {
59 $link = $xrd->get(Magicsig::PUBLICKEYREL);
60 if (!is_null($link)) {
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) {
78 throw new Exception(_m('Unable to locate signer public key.'));
82 * The current MagicEnvelope spec as used in StatusNet 0.9.7 and later
83 * includes both the original data and some signing metadata fields as
84 * the input plaintext for the signature hash.
89 public function signingText($env) {
90 return implode('.', array($env['data'], // this field is pre-base64'd
91 Magicsig::base64_url_encode($env['data_type']),
92 Magicsig::base64_url_encode($env['encoding']),
93 Magicsig::base64_url_encode($env['alg'])));
99 * @param <type> $mimetype
100 * @param <type> $keypair
101 * @return array: associative array of envelope properties
102 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
104 public function signMessage($text, $mimetype, $keypair)
106 $signature_alg = Magicsig::fromString($keypair);
107 $armored_text = Magicsig::base64_url_encode($text);
109 'data' => $armored_text,
110 'encoding' => MagicEnvelope::ENCODING,
111 'data_type' => $mimetype,
113 'alg' => $signature_alg->getName()
116 $env['sig'] = $signature_alg->sign($this->signingText($env));
122 * Create an <me:env> XML representation of the envelope.
124 * @param array $env associative array with envelope data
125 * @return string representation of XML document
126 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
128 public function toXML($env) {
129 $xs = new XMLStringer();
131 $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::NS));
132 $xs->element('me:data', array('type' => $env['data_type']), $env['data']);
133 $xs->element('me:encoding', null, $env['encoding']);
134 $xs->element('me:alg', null, $env['alg']);
135 $xs->element('me:sig', null, $env['sig']);
136 $xs->elementEnd('me:env');
138 $string = $xs->getString();
139 common_debug($string);
144 * Extract the contained XML payload, and insert a copy of the envelope
145 * signature data as an <me:provenance> section.
147 * @param array $env associative array with envelope data
148 * @return string representation of modified XML document
150 * @fixme in case of XML parsing errors, this will spew to the error log or output
151 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
153 public function unfold($env)
155 $dom = new DOMDocument();
156 $dom->loadXML(Magicsig::base64_url_decode($env['data']));
158 if ($dom->documentElement->tagName != 'entry') {
162 $prov = $dom->createElementNS(MagicEnvelope::NS, 'me:provenance');
163 $prov->setAttribute('xmlns:me', MagicEnvelope::NS);
164 $data = $dom->createElementNS(MagicEnvelope::NS, 'me:data', $env['data']);
165 $data->setAttribute('type', $env['data_type']);
166 $prov->appendChild($data);
167 $enc = $dom->createElementNS(MagicEnvelope::NS, 'me:encoding', $env['encoding']);
168 $prov->appendChild($enc);
169 $alg = $dom->createElementNS(MagicEnvelope::NS, 'me:alg', $env['alg']);
170 $prov->appendChild($alg);
171 $sig = $dom->createElementNS(MagicEnvelope::NS, 'me:sig', $env['sig']);
172 $prov->appendChild($sig);
174 $dom->documentElement->appendChild($prov);
176 return $dom->saveXML();
180 * Find the author URI referenced in the given Atom entry.
182 * @param string $text string containing Atom entry XML
183 * @return mixed URI string or false if XML parsing fails, or null if no author URI can be found
185 * @fixme XML parsing failures will spew to error logs/output
187 public function getAuthor($text) {
188 $doc = new DOMDocument();
189 if (!$doc->loadXML($text)) {
193 if ($doc->documentElement->tagName == 'entry') {
194 $authors = $doc->documentElement->getElementsByTagName('author');
195 foreach ($authors as $author) {
196 $uris = $author->getElementsByTagName('uri');
197 foreach ($uris as $uri) {
198 return $this->normalizeUser($uri->nodeValue);
205 * Check if the author in the Atom entry fragment claims to match
206 * the given identifier URI.
208 * @param string $text string containing Atom entry XML
209 * @param string $signer_uri
212 public function checkAuthor($text, $signer_uri)
214 return ($this->getAuthor($text) == $signer_uri);
218 * Attempt to verify cryptographic signing for parsed envelope data.
219 * Requires network access to retrieve public key referenced by the envelope signer.
221 * Details of failure conditions are dumped to output log and not exposed to caller.
223 * @param array $env array representation of magic envelope data, as returned from MagicEnvelope::parse()
226 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
228 public function verify($env)
230 if ($env['alg'] != 'RSA-SHA256') {
231 common_log(LOG_DEBUG, "Salmon error: bad algorithm");
235 if ($env['encoding'] != MagicEnvelope::ENCODING) {
236 common_log(LOG_DEBUG, "Salmon error: bad encoding");
240 $text = Magicsig::base64_url_decode($env['data']);
241 $signer_uri = $this->getAuthor($text);
244 $keypair = $this->getKeyPair($signer_uri);
245 } catch (Exception $e) {
246 common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
250 $verifier = Magicsig::fromString($keypair);
253 common_log(LOG_DEBUG, "Salmon error: unable to parse keypair");
257 return $verifier->verify($this->signingText($env), $env['sig']);
261 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
263 * @param string XML source
264 * @return mixed associative array of envelope data, or false on unrecognized input
266 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
267 * @fixme will spew errors to logs or output in case of XML parse errors
268 * @fixme may give fatal errors if some elements are missing or invalid XML
269 * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
271 public function parse($text)
273 $dom = DOMDocument::loadXML($text);
274 return $this->fromDom($dom);
278 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
280 * @param DOMDocument $dom
281 * @return mixed associative array of envelope data, or false on unrecognized input
283 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
284 * @fixme may give fatal errors if some elements are missing
286 public function fromDom($dom)
288 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'env')->item(0);
290 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'provenance')->item(0);
297 $data_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'data')->item(0);
298 $sig_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'sig')->item(0);
300 'data' => preg_replace('/\s/', '', $data_element->nodeValue),
301 'data_type' => $data_element->getAttribute('type'),
302 'encoding' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'encoding')->item(0)->nodeValue,
303 'alg' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'alg')->item(0)->nodeValue,
304 'sig' => preg_replace('/\s/', '', $sig_element->nodeValue),
310 * Variant of MagicEnvelope using the earlier signature form listed in the MagicEnvelope
311 * spec in early 2010; this was used in StatusNet up through 0.9.6, so for backwards compatiblity
312 * we still need to accept and sometimes send this format.
314 class MagicEnvelopeCompat extends MagicEnvelope {
317 * StatusNet through 0.9.6 used an earlier version of the MagicEnvelope spec
318 * which used only the input data, without the additional fields, as the plaintext
324 public function signingText($env) {