httpsignature.php 6.3 KB

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