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;
12 use Friendica\Model\User;
13 use Friendica\Model\APContact;
16 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
18 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
20 * Other parts of the code for HTTP signing are taken from the Osada project.
21 * https://framagit.org/macgirvin/osada
23 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
28 // See draft-cavage-http-signatures-08
30 * Verifies a magic request
34 * @return array with verification data
35 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
192 public static function parseSigheader($header)
197 // if the header is encrypted, decrypt with (default) site private key and continue
198 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
199 $header = self::decryptSigheader($header);
202 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
203 $ret['keyId'] = $matches[1];
206 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
207 $ret['algorithm'] = $matches[1];
209 $ret['algorithm'] = 'rsa-sha256';
212 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
213 $ret['headers'] = explode(' ', $matches[1]);
216 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
217 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
220 if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
221 $ret['headers'] = ['date'];
230 * @param string $header
231 * @param string $prvkey (optional), if not set use site private key
233 * @return array|string associative array, empty string if failue
237 * - \e string \b data
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
240 private static function decryptSigheader($header, $prvkey = null)
242 $iv = $key = $alg = $data = null;
245 $prvkey = DI::config()->get('system', 'prvkey');
250 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
254 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
258 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
262 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
266 if ($iv && $key && $alg && $data) {
267 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
274 * Functions for ActivityPub
278 * Transmit given data to a target for a user
280 * @param array $data Data that is about to be send
281 * @param string $target The URL of the inbox
282 * @param integer $uid User id of the sender
284 * @return boolean Was the transmission successful?
285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
287 public static function transmit($data, $target, $uid)
289 $owner = User::getOwnerDataById($uid);
295 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
297 // Header data that is about to be signed.
298 $host = parse_url($target, PHP_URL_HOST);
299 $path = parse_url($target, PHP_URL_PATH);
300 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
301 $content_length = strlen($content);
302 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
304 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
306 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
308 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
310 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
312 $headers[] = 'Content-Type: application/activity+json';
314 $postResult = Network::post($target, $content, $headers);
315 $return_code = $postResult->getReturnCode();
317 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
319 $success = ($return_code >= 200) && ($return_code <= 299);
321 self::setInboxStatus($target, $success);
327 * Set the delivery status for a given inbox
329 * @param string $url The URL of the inbox
330 * @param boolean $success Transmission status
332 static private function setInboxStatus($url, $success)
334 $now = DateTimeFormat::utcNow();
336 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
337 if (!DBA::isResult($status)) {
338 DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
339 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
343 $fields = ['success' => $now];
345 $fields = ['failure' => $now];
348 if ($status['failure'] > DBA::NULL_DATETIME) {
349 $new_previous_stamp = strtotime($status['failure']);
350 $old_previous_stamp = strtotime($status['previous']);
352 // Only set "previous" with at least one day difference.
353 // We use this to assure to not accidentally archive too soon.
354 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
355 $fields['previous'] = $status['failure'];
360 if ($status['success'] <= DBA::NULL_DATETIME) {
361 $stamp1 = strtotime($status['created']);
363 $stamp1 = strtotime($status['success']);
366 $stamp2 = strtotime($now);
367 $previous_stamp = strtotime($status['previous']);
369 // Archive the inbox when there had been failures for five days.
370 // Additionally ensure that at least one previous attempt has to be in between.
371 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
372 $fields['archive'] = true;
375 $fields['archive'] = false;
378 DBA::update('inbox-status', $fields, ['url' => $url]);
382 * Fetches JSON data for a user
384 * @param string $request request url
385 * @param integer $uid User id of the requester
387 * @return array JSON array
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
390 public static function fetch($request, $uid)
392 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
393 $curlResult = self::fetchRaw($request, $uid, false, $opts);
395 if (empty($curlResult)) {
399 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
403 $content = json_decode($curlResult->getBody(), true);
404 if (empty($content) || !is_array($content)) {
412 * Fetches raw data for a user
414 * @param string $request request url
415 * @param integer $uid User id of the requester
416 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
417 * @param array $opts (optional parameters) assoziative array with:
418 * 'accept_content' => supply Accept: header with 'accept_content' as the value
419 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
420 * 'http_auth' => username:password
421 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
422 * 'nobody' => only return the header
423 * 'cookiejar' => path to cookie jar file
425 * @return object CurlResult
426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
431 $owner = User::getOwnerDataById($uid);
436 // Header data that is about to be signed.
437 $host = parse_url($request, PHP_URL_HOST);
438 $path = parse_url($request, PHP_URL_PATH);
439 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
441 $headers = ['Date: ' . $date, 'Host: ' . $host];
443 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
445 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
447 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
452 if (!empty($opts['accept_content'])) {
453 $headers[] = 'Accept: ' . $opts['accept_content'];
457 $curl_opts['header'] = $headers;
459 $curlResult = Network::curl($request, false, $curl_opts);
460 $return_code = $curlResult->getReturnCode();
462 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
468 * Gets a signer from a given HTTP request
471 * @param $http_headers
473 * @return string Signer
474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
476 public static function getSigner($content, $http_headers)
478 if (empty($http_headers['HTTP_SIGNATURE'])) {
482 if (!empty($content)) {
483 $object = json_decode($content, true);
484 if (empty($object)) {
488 $actor = JsonLD::fetchElement($object, 'actor', 'id');
494 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
496 // First take every header
497 foreach ($http_headers as $k => $v) {
498 $field = str_replace('_', '-', strtolower($k));
499 $headers[$field] = $v;
502 // Now add every http header
503 foreach ($http_headers as $k => $v) {
504 if (strpos($k, 'HTTP_') === 0) {
505 $field = str_replace('_', '-', strtolower(substr($k, 5)));
506 $headers[$field] = $v;
510 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
512 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
517 foreach ($sig_block['headers'] as $h) {
518 if (array_key_exists($h, $headers)) {
519 $signed_data .= $h . ': ' . $headers[$h] . "\n";
522 $signed_data = rtrim($signed_data, "\n");
524 if (empty($signed_data)) {
530 if ($sig_block['algorithm'] === 'rsa-sha256') {
531 $algorithm = 'sha256';
534 if ($sig_block['algorithm'] === 'rsa-sha512') {
535 $algorithm = 'sha512';
538 if (empty($algorithm)) {
542 $key = self::fetchKey($sig_block['keyId'], $actor);
548 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
552 $hasGoodSignedContent = false;
554 // Check the digest when it is part of the signed data
555 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
556 $digest = explode('=', $headers['digest'], 2);
557 if ($digest[0] === 'SHA-256') {
560 if ($digest[0] === 'SHA-512') {
564 /// @todo add all hashes from the rfc
566 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
570 $hasGoodSignedContent = true;
573 // Check if the signed date field is in an acceptable range
574 if (in_array('date', $sig_block['headers'])) {
575 $diff = abs(strtotime($headers['date']) - time());
577 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
580 $hasGoodSignedContent = true;
583 // Check the content-length when it is part of the signed data
584 if (in_array('content-length', $sig_block['headers'])) {
585 if (strlen($content) != $headers['content-length']) {
590 // Ensure that the authentication had been done with some content
591 // Without this check someone could authenticate with fakeable data
592 if (!$hasGoodSignedContent) {
600 * fetches a key for a given id and actor
605 * @return array with actor url and public key
608 private static function fetchKey($id, $actor)
610 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
612 $profile = APContact::getByURL($url);
613 if (!empty($profile)) {
614 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
615 return ['url' => $url, 'pubkey' => $profile['pubkey']];
616 } elseif ($url != $actor) {
617 $profile = APContact::getByURL($actor);
618 if (!empty($profile)) {
619 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
620 return ['url' => $actor, 'pubkey' => $profile['pubkey']];