DiasporaPlugin.php 12 KB

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