4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\BaseObject;
9 use Friendica\Core\Config;
10 use Friendica\Database\DBA;
11 use Friendica\Model\User;
12 use Friendica\Protocol\ActivityPub;
15 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
17 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
19 * Other parts of the code for HTTP signing are taken from the Osada project.
20 * https://framagit.org/macgirvin/osada
22 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
27 // See draft-cavage-http-signatures-08
28 public static function verifyMagic($key)
34 'header_signed' => false,
35 'header_valid' => false
38 // Decide if $data arrived via controller submission or curl.
40 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
42 foreach ($_SERVER as $k => $v) {
43 if (strpos($k, 'HTTP_') === 0) {
44 $field = str_replace('_', '-', strtolower(substr($k, 5)));
45 $headers[$field] = $v;
51 $sig_block = self::parseSigheader($headers['authorization']);
54 logger('no signature provided.');
58 $result['header_signed'] = true;
60 $signed_headers = $sig_block['headers'];
61 if (!$signed_headers) {
62 $signed_headers = ['date'];
66 foreach ($signed_headers as $h) {
67 if (array_key_exists($h, $headers)) {
68 $signed_data .= $h . ': ' . $headers[$h] . "\n";
70 if (strpos($h, '.')) {
75 $signed_data = rtrim($signed_data, "\n");
77 $algorithm = 'sha512';
79 if ($key && function_exists($key)) {
80 $result['signer'] = $sig_block['keyId'];
81 $key = $key($sig_block['keyId']);
84 logger('Got keyID ' . $sig_block['keyId']);
90 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
92 logger('verified: ' . $x, LOGGER_DEBUG);
99 $result['header_valid'] = true;
109 * @param string $prvkey
110 * @param string $keyid (optional, default 'Key')
114 public static function createSig($head, $prvkey, $keyid = 'Key')
116 $return_headers = [];
119 $algorithm = 'rsa-sha512';
121 $x = self::sign($head, $prvkey, $alg);
123 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
124 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
126 $sighead = 'Authorization: Signature ' . $headerval;
129 foreach ($head as $k => $v) {
130 $return_headers[] = $k . ': ' . $v;
134 $return_headers[] = $sighead;
136 return $return_headers;
143 * @param string $prvkey
144 * @param string $alg (optional) default 'sha256'
148 private static function sign($head, $prvkey, $alg = 'sha256')
154 foreach ($head as $k => $v) {
155 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
159 $fields .= strtolower($k);
161 // strip the trailing linefeed
162 $headers = rtrim($headers, "\n");
164 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
166 $ret['headers'] = $fields;
167 $ret['signature'] = $sig;
175 * @param string $header
176 * @return array associate array with
177 * - \e string \b keyID
178 * - \e string \b algorithm
179 * - \e array \b headers
180 * - \e string \b signature
182 public static function parseSigheader($header)
187 // if the header is encrypted, decrypt with (default) site private key and continue
188 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
189 $header = self::decryptSigheader($header);
192 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
193 $ret['keyId'] = $matches[1];
196 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
197 $ret['algorithm'] = $matches[1];
200 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
201 $ret['headers'] = explode(' ', $matches[1]);
204 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
205 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
208 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
209 $ret['headers'] = ['date'];
218 * @param string $header
219 * @param string $prvkey (optional), if not set use site private key
221 * @return array|string associative array, empty string if failue
225 * - \e string \b data
227 private static function decryptSigheader($header, $prvkey = null)
229 $iv = $key = $alg = $data = null;
232 $prvkey = Config::get('system', 'prvkey');
237 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
241 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
245 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
249 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
253 if ($iv && $key && $alg && $data) {
254 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
261 * Functions for ActivityPub
264 public static function transmit($data, $target, $uid)
266 $owner = User::getOwnerDataById($uid);
272 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
274 // Header data that is about to be signed.
275 $host = parse_url($target, PHP_URL_HOST);
276 $path = parse_url($target, PHP_URL_PATH);
277 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
278 $content_length = strlen($content);
280 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
282 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
284 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
286 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
288 $headers[] = 'Content-Type: application/activity+json';
290 Network::post($target, $content, $headers);
291 $return_code = BaseObject::getApp()->get_curl_code();
293 logger('Transmit to ' . $target . ' returned ' . $return_code);
296 public static function getSigner($content, $http_headers)
298 $object = json_decode($content, true);
300 if (empty($object)) {
304 $actor = JsonLD::fetchElement($object, 'actor', 'id');
307 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
309 // First take every header
310 foreach ($http_headers as $k => $v) {
311 $field = str_replace('_', '-', strtolower($k));
312 $headers[$field] = $v;
315 // Now add every http header
316 foreach ($http_headers as $k => $v) {
317 if (strpos($k, 'HTTP_') === 0) {
318 $field = str_replace('_', '-', strtolower(substr($k, 5)));
319 $headers[$field] = $v;
323 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
325 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
330 foreach ($sig_block['headers'] as $h) {
331 if (array_key_exists($h, $headers)) {
332 $signed_data .= $h . ': ' . $headers[$h] . "\n";
335 $signed_data = rtrim($signed_data, "\n");
337 if (empty($signed_data)) {
343 if ($sig_block['algorithm'] === 'rsa-sha256') {
344 $algorithm = 'sha256';
347 if ($sig_block['algorithm'] === 'rsa-sha512') {
348 $algorithm = 'sha512';
351 if (empty($algorithm)) {
355 $key = self::fetchKey($sig_block['keyId'], $actor);
361 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
365 // Check the digest when it is part of the signed data
366 if (in_array('digest', $sig_block['headers'])) {
367 $digest = explode('=', $headers['digest'], 2);
368 if ($digest[0] === 'SHA-256') {
371 if ($digest[0] === 'SHA-512') {
375 /// @todo add all hashes from the rfc
377 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
382 // Check the content-length when it is part of the signed data
383 if (in_array('content-length', $sig_block['headers'])) {
384 if (strlen($content) != $headers['content-length']) {
392 private static function fetchKey($id, $actor)
394 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
396 $profile = ActivityPub::fetchprofile($url);
397 if (!empty($profile)) {
398 logger('Taking key from id ' . $id, LOGGER_DEBUG);
399 return ['url' => $url, 'pubkey' => $profile['pubkey']];
400 } elseif ($url != $actor) {
401 $profile = ActivityPub::fetchprofile($actor);
402 if (!empty($profile)) {
403 logger('Taking key from actor ' . $actor, LOGGER_DEBUG);
404 return ['url' => $actor, 'pubkey' => $profile['pubkey']];