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];
209 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
210 $ret['headers'] = explode(' ', $matches[1]);
213 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
214 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
217 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
218 $ret['headers'] = ['date'];
227 * @param string $header
228 * @param string $prvkey (optional), if not set use site private key
230 * @return array|string associative array, empty string if failue
234 * - \e string \b data
236 private static function decryptSigheader($header, $prvkey = null)
238 $iv = $key = $alg = $data = null;
241 $prvkey = Config::get('system', 'prvkey');
246 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
250 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
254 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
258 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
262 if ($iv && $key && $alg && $data) {
263 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
270 * Functions for ActivityPub
274 * @brief Transmit given data to a target for a user
276 * @param array $data Data that is about to be send
277 * @param string $target The URL of the inbox
278 * @param integer $uid User id of the sender
280 * @return boolean Was the transmission successful?
282 public static function transmit($data, $target, $uid)
284 $owner = User::getOwnerDataById($uid);
290 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
292 // Header data that is about to be signed.
293 $host = parse_url($target, PHP_URL_HOST);
294 $path = parse_url($target, PHP_URL_PATH);
295 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
296 $content_length = strlen($content);
298 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
300 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
302 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
304 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
306 $headers[] = 'Content-Type: application/activity+json';
308 $postResult = Network::post($target, $content, $headers);
309 $return_code = $postResult->getReturnCode();
311 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
313 return ($return_code >= 200) && ($return_code <= 299);
317 * @brief Fetches JSON data for a user
319 * @param string $request request url
320 * @param integer $uid User id of the requester
322 * @return array JSON array
324 public static function fetch($request, $uid)
326 $owner = User::getOwnerDataById($uid);
332 // Header data that is about to be signed.
333 $host = parse_url($request, PHP_URL_HOST);
334 $path = parse_url($request, PHP_URL_PATH);
336 $headers = ['Host: ' . $host];
338 $signed_data = "(request-target): get " . $path . "\nhost: " . $host;
340 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
342 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) host",signature="' . $signature . '"';
344 $headers[] = 'Accept: application/activity+json, application/ld+json';
346 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
347 $return_code = $curlResult->getReturnCode();
349 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
351 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
355 $content = json_decode($curlResult->getBody(), true);
357 if (empty($content) || !is_array($content)) {
365 * @brief Gets a signer from a given HTTP request
368 * @param $http_headers
370 * @return signer string
372 public static function getSigner($content, $http_headers)
374 $object = json_decode($content, true);
376 if (empty($object)) {
380 $actor = JsonLD::fetchElement($object, 'actor', 'id');
383 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
385 // First take every header
386 foreach ($http_headers as $k => $v) {
387 $field = str_replace('_', '-', strtolower($k));
388 $headers[$field] = $v;
391 // Now add every http header
392 foreach ($http_headers as $k => $v) {
393 if (strpos($k, 'HTTP_') === 0) {
394 $field = str_replace('_', '-', strtolower(substr($k, 5)));
395 $headers[$field] = $v;
399 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
401 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
406 foreach ($sig_block['headers'] as $h) {
407 if (array_key_exists($h, $headers)) {
408 $signed_data .= $h . ': ' . $headers[$h] . "\n";
411 $signed_data = rtrim($signed_data, "\n");
413 if (empty($signed_data)) {
419 if ($sig_block['algorithm'] === 'rsa-sha256') {
420 $algorithm = 'sha256';
423 if ($sig_block['algorithm'] === 'rsa-sha512') {
424 $algorithm = 'sha512';
427 if (empty($algorithm)) {
431 $key = self::fetchKey($sig_block['keyId'], $actor);
437 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
441 // Check the digest when it is part of the signed data
442 if (in_array('digest', $sig_block['headers'])) {
443 $digest = explode('=', $headers['digest'], 2);
444 if ($digest[0] === 'SHA-256') {
447 if ($digest[0] === 'SHA-512') {
451 /// @todo add all hashes from the rfc
453 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
458 /// @todo Check if the signed date field is in an acceptable range
460 // Check the content-length when it is part of the signed data
461 if (in_array('content-length', $sig_block['headers'])) {
462 if (strlen($content) != $headers['content-length']) {
471 * @brief fetches a key for a given id and actor
476 * @return array with actor url and public key
478 private static function fetchKey($id, $actor)
480 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
482 $profile = APContact::getByURL($url);
483 if (!empty($profile)) {
484 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
485 return ['url' => $url, 'pubkey' => $profile['pubkey']];
486 } elseif ($url != $actor) {
487 $profile = APContact::getByURL($actor);
488 if (!empty($profile)) {
489 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
490 return ['url' => $actor, 'pubkey' => $profile['pubkey']];