HTTPSignature.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. <?php
  2. declare(strict_types = 1);
  3. /**
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. * @category Network
  17. * @package Nautilus
  18. *
  19. * @author Aaron Parecki <aaron@parecki.com>
  20. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  21. *
  22. * @see https://github.com/aaronpk/Nautilus/blob/master/app/ActivityPub/HTTPSignature.php
  23. */
  24. namespace Plugin\ActivityPub\Util;
  25. use App\Entity\Actor;
  26. use DateTime;
  27. use Exception;
  28. use Plugin\ActivityPub\Entity\ActivitypubRsa;
  29. class HTTPSignature
  30. {
  31. /**
  32. * Sign a message with an Actor
  33. *
  34. * @param Actor $user Actor signing
  35. * @param string $url Inbox url
  36. * @param bool|string $body Data to sign (optional)
  37. * @param array $addlHeaders Additional headers (optional)
  38. *
  39. * @throws Exception Attempted to sign something that belongs to an Actor we don't own
  40. *
  41. * @return array Headers to be used in request
  42. */
  43. public static function sign(Actor $user, string $url, string|bool $body = false, array $addlHeaders = []): array
  44. {
  45. $digest = false;
  46. if ($body) {
  47. $digest = self::_digest($body);
  48. }
  49. $headers = self::_headersToSign($url, $digest);
  50. $headers = array_merge($headers, $addlHeaders);
  51. $stringToSign = self::_headersToSigningString($headers);
  52. $signedHeaders = implode(' ', array_map('strtolower', array_keys($headers)));
  53. $actor_private_key = ActivitypubRsa::getByActor($user)->getPrivateKey();
  54. // Intentionally unhandled exception, we want this to explode if that happens as it would be a bug
  55. $key = openssl_pkey_get_private($actor_private_key);
  56. openssl_sign($stringToSign, $signature, $key, \OPENSSL_ALGO_SHA256);
  57. $signature = base64_encode($signature);
  58. $signatureHeader = 'keyId="' . $user->getUri() . '#public-key' . '",headers="' . $signedHeaders . '",algorithm="rsa-sha256",signature="' . $signature . '"';
  59. unset($headers['(request-target)']);
  60. $headers['Signature'] = $signatureHeader;
  61. return $headers;
  62. }
  63. /**
  64. * @param array|string $body array or json string $body
  65. */
  66. private static function _digest(array|string $body): string
  67. {
  68. if (\is_array($body)) {
  69. $body = json_encode($body);
  70. }
  71. return base64_encode(hash('sha256', $body, true));
  72. }
  73. /**
  74. * @throws Exception
  75. */
  76. protected static function _headersToSign(string $url, string|bool $digest = false): array
  77. {
  78. $date = new DateTime('UTC');
  79. $headers = [
  80. '(request-target)' => 'post ' . parse_url($url, \PHP_URL_PATH),
  81. 'Date' => $date->format('D, d M Y H:i:s \G\M\T'),
  82. 'Host' => parse_url($url, \PHP_URL_HOST),
  83. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams", application/activity+json, application/json',
  84. 'User-Agent' => 'GNU social ActivityPub Plugin - ' . GNUSOCIAL_ENGINE_URL,
  85. 'Content-Type' => 'application/activity+json',
  86. ];
  87. if ($digest) {
  88. $headers['Digest'] = 'SHA-256=' . $digest;
  89. }
  90. return $headers;
  91. }
  92. private static function _headersToSigningString(array $headers): string
  93. {
  94. return implode("\n", array_map(fn ($k, $v) => mb_strtolower($k) . ': ' . $v, array_keys($headers), $headers));
  95. }
  96. public static function parseSignatureHeader(string $signature): array
  97. {
  98. $parts = explode(',', $signature);
  99. $signatureData = [];
  100. foreach ($parts as $part) {
  101. if (preg_match('/(.+)="(.+)"/', $part, $match)) {
  102. $signatureData[$match[1]] = $match[2];
  103. }
  104. }
  105. if (!isset($signatureData['keyId'])) {
  106. return [
  107. 'error' => 'No keyId was found in the signature header. Found: ' . implode(', ', array_keys($signatureData)),
  108. ];
  109. }
  110. if (!filter_var($signatureData['keyId'], \FILTER_VALIDATE_URL)) {
  111. return [
  112. 'error' => 'keyId is not a URL: ' . $signatureData['keyId'],
  113. ];
  114. }
  115. if (!isset($signatureData['headers']) || !isset($signatureData['signature'])) {
  116. return [
  117. 'error' => 'Signature is missing headers or signature parts',
  118. ];
  119. }
  120. return $signatureData;
  121. }
  122. public static function verify(string $publicKey, array $signatureData, array $inputHeaders, string $path, string $body): array
  123. {
  124. // We need this because the used Request headers fields specified by Signature are in lower case.
  125. $headersContent = array_change_key_case($inputHeaders, \CASE_LOWER);
  126. $digest = 'SHA-256=' . base64_encode(hash('sha256', $body, true));
  127. $headersToSign = [];
  128. foreach (explode(' ', $signatureData['headers']) as $h) {
  129. if ($h == '(request-target)') {
  130. $headersToSign[$h] = 'post ' . $path;
  131. } elseif ($h == 'digest') {
  132. $headersToSign[$h] = $digest;
  133. } elseif (\array_key_exists($h, $headersContent)) {
  134. $headersToSign[$h] = $headersContent[$h];
  135. }
  136. }
  137. $signingString = self::_headersToSigningString($headersToSign);
  138. $verified = openssl_verify($signingString, base64_decode($signatureData['signature']), $publicKey, \OPENSSL_ALGO_SHA256);
  139. return [$verified, $signingString];
  140. }
  141. }