4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\BaseObject;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Database\DBA;
12 use Friendica\Model\User;
13 use Friendica\Model\APContact;
14 use Friendica\Protocol\ActivityPub;
17 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
19 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
21 * Other parts of the code for HTTP signing are taken from the Osada project.
22 * https://framagit.org/macgirvin/osada
24 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
29 // See draft-cavage-http-signatures-08
31 * @brief Verifies a magic request
35 * @return array with verification data
37 public static function verifyMagic($key)
43 'header_signed' => false,
44 'header_valid' => false
47 // Decide if $data arrived via controller submission or curl.
49 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
51 foreach ($_SERVER as $k => $v) {
52 if (strpos($k, 'HTTP_') === 0) {
53 $field = str_replace('_', '-', strtolower(substr($k, 5)));
54 $headers[$field] = $v;
60 $sig_block = self::parseSigheader($headers['authorization']);
63 Logger::log('no signature provided.');
67 $result['header_signed'] = true;
69 $signed_headers = $sig_block['headers'];
70 if (!$signed_headers) {
71 $signed_headers = ['date'];
75 foreach ($signed_headers as $h) {
76 if (array_key_exists($h, $headers)) {
77 $signed_data .= $h . ': ' . $headers[$h] . "\n";
79 if (strpos($h, '.')) {
84 $signed_data = rtrim($signed_data, "\n");
86 $algorithm = 'sha512';
88 if ($key && function_exists($key)) {
89 $result['signer'] = $sig_block['keyId'];
90 $key = $key($sig_block['keyId']);
93 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
99 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
101 Logger::log('verified: ' . $x, Logger::DEBUG);
108 $result['header_valid'] = true;
118 * @param string $prvkey
119 * @param string $keyid (optional, default 'Key')
123 public static function createSig($head, $prvkey, $keyid = 'Key')
125 $return_headers = [];
128 $algorithm = 'rsa-sha512';
130 $x = self::sign($head, $prvkey, $alg);
132 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
133 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
135 $sighead = 'Authorization: Signature ' . $headerval;
138 foreach ($head as $k => $v) {
139 $return_headers[] = $k . ': ' . $v;
143 $return_headers[] = $sighead;
145 return $return_headers;
152 * @param string $prvkey
153 * @param string $alg (optional) default 'sha256'
157 private static function sign($head, $prvkey, $alg = 'sha256')
163 foreach ($head as $k => $v) {
164 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
168 $fields .= strtolower($k);
170 // strip the trailing linefeed
171 $headers = rtrim($headers, "\n");
173 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
175 $ret['headers'] = $fields;
176 $ret['signature'] = $sig;
184 * @param string $header
185 * @return array associate array with
186 * - \e string \b keyID
187 * - \e string \b algorithm
188 * - \e array \b headers
189 * - \e string \b signature
191 public static function parseSigheader($header)
196 // if the header is encrypted, decrypt with (default) site private key and continue
197 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
198 $header = self::decryptSigheader($header);
201 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
202 $ret['keyId'] = $matches[1];
205 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
206 $ret['algorithm'] = $matches[1];
208 $ret['algorithm'] = 'rsa-sha256';
211 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
212 $ret['headers'] = explode(' ', $matches[1]);
215 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
216 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
219 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
220 $ret['headers'] = ['date'];
229 * @param string $header
230 * @param string $prvkey (optional), if not set use site private key
232 * @return array|string associative array, empty string if failue
236 * - \e string \b data
238 private static function decryptSigheader($header, $prvkey = null)
240 $iv = $key = $alg = $data = null;
243 $prvkey = Config::get('system', 'prvkey');
248 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
252 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
256 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
260 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
264 if ($iv && $key && $alg && $data) {
265 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
272 * Functions for ActivityPub
276 * @brief Transmit given data to a target for a user
278 * @param array $data Data that is about to be send
279 * @param string $target The URL of the inbox
280 * @param integer $uid User id of the sender
282 * @return boolean Was the transmission successful?
284 public static function transmit($data, $target, $uid)
286 $owner = User::getOwnerDataById($uid);
292 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
294 // Header data that is about to be signed.
295 $host = parse_url($target, PHP_URL_HOST);
296 $path = parse_url($target, PHP_URL_PATH);
297 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
298 $content_length = strlen($content);
300 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
302 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
304 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
306 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
308 $headers[] = 'Content-Type: application/activity+json';
310 $postResult = Network::post($target, $content, $headers);
311 $return_code = $postResult->getReturnCode();
313 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
315 return ($return_code >= 200) && ($return_code <= 299);
319 * @brief Fetches JSON data for a user
321 * @param string $request request url
322 * @param integer $uid User id of the requester
324 * @return array JSON array
326 public static function fetch($request, $uid)
328 $owner = User::getOwnerDataById($uid);
334 // Header data that is about to be signed.
335 $host = parse_url($request, PHP_URL_HOST);
336 $path = parse_url($request, PHP_URL_PATH);
338 $headers = ['Host: ' . $host];
340 $signed_data = "(request-target): get " . $path . "\nhost: " . $host;
342 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
344 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) host",signature="' . $signature . '"';
346 $headers[] = 'Accept: application/activity+json, application/ld+json';
348 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
349 $return_code = $curlResult->getReturnCode();
351 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
353 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
357 $content = json_decode($curlResult->getBody(), true);
359 if (empty($content) || !is_array($content)) {
367 * @brief Gets a signer from a given HTTP request
370 * @param $http_headers
372 * @return signer string
374 public static function getSigner($content, $http_headers)
376 $object = json_decode($content, true);
378 if (empty($object)) {
382 $actor = JsonLD::fetchElement($object, 'actor', 'id');
385 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
387 // First take every header
388 foreach ($http_headers as $k => $v) {
389 $field = str_replace('_', '-', strtolower($k));
390 $headers[$field] = $v;
393 // Now add every http header
394 foreach ($http_headers as $k => $v) {
395 if (strpos($k, 'HTTP_') === 0) {
396 $field = str_replace('_', '-', strtolower(substr($k, 5)));
397 $headers[$field] = $v;
401 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
403 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
408 foreach ($sig_block['headers'] as $h) {
409 if (array_key_exists($h, $headers)) {
410 $signed_data .= $h . ': ' . $headers[$h] . "\n";
413 $signed_data = rtrim($signed_data, "\n");
415 if (empty($signed_data)) {
421 if ($sig_block['algorithm'] === 'rsa-sha256') {
422 $algorithm = 'sha256';
425 if ($sig_block['algorithm'] === 'rsa-sha512') {
426 $algorithm = 'sha512';
429 if (empty($algorithm)) {
433 $key = self::fetchKey($sig_block['keyId'], $actor);
439 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
443 // Check the digest when it is part of the signed data
444 if (in_array('digest', $sig_block['headers'])) {
445 $digest = explode('=', $headers['digest'], 2);
446 if ($digest[0] === 'SHA-256') {
449 if ($digest[0] === 'SHA-512') {
453 /// @todo add all hashes from the rfc
455 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
460 /// @todo Check if the signed date field is in an acceptable range
462 // Check the content-length when it is part of the signed data
463 if (in_array('content-length', $sig_block['headers'])) {
464 if (strlen($content) != $headers['content-length']) {
473 * @brief fetches a key for a given id and actor
478 * @return array with actor url and public key
480 private static function fetchKey($id, $actor)
482 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
484 $profile = APContact::getByURL($url);
485 if (!empty($profile)) {
486 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
487 return ['url' => $url, 'pubkey' => $profile['pubkey']];
488 } elseif ($url != $actor) {
489 $profile = APContact::getByURL($actor);
490 if (!empty($profile)) {
491 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
492 return ['url' => $actor, 'pubkey' => $profile['pubkey']];