ActivitypubRsa.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social 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. // GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. /**
  20. * ActivityPub implementation for GNU social
  21. *
  22. * @package GNUsocial
  23. * @category ActivityPub
  24. *
  25. * @author Diogo Peralta Cordeiro <@diogo.site>
  26. * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
  27. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  28. */
  29. namespace Plugin\ActivityPub\Entity;
  30. use App\Core\DB\DB;
  31. use App\Core\Entity;
  32. use App\Core\Log;
  33. use App\Entity\Actor;
  34. use App\Util\Exception\ServerException;
  35. use DateTimeInterface;
  36. use Exception;
  37. use Plugin\ActivityPub\Util\Explorer;
  38. /**
  39. * ActivityPub Keys System
  40. *
  41. * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
  42. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  43. */
  44. class ActivitypubRsa extends Entity
  45. {
  46. // {{{ Autocode
  47. // @codeCoverageIgnoreStart
  48. private int $actor_id;
  49. private ?string $private_key = null;
  50. private string $public_key;
  51. private DateTimeInterface $created;
  52. private DateTimeInterface $modified;
  53. public function setActorId(int $actor_id): self
  54. {
  55. $this->actor_id = $actor_id;
  56. return $this;
  57. }
  58. public function getActorId(): int
  59. {
  60. return $this->actor_id;
  61. }
  62. public function setPrivateKey(?string $private_key): self
  63. {
  64. $this->private_key = $private_key;
  65. return $this;
  66. }
  67. public function getPrivateKey(): ?string
  68. {
  69. return $this->private_key;
  70. }
  71. public function setPublicKey(string $public_key): self
  72. {
  73. $this->public_key = $public_key;
  74. return $this;
  75. }
  76. public function getPublicKey(): string
  77. {
  78. return $this->public_key;
  79. }
  80. public function setCreated(DateTimeInterface $created): self
  81. {
  82. $this->created = $created;
  83. return $this;
  84. }
  85. public function getCreated(): DateTimeInterface
  86. {
  87. return $this->created;
  88. }
  89. public function setModified(DateTimeInterface $modified): self
  90. {
  91. $this->modified = $modified;
  92. return $this;
  93. }
  94. public function getModified(): DateTimeInterface
  95. {
  96. return $this->modified;
  97. }
  98. // @codeCoverageIgnoreEnd
  99. // }}} Autocode
  100. /**
  101. * Return table definition for Schema setup and Entity usage.
  102. *
  103. * @return array array of column definitions
  104. */
  105. public static function schemaDef(): array
  106. {
  107. return [
  108. 'name' => 'activitypub_rsa',
  109. 'fields' => [
  110. 'actor_id' => ['type' => 'int', 'not null' => true],
  111. 'private_key' => ['type' => 'text'],
  112. 'public_key' => ['type' => 'text', 'not null' => true],
  113. 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
  114. 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
  115. ],
  116. 'primary key' => ['actor_id'],
  117. 'foreign keys' => [
  118. 'activitypub_rsa_actor_id_fkey' => ['actor', ['actor_id' => 'id']],
  119. ],
  120. ];
  121. }
  122. /**
  123. * Guarantees RSA keys for a given actor.
  124. *
  125. * @param bool $fetch =true Should attempt to fetch keys from a remote profile?
  126. *
  127. * @throws ServerException It should never occur, but if so, we break everything!
  128. *
  129. * @return ActivitypubRsa The keys (private key is null for remote actors)
  130. */
  131. public static function getByActor(Actor $gsactor, bool $fetch = true): self
  132. {
  133. $apRSA = DB::findOneBy(self::class, ['actor_id' => ($actor_id = $gsactor->getId())], return_null: true);
  134. if (\is_null($apRSA)) {
  135. // Nonexistent key pair for this profile
  136. if ($gsactor->getIsLocal()) {
  137. self::generateKeys($private_key, $public_key);
  138. $apRSA = self::create([
  139. 'actor_id' => $actor_id,
  140. 'private_key' => $private_key,
  141. 'public_key' => $public_key,
  142. ]);
  143. DB::wrapInTransaction(fn () => DB::persist($apRSA));
  144. } else {
  145. // ASSERT: This should never happen, but try to recover!
  146. Log::error('Activitypub_rsa: It seems that the RSA key for this remote actor was somehow lost. That should have never happened!');
  147. if ($fetch) {
  148. try {
  149. $res = Explorer::getRemoteActorActivity($gsactor->getUri());
  150. if (\is_null($res)) {
  151. throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened! Invalid remote actor (null response).');
  152. }
  153. DB::wrapInTransaction(fn () => DB::persist(self::create([
  154. 'actor_id' => $gsactor->getId(),
  155. 'public_key' => json_decode($res, associative: true)['publicKey']['publicKeyPem'],
  156. ])));
  157. return self::getByActor($gsactor, false);
  158. } catch (Exception $e) {
  159. throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!', previous: $e);
  160. }
  161. } else {
  162. throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!');
  163. }
  164. }
  165. }
  166. return $apRSA;
  167. }
  168. /**
  169. * Generates a pair of RSA keys.
  170. *
  171. * @param null|string $private_key out
  172. * @param null|string $public_key out
  173. *
  174. * @author PHP Manual Contributed Notes <dirt@awoms.com>
  175. */
  176. private static function generateKeys(?string &$private_key, ?string &$public_key): void
  177. {
  178. $config = [
  179. 'digest_alg' => 'sha512',
  180. 'private_key_bits' => 2048,
  181. 'private_key_type' => \OPENSSL_KEYTYPE_RSA,
  182. ];
  183. // Create the private and public key
  184. $res = openssl_pkey_new($config);
  185. // Extract the private key from $res to $private_key
  186. openssl_pkey_export($res, $private_key);
  187. // Extract the public key from $res to $pubKey
  188. $pubKey = openssl_pkey_get_details($res);
  189. $public_key = $pubKey['key'];
  190. unset($pubKey);
  191. }
  192. }