]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Diaspora/DiasporaPlugin.php
Missed some phpseclib stuff in DiasporaPlugin
[quix0rs-gnu-social.git] / plugins / Diaspora / DiasporaPlugin.php
1 <?php
2 /*
3  * GNU Social - a federating social network
4  * Copyright (C) 2015, Free Software Foundation, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Diaspora federation protocol plugin for GNU Social
24  *
25  * Depends on:
26  *  - OStatus plugin
27  *  - WebFinger plugin
28  *
29  * @package ProtocolDiasporaPlugin
30  * @maintainer Mikael Nordfeldth <mmn@hethane.se>
31  */
32
33 // Depends on OStatus of course.
34 addPlugin('OStatus');
35
36 //Since Magicsig hasn't loaded yet
37
38 class DiasporaPlugin extends Plugin
39 {
40     const REL_SEED_LOCATION = 'http://joindiaspora.com/seed_location';
41     const REL_GUID          = 'http://joindiaspora.com/guid';
42     const REL_PUBLIC_KEY    = 'diaspora-public-key';
43
44     public function onEndAttachPubkeyToUserXRD(Magicsig $magicsig, XML_XRD $xrd, Profile $target)
45     {
46         // So far we've only handled RSA keys, but it can change in the future,
47         // so be prepared. And remember to change the statically assigned type attribute below!
48         assert($magicsig->publicKey instanceof \phpseclib\Crypt\RSA);
49         $xrd->links[] = new XML_XRD_Element_Link(self::REL_PUBLIC_KEY,
50                                     base64_encode($magicsig->exportPublicKey()), 'RSA');
51
52         // Instead of choosing a random string, we calculate our GUID from the public key
53         // by fingerprint through a sha256 hash.
54         $xrd->links[] = new XML_XRD_Element_Link(self::REL_GUID,
55                                     strtolower($magicsig->toFingerprint()));
56     }
57
58     public function onMagicsigPublicKeyFromXRD(XML_XRD $xrd, &$pubkey)
59     {
60         // See if we have a Diaspora public key in the XRD response
61         $link = $xrd->get(self::REL_PUBLIC_KEY, 'RSA');
62         if (!is_null($link)) {
63             // If we do, decode it so we have the PKCS1 format (starts with -----BEGIN PUBLIC KEY-----)
64             $pkcs1 = base64_decode($link->href);
65             $magicsig = new Magicsig(Magicsig::DEFAULT_SIGALG); // Diaspora uses RSA-SHA256 (we do too)
66             try {
67                 // Try to load the public key so we can get it in the standard Magic signature format
68                 $magicsig->loadPublicKeyPKCS1($pkcs1);
69                 // We found it and will now store it in $pubkey in a proper format!
70                 // This is how it would be found in a well implemented XRD according to the standard.
71                 $pubkey = 'data:application/magic-public-key,'.$magicsig->toString();
72                 common_debug('magic-public-key found in diaspora-public-key: '.$pubkey);
73                 return false;
74             } catch (ServerException $e) {
75                 common_log(LOG_WARNING, $e->getMessage());
76             }
77         }
78         return true;
79     }
80
81     public function onPluginVersion(array &$versions)
82     {
83         $versions[] = array('name' => 'Diaspora',
84                             'version' => '0.1',
85                             'author' => 'Mikael Nordfeldth',
86                             'homepage' => 'https://gnu.io/social',
87                             // TRANS: Plugin description.
88                             'rawdescription' => _m('Follow people across social networks that implement '.
89                                'the <a href="https://diasporafoundation.org/">Diaspora</a> federation protocol.'));
90
91         return true;
92     }
93
94     public function onStartMagicEnvelopeToXML(MagicEnvelope $magic_env, XMLStringer $xs, $flavour=null, Profile $target=null)
95     {
96         // Since Diaspora doesn't use a separate namespace for their "extended"
97         // salmon slap, we'll have to resort to this workaround hack.
98         if ($flavour !== 'diaspora') {
99             return true;
100         }
101
102         // WARNING: This changes the $magic_env contents! Be aware of it.
103
104         /**
105          * https://wiki.diasporafoundation.org/Federation_protocol_overview
106          * http://www.rubydoc.info/github/Raven24/diaspora-federation/master/DiasporaFederation/Salmon/EncryptedSlap
107          *
108          * Constructing the encryption header
109          */
110
111         // For some reason diaspora wants the salmon slap in a <diaspora> header.
112         $xs->elementStart('diaspora', array('xmlns'=>'https://joindiaspora.com/protocol'));
113
114         /**
115          * Choose an AES key and initialization vector, suitable for the
116          * aes-256-cbc cipher. I shall refer to this as the “inner key”
117          * and the “inner initialization vector (iv)”.
118          */
119         $inner_key = new \phpseclib\Crypt\AES(\phpseclib\Crypt\AES::MODE_CBC);
120         $inner_key->setKeyLength(256);  // set length to 256 bits (could be calculated, but let's be sure)
121         $inner_key->setKey(common_random_rawstr(32));   // 32 bytes from a (pseudo) random source
122         $inner_key->setIV(common_random_rawstr(16));    // 16 bytes is the block length
123
124         /**
125          * Construct the following XML snippet:
126          *  <decrypted_header>
127          *      <iv>((base64-encoded inner iv))</iv>
128          *      <aes_key>((base64-encoded inner key))</aes_key>
129          *      <author>
130          *          <name>Alice Exampleman</name>
131          *          <uri>acct:user@sender.example</uri>
132          *      </author>
133          *  </decrypted_header>
134          */
135         $decrypted_header = sprintf('<decrypted_header><iv>%1$s</iv><aes_key>%2$s</aes_key><author_id>%3$s</author_id></decrypted_header>',
136                                     base64_encode($inner_key->iv),
137                                     base64_encode($inner_key->key),
138                                     $magic_env->getActor()->getAcctUri());
139
140         /**
141          * Construct another AES key and initialization vector suitable
142          * for the aes-256-cbc cipher. I shall refer to this as the
143          * “outer key” and the “outer initialization vector (iv)”.
144          */
145         $outer_key = new \phpseclib\Crypt\AES(\phpseclib\Crypt\AES::MODE_CBC);
146         $outer_key->setKeyLength(256);  // set length to 256 bits (could be calculated, but let's be sure)
147         $outer_key->setKey(common_random_rawstr(32));   // 32 bytes from a (pseudo) random source
148         $outer_key->setIV(common_random_rawstr(16));    // 16 bytes is the block length
149
150         /**
151          * Encrypt your <decrypted_header> XML snippet using the “outer key”
152          * and “outer iv” (using the aes-256-cbc cipher). This encrypted
153          * blob shall be referred to as “the ciphertext”. 
154          */
155         $ciphertext = $outer_key->encrypt($decrypted_header);
156
157         /**
158          * Construct the following JSON object, which shall be referred to
159          * as “the outer aes key bundle”:
160          *  {
161          *      "iv": ((base64-encoded AES outer iv)),
162          *      "key": ((base64-encoded AES outer key))
163          *  }
164          */
165         $outer_bundle = json_encode(array(
166                                 'iv' => base64_encode($outer_key->iv),
167                                 'key' => base64_encode($outer_key->key),
168                             ));
169         /**
170          * Encrypt the “outer aes key bundle” with Bob’s RSA public key.
171          * I shall refer to this as the “encrypted outer aes key bundle”.
172          */
173         common_debug('Diaspora creating "outer aes key bundle", will require magic-public-key');
174         $key_fetcher = new MagicEnvelope();
175         $remote_keys = $key_fetcher->getKeyPair($target, true); // actually just gets the public key
176         $enc_outer = $remote_keys->publicKey->encrypt($outer_bundle);
177
178         /**
179          * Construct the following JSON object, which I shall refer to as
180          * the “encrypted header json object”:
181          *  {
182          *      "aes_key": ((base64-encoded encrypted outer aes key bundle)),
183          *      "ciphertext": ((base64-encoded ciphertextm from above))
184          *  }
185          */
186         $enc_header = json_encode(array(
187                             'aes_key' => base64_encode($enc_outer),
188                             'ciphertext' => base64_encode($ciphertext),
189                         ));
190
191         /**
192          * Construct the xml snippet:
193          *  <encrypted_header>((base64-encoded encrypted header json object))</encrypted_header>
194          */
195         $xs->element('encrypted_header', null, base64_encode($enc_header));
196
197         /**
198          * In order to prepare the payload message for inclusion in your
199          * salmon slap, you will:
200          *
201          * 1. Encrypt the payload message using the aes-256-cbc cipher and
202          *      the “inner encryption key” and “inner encryption iv” you
203          *      chose earlier.
204          * 2. Base64-encode the encrypted payload message.
205          */
206         $payload = $inner_key->encrypt($magic_env->getData());
207         //FIXME: This means we don't actually put an <atom:entry> in the payload,
208         // since Diaspora has its own update method! Silly me. Read up on:
209         // https://wiki.diasporafoundation.org/Federation_Message_Semantics
210         $magic_env->signMessage(base64_encode($payload), 'application/xml');
211
212
213         // Since we have to change the content of me:data we'll just write the
214         // whole thing from scratch. We _could_ otherwise have just manipulated
215         // that element and added the encrypted_header in the EndMagicEnvelopeToXML event.
216         $xs->elementStart('me:env', array('xmlns:me' => MagicEnvelope::NS));
217         $xs->element('me:data', array('type' => $magic_env->getDataType()), $magic_env->getData());
218         $xs->element('me:encoding', null, $magic_env->getEncoding());
219         $xs->element('me:alg', null, $magic_env->getSignatureAlgorithm());
220         $xs->element('me:sig', null, $magic_env->getSignature());
221         $xs->elementEnd('me:env');
222
223         $xs->elementEnd('entry');
224
225         return false;
226     }
227
228     public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
229     {
230         $envxml = $magic_env->toXML($target, 'diaspora');
231
232         // Diaspora wants another POST format (base64url-encoded POST variable 'xml')
233         $headers = array('Content-Type: application/x-www-form-urlencoded');
234
235         // Another way to distinguish Diaspora from GNU social is that a POST with
236         // $headers=array('Content-Type: application/magic-envelope+xml') would return
237         // HTTP status code 422 Unprocessable Entity, at least as of 2015-10-04.
238         try {
239             $client = new HTTPClient();
240             $client->setBody('xml=' . Magicsig::base64_url_encode($envxml));
241             $response = $client->post($endpoint_uri, $headers);
242         } catch (Exception $e) {
243             common_log(LOG_ERR, "Diaspora-flavoured Salmon post to $endpoint_uri failed: " . $e->getMessage());
244             return false;
245         }
246
247         // 200 OK is the best response
248         // 202 Accepted is what we get from Diaspora for example
249         if (!in_array($response->getStatus(), array(200, 202))) {
250             common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
251                                 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
252             return true;
253         }
254
255         // Success!
256         return false;
257     }
258 }