4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Model\User;
12 use Friendica\Model\APContact;
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
29 * @brief Verifies a magic request
33 * @return array with verification data
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
36 public static function verifyMagic($key)
42 'header_signed' => false,
43 'header_valid' => false
46 // Decide if $data arrived via controller submission or curl.
48 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
50 foreach ($_SERVER as $k => $v) {
51 if (strpos($k, 'HTTP_') === 0) {
52 $field = str_replace('_', '-', strtolower(substr($k, 5)));
53 $headers[$field] = $v;
59 $sig_block = self::parseSigheader($headers['authorization']);
62 Logger::log('no signature provided.');
66 $result['header_signed'] = true;
68 $signed_headers = $sig_block['headers'];
69 if (!$signed_headers) {
70 $signed_headers = ['date'];
74 foreach ($signed_headers as $h) {
75 if (array_key_exists($h, $headers)) {
76 $signed_data .= $h . ': ' . $headers[$h] . "\n";
78 if (strpos($h, '.')) {
83 $signed_data = rtrim($signed_data, "\n");
85 $algorithm = 'sha512';
87 if ($key && function_exists($key)) {
88 $result['signer'] = $sig_block['keyId'];
89 $key = $key($sig_block['keyId']);
92 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
98 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
100 Logger::log('verified: ' . $x, Logger::DEBUG);
107 $result['header_valid'] = true;
117 * @param string $prvkey
118 * @param string $keyid (optional, default 'Key')
122 public static function createSig($head, $prvkey, $keyid = 'Key')
124 $return_headers = [];
127 $algorithm = 'rsa-sha512';
129 $x = self::sign($head, $prvkey, $alg);
131 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
132 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
134 $sighead = 'Authorization: Signature ' . $headerval;
137 foreach ($head as $k => $v) {
138 $return_headers[] = $k . ': ' . $v;
142 $return_headers[] = $sighead;
144 return $return_headers;
151 * @param string $prvkey
152 * @param string $alg (optional) default 'sha256'
156 private static function sign($head, $prvkey, $alg = 'sha256')
162 foreach ($head as $k => $v) {
163 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
167 $fields .= strtolower($k);
169 // strip the trailing linefeed
170 $headers = rtrim($headers, "\n");
172 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
174 $ret['headers'] = $fields;
175 $ret['signature'] = $sig;
183 * @param string $header
184 * @return array associate array with
185 * - \e string \b keyID
186 * - \e string \b algorithm
187 * - \e array \b headers
188 * - \e string \b signature
189 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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 (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($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
237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239 private static function decryptSigheader($header, $prvkey = null)
241 $iv = $key = $alg = $data = null;
244 $prvkey = Config::get('system', 'prvkey');
249 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
253 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
257 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
261 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
265 if ($iv && $key && $alg && $data) {
266 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
273 * Functions for ActivityPub
277 * @brief Transmit given data to a target for a user
279 * @param array $data Data that is about to be send
280 * @param string $target The URL of the inbox
281 * @param integer $uid User id of the sender
283 * @return boolean Was the transmission successful?
284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286 public static function transmit($data, $target, $uid)
288 $owner = User::getOwnerDataById($uid);
294 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
296 // Header data that is about to be signed.
297 $host = parse_url($target, PHP_URL_HOST);
298 $path = parse_url($target, PHP_URL_PATH);
299 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
300 $content_length = strlen($content);
301 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
303 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
305 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
307 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
309 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
311 $headers[] = 'Content-Type: application/activity+json';
313 $postResult = Network::post($target, $content, $headers);
314 $return_code = $postResult->getReturnCode();
316 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
318 $success = ($return_code >= 200) && ($return_code <= 299);
320 self::setInboxStatus($target, $success);
326 * @brief Set the delivery status for a given inbox
328 * @param string $url The URL of the inbox
329 * @param boolean $success Transmission status
331 static private function setInboxStatus($url, $success)
333 $now = DateTimeFormat::utcNow();
335 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
336 if (!DBA::isResult($status)) {
337 DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
338 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
342 $fields = ['success' => $now];
344 $fields = ['failure' => $now];
347 if ($status['failure'] > DBA::NULL_DATETIME) {
348 $new_previous_stamp = strtotime($status['failure']);
349 $old_previous_stamp = strtotime($status['previous']);
351 // Only set "previous" with at least one day difference.
352 // We use this to assure to not accidentally archive too soon.
353 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
354 $fields['previous'] = $status['failure'];
359 if ($status['success'] <= DBA::NULL_DATETIME) {
360 $stamp1 = strtotime($status['created']);
362 $stamp1 = strtotime($status['success']);
365 $stamp2 = strtotime($now);
366 $previous_stamp = strtotime($status['previous']);
368 // Archive the inbox when there had been failures for five days.
369 // Additionally ensure that at least one previous attempt has to be in between.
370 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
371 $fields['archive'] = true;
374 $fields['archive'] = false;
377 DBA::update('inbox-status', $fields, ['url' => $url]);
381 * @brief Fetches JSON data for a user
383 * @param string $request request url
384 * @param integer $uid User id of the requester
386 * @return array JSON array
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 public static function fetch($request, $uid)
391 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
392 $curlResult = self::fetchRaw($request, $uid, false, $opts);
394 if (empty($curlResult)) {
398 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
402 $content = json_decode($curlResult->getBody(), true);
403 if (empty($content) || !is_array($content)) {
411 * @brief Fetches raw data for a user
413 * @param string $request request url
414 * @param integer $uid User id of the requester
415 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
416 * @param array $opts (optional parameters) assoziative array with:
417 * 'accept_content' => supply Accept: header with 'accept_content' as the value
418 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
419 * 'http_auth' => username:password
420 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
421 * 'nobody' => only return the header
422 * 'cookiejar' => path to cookie jar file
424 * @return object CurlResult
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
427 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
430 $owner = User::getOwnerDataById($uid);
435 // Header data that is about to be signed.
436 $host = parse_url($request, PHP_URL_HOST);
437 $path = parse_url($request, PHP_URL_PATH);
438 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
440 $headers = ['Date: ' . $date, 'Host: ' . $host];
442 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
444 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
446 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
451 if (!empty($opts['accept_content'])) {
452 $headers[] = 'Accept: ' . $opts['accept_content'];
456 $curl_opts['header'] = $headers;
458 $curlResult = Network::curl($request, false, $curl_opts);
459 $return_code = $curlResult->getReturnCode();
461 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
467 * @brief Gets a signer from a given HTTP request
470 * @param $http_headers
472 * @return string Signer
473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475 public static function getSigner($content, $http_headers)
477 if (empty($http_headers['HTTP_SIGNATURE'])) {
481 if (!empty($content)) {
482 $object = json_decode($content, true);
483 if (empty($object)) {
487 $actor = JsonLD::fetchElement($object, 'actor', 'id');
493 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
495 // First take every header
496 foreach ($http_headers as $k => $v) {
497 $field = str_replace('_', '-', strtolower($k));
498 $headers[$field] = $v;
501 // Now add every http header
502 foreach ($http_headers as $k => $v) {
503 if (strpos($k, 'HTTP_') === 0) {
504 $field = str_replace('_', '-', strtolower(substr($k, 5)));
505 $headers[$field] = $v;
509 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
511 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
516 foreach ($sig_block['headers'] as $h) {
517 if (array_key_exists($h, $headers)) {
518 $signed_data .= $h . ': ' . $headers[$h] . "\n";
521 $signed_data = rtrim($signed_data, "\n");
523 if (empty($signed_data)) {
529 if ($sig_block['algorithm'] === 'rsa-sha256') {
530 $algorithm = 'sha256';
533 if ($sig_block['algorithm'] === 'rsa-sha512') {
534 $algorithm = 'sha512';
537 if (empty($algorithm)) {
541 $key = self::fetchKey($sig_block['keyId'], $actor);
547 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
551 $hasGoodSignedContent = false;
553 // Check the digest when it is part of the signed data
554 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
555 $digest = explode('=', $headers['digest'], 2);
556 if ($digest[0] === 'SHA-256') {
559 if ($digest[0] === 'SHA-512') {
563 /// @todo add all hashes from the rfc
565 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
569 $hasGoodSignedContent = true;
572 // Check if the signed date field is in an acceptable range
573 if (in_array('date', $sig_block['headers'])) {
574 $diff = abs(strtotime($headers['date']) - time());
576 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
579 $hasGoodSignedContent = true;
582 // Check the content-length when it is part of the signed data
583 if (in_array('content-length', $sig_block['headers'])) {
584 if (strlen($content) != $headers['content-length']) {
589 // Ensure that the authentication had been done with some content
590 // Without this check someone could authenticate with fakeable data
591 if (!$hasGoodSignedContent) {
599 * @brief fetches a key for a given id and actor
604 * @return array with actor url and public key
607 private static function fetchKey($id, $actor)
609 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
611 $profile = APContact::getByURL($url);
612 if (!empty($profile)) {
613 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
614 return ['url' => $url, 'pubkey' => $profile['pubkey']];
615 } elseif ($url != $actor) {
616 $profile = APContact::getByURL($actor);
617 if (!empty($profile)) {
618 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
619 return ['url' => $actor, 'pubkey' => $profile['pubkey']];