Activitypub_rsa.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * ActivityPub implementation for GNU social
  18. *
  19. * @package GNUsocial
  20. * @author Diogo Cordeiro <diogo@fc.up.pt>
  21. * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
  22. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  23. * @link http://www.gnu.org/software/social/
  24. */
  25. defined('GNUSOCIAL') || die();
  26. /**
  27. * ActivityPub Keys System
  28. *
  29. * @category Plugin
  30. * @package GNUsocial
  31. * @author Diogo Cordeiro <diogo@fc.up.pt>
  32. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  33. */
  34. class Activitypub_rsa extends Managed_DataObject
  35. {
  36. public $__table = 'activitypub_rsa';
  37. public $profile_id; // int(4) primary_key not_null
  38. public $private_key; // text() not_null
  39. public $public_key; // text() not_null
  40. public $created; // datetime()
  41. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  42. /**
  43. * Return table definition for Schema setup and DB_DataObject usage.
  44. *
  45. * @return array array of column definitions
  46. * @author Diogo Cordeiro <diogo@fc.up.pt>
  47. */
  48. public static function schemaDef()
  49. {
  50. return [
  51. 'fields' => [
  52. 'profile_id' => ['type' => 'int', 'not null' => true],
  53. 'private_key' => ['type' => 'text'],
  54. 'public_key' => ['type' => 'text', 'not null' => true],
  55. 'created' => ['type' => 'datetime', 'description' => 'date this record was created'],
  56. 'modified' => ['type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'],
  57. ],
  58. 'primary key' => ['profile_id'],
  59. 'foreign keys' => [
  60. 'activitypub_rsa_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
  61. ],
  62. ];
  63. }
  64. /**
  65. * Private key getter
  66. *
  67. * @param Profile $profile
  68. * @return string The private key
  69. * @throws Exception Throws exception if tries to fetch a private key of an actor we don't own
  70. */
  71. public function get_private_key(Profile $profile): string
  72. {
  73. $this->profile_id = $profile->getID();
  74. $apRSA = self::getKV('profile_id', $this->profile_id);
  75. if (!$apRSA instanceof Activitypub_rsa) {
  76. // Nonexistent key pair for this profile
  77. if ($profile->isLocal()) {
  78. self::generate_keys($this->private_key, $this->public_key);
  79. $this->store_keys();
  80. $apRSA->private_key = $this->private_key;
  81. } else {
  82. throw new Exception('This is a remote Profile, there is no Private Key for this Profile.');
  83. }
  84. }
  85. return $apRSA->private_key;
  86. }
  87. /**
  88. * Guarantees a Public Key for a given profile.
  89. *
  90. * @param Profile $profile
  91. * @param bool $fetch=true Should attempt to fetch keys from a remote profile?
  92. * @return string The public key
  93. * @throws ServerException It should never occur, but if so, we break everything!
  94. * @throws Exception
  95. * @author Diogo Cordeiro <diogo@fc.up.pt>
  96. */
  97. public function ensure_public_key(Profile $profile, bool $fetch = true): string
  98. {
  99. $this->profile_id = $profile->getID();
  100. $apRSA = self::getKV('profile_id', $this->profile_id);
  101. if (!$apRSA instanceof Activitypub_rsa) {
  102. // No existing key pair for this profile
  103. if ($profile->isLocal()) {
  104. self::generate_keys($this->private_key, $this->public_key);
  105. $this->store_keys();
  106. $apRSA->public_key = $this->public_key;
  107. } else {
  108. // ASSERT: This should never happen, but try to recover!
  109. common_log(LOG_ERR, "Activitypub_rsa: An impossible thing has happened... Please let the devs know that it entered in line 116 at Activitypub_rsa.php");
  110. if ($fetch) {
  111. $res = Activitypub_explorer::get_remote_user_activity($profile->getUri());
  112. Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
  113. return self::ensure_public_key($profile, false);
  114. } else {
  115. throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!');
  116. }
  117. }
  118. }
  119. return $apRSA->public_key;
  120. }
  121. /**
  122. * Insert the current object variables into the database.
  123. *
  124. * @throws ServerException
  125. * @author Diogo Cordeiro <diogo@fc.up.pt>
  126. * @access public
  127. */
  128. public function store_keys(): void
  129. {
  130. $this->created = $this->modified = common_sql_now();
  131. $ok = $this->insert();
  132. if ($ok === false) {
  133. throw new ServerException('Cannot save ActivityPub RSA.');
  134. }
  135. }
  136. /**
  137. * Generates a pair of RSA keys.
  138. *
  139. * @param string $private_key out
  140. * @param string $public_key out
  141. * @author PHP Manual Contributed Notes <dirt@awoms.com>
  142. */
  143. public static function generate_keys(?string &$private_key, ?string &$public_key): void
  144. {
  145. $config = [
  146. 'digest_alg' => 'sha512',
  147. 'private_key_bits' => 2048,
  148. 'private_key_type' => OPENSSL_KEYTYPE_RSA,
  149. ];
  150. // Create the private and public key
  151. $res = openssl_pkey_new($config);
  152. // Extract the private key from $res to $private_key
  153. openssl_pkey_export($res, $private_key);
  154. // Extract the public key from $res to $pubKey
  155. $pubKey = openssl_pkey_get_details($res);
  156. $public_key = $pubKey["key"];
  157. unset($pubKey);
  158. }
  159. /**
  160. * Update public key.
  161. *
  162. * @param Profile|Activitypub_profile $profile
  163. * @param string $public_key
  164. * @throws Exception
  165. * @author Diogo Cordeiro <diogo@fc.up.pt>
  166. */
  167. public static function update_public_key($profile, string $public_key): void
  168. {
  169. // Public Key
  170. $apRSA = new Activitypub_rsa();
  171. $apRSA->profile_id = $profile->getID();
  172. $apRSA->public_key = $public_key;
  173. $apRSA->created = common_sql_now();
  174. if (!$apRSA->update()) {
  175. $apRSA->insert();
  176. }
  177. }
  178. }