DiasporaPlugin.php 12 KB

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