3 * GNU Social - a federating social network
4 * Copyright (C) 2015, Free Software Foundation, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
23 * Diaspora federation protocol plugin for GNU Social
29 * @package ProtocolDiasporaPlugin
30 * @maintainer Mikael Nordfeldth <mmn@hethane.se>
33 // Depends on OStatus of course.
36 class DiasporaPlugin extends Plugin
38 const REL_SEED_LOCATION = 'http://joindiaspora.com/seed_location';
39 const REL_GUID = 'http://joindiaspora.com/guid';
40 const REL_PUBLIC_KEY = 'diaspora-public-key';
42 public function onEndAttachPubkeyToUserXRD(Magicsig $magicsig, XML_XRD $xrd, Profile $target)
44 // So far we've only handled RSA keys, but it can change in the future,
45 // so be prepared. And remember to change the statically assigned type attribute below!
46 assert($magicsig->publicKey instanceof \phpseclib\Crypt\RSA);
47 $xrd->links[] = new XML_XRD_Element_Link(self::REL_PUBLIC_KEY,
48 base64_encode($magicsig->exportPublicKey()), 'RSA');
50 // Instead of choosing a random string, we calculate our GUID from the public key
51 // by fingerprint through a sha256 hash.
52 $xrd->links[] = new XML_XRD_Element_Link(self::REL_GUID,
53 strtolower($magicsig->toFingerprint()));
56 public function onMagicsigPublicKeyFromXRD(XML_XRD $xrd, &$pubkey)
58 // See if we have a Diaspora public key in the XRD response
59 $link = $xrd->get(self::REL_PUBLIC_KEY, 'RSA');
60 if (!is_null($link)) {
61 // If we do, decode it so we have the PKCS1 format (starts with -----BEGIN PUBLIC KEY-----)
62 $pkcs1 = base64_decode($link->href);
63 $magicsig = new Magicsig(Magicsig::DEFAULT_SIGALG); // Diaspora uses RSA-SHA256 (we do too)
65 // Try to load the public key so we can get it in the standard Magic signature format
66 $magicsig->loadPublicKeyPKCS1($pkcs1);
67 // We found it and will now store it in $pubkey in a proper format!
68 // This is how it would be found in a well implemented XRD according to the standard.
69 $pubkey = 'data:application/magic-public-key,'.$magicsig->toString();
70 common_debug('magic-public-key found in diaspora-public-key: '.$pubkey);
72 } catch (ServerException $e) {
73 common_log(LOG_WARNING, $e->getMessage());
79 public function onPluginVersion(array &$versions)
81 $versions[] = array('name' => 'Diaspora',
83 'author' => 'Mikael Nordfeldth',
84 'homepage' => 'https://gnu.io/social',
85 // TRANS: Plugin description.
86 'rawdescription' => _m('Follow people across social networks that implement '.
87 'the <a href="https://diasporafoundation.org/">Diaspora</a> federation protocol.'));
92 public function onStartMagicEnvelopeToXML(MagicEnvelope $magic_env, XMLStringer $xs, $flavour=null, Profile $target=null)
94 // Since Diaspora doesn't use a separate namespace for their "extended"
95 // salmon slap, we'll have to resort to this workaround hack.
96 if ($flavour !== 'diaspora') {
100 // WARNING: This changes the $magic_env contents! Be aware of it.
103 * https://wiki.diasporafoundation.org/Federation_protocol_overview
104 * http://www.rubydoc.info/github/Raven24/diaspora-federation/master/DiasporaFederation/Salmon/EncryptedSlap
106 * Constructing the encryption header
109 // For some reason diaspora wants the salmon slap in a <diaspora> header.
110 $xs->elementStart('diaspora', array('xmlns'=>'https://joindiaspora.com/protocol'));
113 * Choose an AES key and initialization vector, suitable for the
114 * aes-256-cbc cipher. I shall refer to this as the “inner key”
115 * and the “inner initialization vector (iv)”.
117 $inner_key = new \phpseclib\Crypt\AES(\phpseclib\Crypt\AES::MODE_CBC);
118 $inner_key->setKeyLength(256); // set length to 256 bits (could be calculated, but let's be sure)
119 $inner_key->setKey(common_random_rawstr(32)); // 32 bytes from a (pseudo) random source
120 $inner_key->setIV(common_random_rawstr(16)); // 16 bytes is the block length
123 * Construct the following XML snippet:
125 * <iv>((base64-encoded inner iv))</iv>
126 * <aes_key>((base64-encoded inner key))</aes_key>
128 * <name>Alice Exampleman</name>
129 * <uri>acct:user@sender.example</uri>
131 * </decrypted_header>
133 $decrypted_header = sprintf('<decrypted_header><iv>%1$s</iv><aes_key>%2$s</aes_key><author_id>%3$s</author_id></decrypted_header>',
134 base64_encode($inner_key->iv),
135 base64_encode($inner_key->key),
136 $magic_env->getActor()->getAcctUri());
139 * Construct another AES key and initialization vector suitable
140 * for the aes-256-cbc cipher. I shall refer to this as the
141 * “outer key” and the “outer initialization vector (iv)”.
143 $outer_key = new \phpseclib\Crypt\AES(\phpseclib\Crypt\AES::MODE_CBC);
144 $outer_key->setKeyLength(256); // set length to 256 bits (could be calculated, but let's be sure)
145 $outer_key->setKey(common_random_rawstr(32)); // 32 bytes from a (pseudo) random source
146 $outer_key->setIV(common_random_rawstr(16)); // 16 bytes is the block length
149 * Encrypt your <decrypted_header> XML snippet using the “outer key”
150 * and “outer iv” (using the aes-256-cbc cipher). This encrypted
151 * blob shall be referred to as “the ciphertext”.
153 $ciphertext = $outer_key->encrypt($decrypted_header, \phpseclib\Crypt\RSA::PADDING_PKCS1);
156 * Construct the following JSON object, which shall be referred to
157 * as “the outer aes key bundle”:
159 * "iv": ((base64-encoded AES outer iv)),
160 * "key": ((base64-encoded AES outer key))
163 $outer_bundle = json_encode(array(
164 'iv' => base64_encode($outer_key->iv),
165 'key' => base64_encode($outer_key->key),
168 * Encrypt the “outer aes key bundle” with Bob’s RSA public key.
169 * I shall refer to this as the “encrypted outer aes key bundle”.
171 common_debug('Diaspora creating "outer aes key bundle", will require magic-public-key');
172 $key_fetcher = new MagicEnvelope();
173 $remote_keys = $key_fetcher->getKeyPair($target, true); // actually just gets the public key
174 $enc_outer = $remote_keys->publicKey->encrypt($outer_bundle, \phpseclib\Crypt\RSA::PADDING_PKCS1);
177 * Construct the following JSON object, which I shall refer to as
178 * the “encrypted header json object”:
180 * "aes_key": ((base64-encoded encrypted outer aes key bundle)),
181 * "ciphertext": ((base64-encoded ciphertextm from above))
184 $enc_header = json_encode(array(
185 'aes_key' => base64_encode($enc_outer),
186 'ciphertext' => base64_encode($ciphertext),
190 * Construct the xml snippet:
191 * <encrypted_header>((base64-encoded encrypted header json object))</encrypted_header>
193 $xs->element('encrypted_header', null, base64_encode($enc_header));
196 * In order to prepare the payload message for inclusion in your
197 * salmon slap, you will:
199 * 1. Encrypt the payload message using the aes-256-cbc cipher and
200 * the “inner encryption key” and “inner encryption iv” you
202 * 2. Base64-encode the encrypted payload message.
204 $payload = $inner_key->encrypt($magic_env->getData(), \phpseclib\Crypt\RSA::PADDING_PKCS1);
205 //FIXME: This means we don't actually put an <atom:entry> in the payload,
206 // since Diaspora has its own update method! Silly me. Read up on:
207 // https://wiki.diasporafoundation.org/Federation_Message_Semantics
208 $magic_env->signMessage(base64_encode($payload), 'application/xml');
211 // Since we have to change the content of me:data we'll just write the
212 // whole thing from scratch. We _could_ otherwise have just manipulated
213 // that element and added the encrypted_header in the EndMagicEnvelopeToXML event.
214 $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::NS));
215 $xs->element('me:data', array('type' => $magic_env->getDataType()), $magic_env->getData());
216 $xs->element('me:encoding', null, $magic_env->getEncoding());
217 $xs->element('me:alg', null, $magic_env->getSignatureAlgorithm());
218 $xs->element('me:sig', null, $magic_env->getSignature());
219 $xs->elementEnd('me:env');
221 $xs->elementEnd('entry');
226 public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
229 $envxml = $magic_env->toXML($target, 'diaspora');
230 } catch (Exception $e) {
231 common_log(LOG_ERR, sprintf('Could not generate Magic Envelope XML (diaspora flavour) for profile id=='.$target->getID().': '.$e->getMessage()));
235 // Diaspora wants another POST format (base64url-encoded POST variable 'xml')
236 $headers = array('Content-Type: application/x-www-form-urlencoded');
238 // Another way to distinguish Diaspora from GNU social is that a POST with
239 // $headers=array('Content-Type: application/magic-envelope+xml') would return
240 // HTTP status code 422 Unprocessable Entity, at least as of 2015-10-04.
242 $client = new HTTPClient();
243 $client->setBody('xml=' . Magicsig::base64_url_encode($envxml));
244 $response = $client->post($endpoint_uri, $headers);
245 } catch (Exception $e) {
246 common_log(LOG_ERR, "Diaspora-flavoured Salmon post to $endpoint_uri failed: " . $e->getMessage());
250 // 200 OK is the best response
251 // 202 Accepted is what we get from Diaspora for example
252 if (!in_array($response->getStatus(), array(200, 202))) {
253 common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
254 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));