HTTPSignature.php 6.2 KB

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