Activitypub_rsa.php 6.8 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() not_null default_CURRENT_TIMESTAMP
  41. public $modified; // datetime() 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', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
  56. 'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
  57. ],
  58. 'primary key' => ['profile_id'],
  59. 'foreign keys' => [
  60. 'activitypub_profile_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
  61. ],
  62. ];
  63. }
  64. /**
  65. * Private key getter
  66. *
  67. * @param Profile $profile
  68. * @return string
  69. * @throws ServerException
  70. * @throws Exception
  71. */
  72. public function get_private_key(Profile $profile): string
  73. {
  74. $this->profile_id = $profile->getID();
  75. $apRSA = self::getKV('profile_id', $this->profile_id);
  76. if (!$apRSA instanceof Activitypub_rsa) {
  77. // No existing key pair for this profile
  78. if ($profile->isLocal()) {
  79. self::generate_keys($this->private_key, $this->public_key);
  80. $this->store_keys();
  81. $apRSA->private_key = $this->private_key;
  82. } else {
  83. throw new Exception('This is a remote Profile, there is no Private Key for this Profile.');
  84. }
  85. }
  86. return $apRSA->private_key;
  87. }
  88. /**
  89. * Guarantees a Public Key for a given profile.
  90. *
  91. * @param Profile $profile
  92. * @param bool $fetch
  93. * @return string The public key
  94. * @throws ServerException It should never occur, but if so, we break everything!
  95. * @throws Exception
  96. * @author Diogo Cordeiro <diogo@fc.up.pt>
  97. */
  98. public function ensure_public_key(Profile $profile, bool $fetch = true): string
  99. {
  100. $this->profile_id = $profile->getID();
  101. $apRSA = self::getKV('profile_id', $this->profile_id);
  102. if (!$apRSA instanceof Activitypub_rsa) {
  103. // No existing key pair for this profile
  104. if ($profile->isLocal()) {
  105. self::generate_keys($this->private_key, $this->public_key);
  106. $this->store_keys();
  107. $apRSA->public_key = $this->public_key;
  108. } else {
  109. // This should never happen, but try to recover!
  110. if ($fetch) {
  111. $res = Activitypub_explorer::get_remote_user_activity(ActivityPubPlugin::actor_uri($profile));
  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 in/out
  140. * @param string $public_key in/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->modified = common_sql_now();
  174. if (!$apRSA->update()) {
  175. $apRSA->insert();
  176. }
  177. }
  178. }