ActivityPubCryptKey.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. <?php
  2. // {{{ License
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. // }}}
  18. /**
  19. * ActivityPub Assymetric Key Storage System
  20. *
  21. * @package GNUsocial
  22. *
  23. * @author Diogo Cordeiro <diogo@fc.up.pt>
  24. * @author Hugo Sales <hugo@fc.up.pt>
  25. * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
  26. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  27. */
  28. namespace Plugin\ActivityPub\Entity;
  29. class ActivityPubCryptKey
  30. {
  31. // {{{ Autocode
  32. private int $gsactor_id;
  33. private ?string $private_key;
  34. private string $public_key;
  35. private ?DateTimeInterface $created;
  36. private DateTimeInterface $modified;
  37. public function setGsactorId(int $gsactor_id): self
  38. {
  39. $this->gsactor_id = $gsactor_id;
  40. return $this;
  41. }
  42. public function getGsactorId(): int
  43. {
  44. return $this->gsactor_id;
  45. }
  46. public function setPrivateKey(?string $private_key): self
  47. {
  48. $this->private_key = $private_key;
  49. return $this;
  50. }
  51. public function getPrivateKey(): ?string
  52. {
  53. return $this->private_key;
  54. }
  55. public function setPublicKey(string $public_key): self
  56. {
  57. $this->public_key = $public_key;
  58. return $this;
  59. }
  60. public function getPublicKey(): string
  61. {
  62. return $this->public_key;
  63. }
  64. public function setCreated(?DateTimeInterface $created): self
  65. {
  66. $this->created = $created;
  67. return $this;
  68. }
  69. public function getCreated(): ?DateTimeInterface
  70. {
  71. return $this->created;
  72. }
  73. public function setModified(DateTimeInterface $modified): self
  74. {
  75. $this->modified = $modified;
  76. return $this;
  77. }
  78. public function getModified(): DateTimeInterface
  79. {
  80. return $this->modified;
  81. }
  82. // }}} Autocode
  83. /**
  84. * Private key getter
  85. *
  86. * @param Profile $profile
  87. *
  88. * @throws Exception Throws exception if tries to fetch a private key of an actor we don't own
  89. *
  90. * @return string The private key
  91. */
  92. public function get_private_key(Profile $profile): string
  93. {
  94. $this->profile_id = $profile->getID();
  95. $apRSA = self::getKV('profile_id', $this->profile_id);
  96. if (!$apRSA instanceof Activitypub_rsa) {
  97. // Nonexistent key pair for this profile
  98. if ($profile->isLocal()) {
  99. self::generate_keys($this->private_key, $this->public_key);
  100. $this->store_keys();
  101. $apRSA->private_key = $this->private_key;
  102. } else {
  103. throw new Exception('This is a remote Profile, there is no Private Key for this Profile.');
  104. }
  105. }
  106. return $apRSA->private_key;
  107. }
  108. /**
  109. * Guarantees a Public Key for a given profile.
  110. *
  111. * @param Profile $profile
  112. * @param bool $fetch=true Should attempt to fetch keys from a remote profile?
  113. *
  114. * @throws ServerException It should never occur, but if so, we break everything!
  115. * @throws Exception
  116. *
  117. * @return string The public key
  118. *
  119. * @author Diogo Cordeiro <diogo@fc.up.pt>
  120. */
  121. public function ensure_public_key(Profile $profile, bool $fetch = true): string
  122. {
  123. $this->profile_id = $profile->getID();
  124. $apRSA = self::getKV('profile_id', $this->profile_id);
  125. if (!$apRSA instanceof Activitypub_rsa) {
  126. // No existing key pair for this profile
  127. if ($profile->isLocal()) {
  128. self::generate_keys($this->private_key, $this->public_key);
  129. $this->store_keys();
  130. $apRSA->public_key = $this->public_key;
  131. } else {
  132. // ASSERT: This should never happen, but try to recover!
  133. 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');
  134. if ($fetch) {
  135. $res = Activitypub_explorer::get_remote_user_activity($profile->getUri());
  136. Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
  137. return self::ensure_public_key($profile, false);
  138. } else {
  139. throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!');
  140. }
  141. }
  142. }
  143. return $apRSA->public_key;
  144. }
  145. /**
  146. * Insert the current object variables into the database.
  147. *
  148. * @throws ServerException
  149. *
  150. * @author Diogo Cordeiro <diogo@fc.up.pt>
  151. */
  152. public function store_keys(): void
  153. {
  154. $this->created = $this->modified = common_sql_now();
  155. $ok = $this->insert();
  156. if ($ok === false) {
  157. throw new ServerException('Cannot save ActivityPub RSA.');
  158. }
  159. }
  160. /**
  161. * Generates a pair of RSA keys.
  162. *
  163. * @param string $private_key out
  164. * @param string $public_key out
  165. *
  166. * @author PHP Manual Contributed Notes <dirt@awoms.com>
  167. */
  168. public static function generate_keys(?string &$private_key, ?string &$public_key): void
  169. {
  170. $config = [
  171. 'digest_alg' => 'sha512',
  172. 'private_key_bits' => 2048,
  173. 'private_key_type' => OPENSSL_KEYTYPE_RSA,
  174. ];
  175. // Create the private and public key
  176. $res = openssl_pkey_new($config);
  177. // Extract the private key from $res to $private_key
  178. openssl_pkey_export($res, $private_key);
  179. // Extract the public key from $res to $pubKey
  180. $pubKey = openssl_pkey_get_details($res);
  181. $public_key = $pubKey['key'];
  182. unset($pubKey);
  183. }
  184. /**
  185. * Update public key.
  186. *
  187. * @param Activitypub_profile|Profile $profile
  188. * @param string $public_key
  189. *
  190. * @throws Exception
  191. *
  192. * @author Diogo Cordeiro <diogo@fc.up.pt>
  193. */
  194. public static function update_public_key($profile, string $public_key): void
  195. {
  196. // Public Key
  197. $apRSA = new Activitypub_rsa();
  198. $apRSA->profile_id = $profile->getID();
  199. $apRSA->public_key = $public_key;
  200. $apRSA->created = common_sql_now();
  201. if (!$apRSA->update()) {
  202. $apRSA->insert();
  203. }
  204. }
  205. public static function schemaDef()
  206. {
  207. return [
  208. 'name' => 'activitypub_crypt_key',
  209. 'description' => 'assymetric key storage for activitypub',
  210. 'fields' => [
  211. 'gsactor_id' => ['type' => 'int', 'not null' => true],
  212. 'private_key' => ['type' => 'text'],
  213. 'public_key' => ['type' => 'text', 'not null' => true],
  214. 'created' => ['type' => 'datetime', 'description' => 'date this record was created'],
  215. 'modified' => ['type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'],
  216. ],
  217. 'primary key' => ['gsactor_id'],
  218. 'foreign keys' => [
  219. 'activitypub_rsa_gsactor_id_fkey' => ['gsactor', ['gsactor_id' => 'id']],
  220. ],
  221. ];
  222. }
  223. }