HTTPSignature.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. * @author Aaron Parecki <aaron@parecki.com>
  19. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  20. * @link https://github.com/aaronpk/Nautilus/blob/master/app/ActivityPub/HTTPSignature.php
  21. */
  22. namespace Plugin\ActivityPub\Util;
  23. use App\Entity\Actor;
  24. use DateTime;
  25. use Exception;
  26. use Plugin\ActivityPub\Entity\ActivitypubRsa;
  27. class HTTPSignature
  28. {
  29. /**
  30. * Sign a message with an Actor
  31. *
  32. * @param Actor $user Actor signing
  33. * @param string $url Inbox url
  34. * @param string|bool $body Data to sign (optional)
  35. * @param array $addlHeaders Additional headers (optional)
  36. * @return array Headers to be used in request
  37. * @throws Exception Attempted to sign something that belongs to an Actor we don't own
  38. */
  39. public static function sign(Actor $user, string $url, string|bool $body = false, array $addlHeaders = []): array
  40. {
  41. $digest = false;
  42. if ($body) {
  43. $digest = self::_digest($body);
  44. }
  45. $headers = self::_headersToSign($url, $digest);
  46. $headers = array_merge($headers, $addlHeaders);
  47. $stringToSign = self::_headersToSigningString($headers);
  48. $signedHeaders = implode(' ', array_map('strtolower', array_keys($headers)));
  49. $actor_private_key = ActivitypubRsa::getByActor($user)->getPrivateKey();
  50. // Intentionally unhandled exception, we want this to explode if that happens as it would be a bug
  51. $key = openssl_pkey_get_private($actor_private_key);
  52. openssl_sign($stringToSign, $signature, $key, OPENSSL_ALGO_SHA256);
  53. $signature = base64_encode($signature);
  54. $signatureHeader = 'keyId="' . $user->getUri() . '#public-key' . '",headers="' . $signedHeaders . '",algorithm="rsa-sha256",signature="' . $signature . '"';
  55. unset($headers['(request-target)']);
  56. $headers['Signature'] = $signatureHeader;
  57. return $headers;
  58. }
  59. /**
  60. * @param array|string $body array or json string $body
  61. * @return string
  62. */
  63. private static function _digest(array|string $body): string
  64. {
  65. if (is_array($body)) {
  66. $body = json_encode($body);
  67. }
  68. return base64_encode(hash('sha256', $body, true));
  69. }
  70. /**
  71. * @param string $url
  72. * @param string|bool $digest
  73. * @return array
  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. /**
  93. * @param array $headers
  94. * @return string
  95. */
  96. private static function _headersToSigningString(array $headers): string
  97. {
  98. return implode("\n", array_map(function ($k, $v) {
  99. return strtolower($k) . ': ' . $v;
  100. }, array_keys($headers), $headers));
  101. }
  102. /**
  103. * @param string $signature
  104. * @return array
  105. */
  106. public static function parseSignatureHeader(string $signature): array
  107. {
  108. $parts = explode(',', $signature);
  109. $signatureData = [];
  110. foreach ($parts as $part) {
  111. if (preg_match('/(.+)="(.+)"/', $part, $match)) {
  112. $signatureData[$match[1]] = $match[2];
  113. }
  114. }
  115. if (!isset($signatureData['keyId'])) {
  116. return [
  117. 'error' => 'No keyId was found in the signature header. Found: ' . implode(', ', array_keys($signatureData))
  118. ];
  119. }
  120. if (!filter_var($signatureData['keyId'], FILTER_VALIDATE_URL)) {
  121. return [
  122. 'error' => 'keyId is not a URL: ' . $signatureData['keyId']
  123. ];
  124. }
  125. if (!isset($signatureData['headers']) || !isset($signatureData['signature'])) {
  126. return [
  127. 'error' => 'Signature is missing headers or signature parts'
  128. ];
  129. }
  130. return $signatureData;
  131. }
  132. /**
  133. * @param string $publicKey
  134. * @param array $signatureData
  135. * @param array $inputHeaders
  136. * @param string $path
  137. * @param string $body
  138. * @return array
  139. */
  140. public static function verify(string $publicKey, array $signatureData, array $inputHeaders, string $path, string $body): array
  141. {
  142. // We need this because the used Request headers fields specified by Signature are in lower case.
  143. $headersContent = array_change_key_case($inputHeaders, CASE_LOWER);
  144. $digest = 'SHA-256=' . base64_encode(hash('sha256', $body, true));
  145. $headersToSign = [];
  146. foreach (explode(' ', $signatureData['headers']) as $h) {
  147. if ($h == '(request-target)') {
  148. $headersToSign[$h] = 'post ' . $path;
  149. } elseif ($h == 'digest') {
  150. $headersToSign[$h] = $digest;
  151. } elseif (array_key_exists($h, $headersContent)) {
  152. $headersToSign[$h] = $headersContent[$h];
  153. }
  154. }
  155. $signingString = self::_headersToSigningString($headersToSign);
  156. $verified = openssl_verify($signingString, base64_decode($signatureData['signature']), $publicKey, OPENSSL_ALGO_SHA256);
  157. return [$verified, $signingString];
  158. }
  159. }