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;
51 * Get the Salmon keypair from a URI, uses XRD Discovery etc.
53 * @return Magicsig with loaded keypair
55 public function getKeyPair($signer_uri)
57 $disco = new Discovery();
59 // Throws exception on lookup problems
60 $xrd = $disco->lookup($signer_uri);
62 $link = $xrd->get(Magicsig::PUBLICKEYREL);
65 throw new Exception(_m('Unable to locate signer public key.'));
68 // We have a public key element, let's hope it has proper key data.
70 $parts = explode(',', $link->href);
71 if (count($parts) == 2) {
74 // Backwards compatibility check for separator bug in 0.9.0
75 $parts = explode(';', $link->href);
76 if (count($parts) == 2) {
81 if ($keypair === false) {
82 // For debugging clarity. Keypair did not pass count()-check above.
83 // TRANS: Exception when public key was not properly formatted.
84 throw new Exception(_m('Incorrectly formatted public key element.'));
87 $magicsig = Magicsig::fromString($keypair);
88 if (!$magicsig instanceof Magicsig) {
89 common_debug('Salmon error: unable to parse keypair: '.var_export($keypair,true));
90 // TRANS: Exception when public key was properly formatted but not parsable.
91 throw new ServerException(_m('Retrieved Salmon keypair could not be parsed.'));
98 * The current MagicEnvelope spec as used in StatusNet 0.9.7 and later
99 * includes both the original data and some signing metadata fields as
100 * the input plaintext for the signature hash.
105 public function signingText($env) {
106 return implode('.', array($env['data'], // this field is pre-base64'd
107 Magicsig::base64_url_encode($env['data_type']),
108 Magicsig::base64_url_encode($env['encoding']),
109 Magicsig::base64_url_encode($env['alg'])));
114 * @param <type> $text
115 * @param <type> $mimetype
116 * @param <type> $keypair
117 * @return array: associative array of envelope properties
118 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
120 public function signMessage($text, $mimetype, $keypair)
122 $signature_alg = Magicsig::fromString($keypair);
123 $armored_text = Magicsig::base64_url_encode($text);
125 'data' => $armored_text,
126 'encoding' => MagicEnvelope::ENCODING,
127 'data_type' => $mimetype,
129 'alg' => $signature_alg->getName()
132 $env['sig'] = $signature_alg->sign($this->signingText($env));
138 * Create an <me:env> XML representation of the envelope.
140 * @param array $env associative array with envelope data
141 * @return string representation of XML document
142 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
144 public function toXML($env) {
145 $xs = new XMLStringer();
147 $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::NS));
148 $xs->element('me:data', array('type' => $env['data_type']), $env['data']);
149 $xs->element('me:encoding', null, $env['encoding']);
150 $xs->element('me:alg', null, $env['alg']);
151 $xs->element('me:sig', null, $env['sig']);
152 $xs->elementEnd('me:env');
154 $string = $xs->getString();
155 common_debug($string);
160 * Extract the contained XML payload, and insert a copy of the envelope
161 * signature data as an <me:provenance> section.
163 * @param array $env associative array with envelope data
164 * @return string representation of modified XML document
166 * @fixme in case of XML parsing errors, this will spew to the error log or output
167 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
169 public function unfold($env)
171 $dom = new DOMDocument();
172 $dom->loadXML(Magicsig::base64_url_decode($env['data']));
174 if ($dom->documentElement->tagName != 'entry') {
178 $prov = $dom->createElementNS(MagicEnvelope::NS, 'me:provenance');
179 $prov->setAttribute('xmlns:me', MagicEnvelope::NS);
180 $data = $dom->createElementNS(MagicEnvelope::NS, 'me:data', $env['data']);
181 $data->setAttribute('type', $env['data_type']);
182 $prov->appendChild($data);
183 $enc = $dom->createElementNS(MagicEnvelope::NS, 'me:encoding', $env['encoding']);
184 $prov->appendChild($enc);
185 $alg = $dom->createElementNS(MagicEnvelope::NS, 'me:alg', $env['alg']);
186 $prov->appendChild($alg);
187 $sig = $dom->createElementNS(MagicEnvelope::NS, 'me:sig', $env['sig']);
188 $prov->appendChild($sig);
190 $dom->documentElement->appendChild($prov);
192 return $dom->saveXML();
196 * Find the author URI referenced in the given Atom entry.
198 * @param string $text string containing Atom entry XML
199 * @return mixed URI string or false if XML parsing fails, or null if no author URI can be found
201 * @fixme XML parsing failures will spew to error logs/output
203 public function getAuthorUri($text) {
204 $doc = new DOMDocument();
205 if (!$doc->loadXML($text)) {
209 if ($doc->documentElement->tagName == 'entry') {
210 $authors = $doc->documentElement->getElementsByTagName('author');
211 foreach ($authors as $author) {
212 $uris = $author->getElementsByTagName('uri');
213 foreach ($uris as $uri) {
214 return $this->normalizeUser($uri->nodeValue);
221 * Attempt to verify cryptographic signing for parsed envelope data.
222 * Requires network access to retrieve public key referenced by the envelope signer.
224 * Details of failure conditions are dumped to output log and not exposed to caller.
226 * @param array $env array representation of magic envelope data, as returned from MagicEnvelope::parse()
229 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
231 public function verify($env)
233 if ($env['alg'] != 'RSA-SHA256') {
234 common_log(LOG_DEBUG, "Salmon error: bad algorithm");
238 if ($env['encoding'] != MagicEnvelope::ENCODING) {
239 common_log(LOG_DEBUG, "Salmon error: bad encoding");
243 $text = Magicsig::base64_url_decode($env['data']);
244 $signer_uri = $this->getAuthorUri($text);
247 $magicsig = $this->getKeyPair($signer_uri);
248 } catch (Exception $e) {
249 common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
253 return $magicsig->verify($this->signingText($env), $env['sig']);
257 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
259 * @param string XML source
260 * @return mixed associative array of envelope data, or false on unrecognized input
262 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
263 * @fixme will spew errors to logs or output in case of XML parse errors
264 * @fixme may give fatal errors if some elements are missing or invalid XML
265 * @fixme calling DOMDocument::loadXML statically triggers warnings in strict mode
267 public function parse($text)
269 $dom = DOMDocument::loadXML($text);
270 return $this->fromDom($dom);
274 * Extract envelope data from an XML document containing an <me:env> or <me:provenance> element.
276 * @param DOMDocument $dom
277 * @return mixed associative array of envelope data, or false on unrecognized input
279 * @fixme it might be easier to work with storing envelope data these in the object instead of passing arrays around
280 * @fixme may give fatal errors if some elements are missing
282 public function fromDom($dom)
284 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'env')->item(0);
286 $env_element = $dom->getElementsByTagNameNS(MagicEnvelope::NS, 'provenance')->item(0);
293 $data_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'data')->item(0);
294 $sig_element = $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'sig')->item(0);
296 'data' => preg_replace('/\s/', '', $data_element->nodeValue),
297 'data_type' => $data_element->getAttribute('type'),
298 'encoding' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'encoding')->item(0)->nodeValue,
299 'alg' => $env_element->getElementsByTagNameNS(MagicEnvelope::NS, 'alg')->item(0)->nodeValue,
300 'sig' => preg_replace('/\s/', '', $sig_element->nodeValue),
306 * Variant of MagicEnvelope using the earlier signature form listed in the MagicEnvelope
307 * spec in early 2010; this was used in StatusNet up through 0.9.6, so for backwards compatiblity
308 * we still need to accept and sometimes send this format.
310 class MagicEnvelopeCompat extends MagicEnvelope {
313 * StatusNet through 0.9.6 used an earlier version of the MagicEnvelope spec
314 * which used only the input data, without the additional fields, as the plaintext
320 public function signingText($env) {