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 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
24 // See draft-cavage-http-signatures-08
25 public static function verifyMagic($key)
31 'header_signed' => false,
32 'header_valid' => false
35 // Decide if $data arrived via controller submission or curl.
37 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
39 foreach ($_SERVER as $k => $v) {
40 if (strpos($k, 'HTTP_') === 0) {
41 $field = str_replace('_', '-', strtolower(substr($k, 5)));
42 $headers[$field] = $v;
48 $sig_block = self::parseSigheader($headers['authorization']);
51 logger('no signature provided.');
55 $result['header_signed'] = true;
57 $signed_headers = $sig_block['headers'];
58 if (!$signed_headers) {
59 $signed_headers = ['date'];
63 foreach ($signed_headers as $h) {
64 if (array_key_exists($h, $headers)) {
65 $signed_data .= $h . ': ' . $headers[$h] . "\n";
67 if (strpos($h, '.')) {
72 $signed_data = rtrim($signed_data, "\n");
74 $algorithm = 'sha512';
76 if ($key && function_exists($key)) {
77 $result['signer'] = $sig_block['keyId'];
78 $key = $key($sig_block['keyId']);
81 logger('Got keyID ' . $sig_block['keyId']);
87 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
89 logger('verified: ' . $x, LOGGER_DEBUG);
96 $result['header_valid'] = true;
106 * @param string $prvkey
107 * @param string $keyid (optional, default 'Key')
111 public static function createSig($head, $prvkey, $keyid = 'Key')
113 $return_headers = [];
116 $algorithm = 'rsa-sha512';
118 $x = self::sign($head, $prvkey, $alg);
120 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
121 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
123 $sighead = 'Authorization: Signature ' . $headerval;
126 foreach ($head as $k => $v) {
127 $return_headers[] = $k . ': ' . $v;
131 $return_headers[] = $sighead;
133 return $return_headers;
140 * @param string $prvkey
141 * @param string $alg (optional) default 'sha256'
145 private static function sign($head, $prvkey, $alg = 'sha256')
151 foreach ($head as $k => $v) {
152 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
156 $fields .= strtolower($k);
158 // strip the trailing linefeed
159 $headers = rtrim($headers, "\n");
161 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
163 $ret['headers'] = $fields;
164 $ret['signature'] = $sig;
172 * @param string $header
173 * @return array associate array with
174 * - \e string \b keyID
175 * - \e string \b algorithm
176 * - \e array \b headers
177 * - \e string \b signature
179 public static function parseSigheader($header)
184 // if the header is encrypted, decrypt with (default) site private key and continue
185 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
186 $header = self::decryptSigheader($header);
189 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
190 $ret['keyId'] = $matches[1];
193 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
194 $ret['algorithm'] = $matches[1];
197 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
198 $ret['headers'] = explode(' ', $matches[1]);
201 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
202 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
205 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
206 $ret['headers'] = ['date'];
215 * @param string $header
216 * @param string $prvkey (optional), if not set use site private key
218 * @return array|string associative array, empty string if failue
222 * - \e string \b data
224 private static function decryptSigheader($header, $prvkey = null)
226 $iv = $key = $alg = $data = null;
229 $prvkey = Config::get('system', 'prvkey');
234 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
238 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
242 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
246 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
250 if ($iv && $key && $alg && $data) {
251 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
258 * Functions for ActivityPub
261 public static function transmit($data, $target, $uid)
263 $owner = User::getOwnerDataById($uid);
269 $content = json_encode($data);
271 // Header data that is about to be signed.
272 $host = parse_url($target, PHP_URL_HOST);
273 $path = parse_url($target, PHP_URL_PATH);
274 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
275 $content_length = strlen($content);
277 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
279 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
281 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
283 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
285 $headers[] = 'Content-Type: application/activity+json';
287 Network::post($target, $content, $headers);
288 $return_code = BaseObject::getApp()->get_curl_code();
290 logger('Transmit to ' . $target . ' returned ' . $return_code);
293 public static function verifyAP($content, $http_headers)
295 $object = json_decode($content, true);
297 if (empty($object)) {
301 $actor = JsonLD::fetchElement($object, 'actor', 'id');
304 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
306 // First take every header
307 foreach ($http_headers as $k => $v) {
308 $field = str_replace('_', '-', strtolower($k));
309 $headers[$field] = $v;
312 // Now add every http header
313 foreach ($http_headers as $k => $v) {
314 if (strpos($k, 'HTTP_') === 0) {
315 $field = str_replace('_', '-', strtolower(substr($k, 5)));
316 $headers[$field] = $v;
320 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
322 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
327 foreach ($sig_block['headers'] as $h) {
328 if (array_key_exists($h, $headers)) {
329 $signed_data .= $h . ': ' . $headers[$h] . "\n";
332 $signed_data = rtrim($signed_data, "\n");
334 if (empty($signed_data)) {
340 if ($sig_block['algorithm'] === 'rsa-sha256') {
341 $algorithm = 'sha256';
344 if ($sig_block['algorithm'] === 'rsa-sha512') {
345 $algorithm = 'sha512';
348 if (empty($algorithm)) {
352 $key = self::fetchKey($sig_block['keyId'], $actor);
358 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
362 // Check the digest when it is part of the signed data
363 if (in_array('digest', $sig_block['headers'])) {
364 $digest = explode('=', $headers['digest'], 2);
365 if ($digest[0] === 'SHA-256') {
368 if ($digest[0] === 'SHA-512') {
372 /// @todo add all hashes from the rfc
374 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
379 // Check the content-length when it is part of the signed data
380 if (in_array('content-length', $sig_block['headers'])) {
381 if (strlen($content) != $headers['content-length']) {
390 private static function fetchKey($id, $actor)
392 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
394 $profile = ActivityPub::fetchprofile($url);
395 if (!empty($profile)) {
396 return $profile['pubkey'];
397 } elseif ($url != $actor) {
398 $profile = ActivityPub::fetchprofile($actor);
399 if (!empty($profile)) {
400 return $profile['pubkey'];