4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Logger;
11 use Friendica\Model\User;
12 use Friendica\Model\APContact;
15 * 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 * 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;
115 * @param string $prvkey
116 * @param string $keyid (optional, default 'Key')
120 public static function createSig($head, $prvkey, $keyid = 'Key')
122 $return_headers = [];
125 $algorithm = 'rsa-sha512';
127 $x = self::sign($head, $prvkey, $alg);
129 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
130 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
132 $sighead = 'Authorization: Signature ' . $headerval;
135 foreach ($head as $k => $v) {
136 $return_headers[] = $k . ': ' . $v;
140 $return_headers[] = $sighead;
142 return $return_headers;
147 * @param string $prvkey
148 * @param string $alg (optional) default 'sha256'
152 private static function sign($head, $prvkey, $alg = 'sha256')
158 foreach ($head as $k => $v) {
159 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
163 $fields .= strtolower($k);
165 // strip the trailing linefeed
166 $headers = rtrim($headers, "\n");
168 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
170 $ret['headers'] = $fields;
171 $ret['signature'] = $sig;
177 * @param string $header
178 * @return array associate array with
179 * - \e string \b keyID
180 * - \e string \b algorithm
181 * - \e array \b headers
182 * - \e string \b signature
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 public static function parseSigheader($header)
190 // if the header is encrypted, decrypt with (default) site private key and continue
191 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
192 $header = self::decryptSigheader($header);
195 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
196 $ret['keyId'] = $matches[1];
199 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
200 $ret['algorithm'] = $matches[1];
202 $ret['algorithm'] = 'rsa-sha256';
205 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
206 $ret['headers'] = explode(' ', $matches[1]);
209 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
210 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
213 if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
214 $ret['headers'] = ['date'];
221 * @param string $header
222 * @param string $prvkey (optional), if not set use site private key
224 * @return array|string associative array, empty string if failue
228 * - \e string \b data
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 private static function decryptSigheader($header, $prvkey = null)
233 $iv = $key = $alg = $data = null;
236 $prvkey = DI::config()->get('system', 'prvkey');
241 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
245 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
249 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
253 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
257 if ($iv && $key && $alg && $data) {
258 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
265 * Functions for ActivityPub
269 * Transmit given data to a target for a user
271 * @param array $data Data that is about to be send
272 * @param string $target The URL of the inbox
273 * @param integer $uid User id of the sender
275 * @return boolean Was the transmission successful?
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 public static function transmit($data, $target, $uid)
280 $owner = User::getOwnerDataById($uid);
286 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
288 // Header data that is about to be signed.
289 $host = parse_url($target, PHP_URL_HOST);
290 $path = parse_url($target, PHP_URL_PATH);
291 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
292 $content_length = strlen($content);
293 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
295 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
297 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
299 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
301 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
303 $headers[] = 'Content-Type: application/activity+json';
305 $postResult = Network::post($target, $content, $headers);
306 $return_code = $postResult->getReturnCode();
308 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
310 $success = ($return_code >= 200) && ($return_code <= 299);
312 self::setInboxStatus($target, $success);
318 * Set the delivery status for a given inbox
320 * @param string $url The URL of the inbox
321 * @param boolean $success Transmission status
323 static private function setInboxStatus($url, $success)
325 $now = DateTimeFormat::utcNow();
327 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
328 if (!DBA::isResult($status)) {
329 DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
330 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
334 $fields = ['success' => $now];
336 $fields = ['failure' => $now];
339 if ($status['failure'] > DBA::NULL_DATETIME) {
340 $new_previous_stamp = strtotime($status['failure']);
341 $old_previous_stamp = strtotime($status['previous']);
343 // Only set "previous" with at least one day difference.
344 // We use this to assure to not accidentally archive too soon.
345 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
346 $fields['previous'] = $status['failure'];
351 if ($status['success'] <= DBA::NULL_DATETIME) {
352 $stamp1 = strtotime($status['created']);
354 $stamp1 = strtotime($status['success']);
357 $stamp2 = strtotime($now);
358 $previous_stamp = strtotime($status['previous']);
360 // Archive the inbox when there had been failures for five days.
361 // Additionally ensure that at least one previous attempt has to be in between.
362 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
363 $fields['archive'] = true;
366 $fields['archive'] = false;
369 DBA::update('inbox-status', $fields, ['url' => $url]);
373 * Fetches JSON data for a user
375 * @param string $request request url
376 * @param integer $uid User id of the requester
378 * @return array JSON array
379 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
381 public static function fetch($request, $uid)
383 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
384 $curlResult = self::fetchRaw($request, $uid, false, $opts);
386 if (empty($curlResult)) {
390 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
394 $content = json_decode($curlResult->getBody(), true);
395 if (empty($content) || !is_array($content)) {
403 * Fetches raw data for a user
405 * @param string $request request url
406 * @param integer $uid User id of the requester
407 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
408 * @param array $opts (optional parameters) assoziative array with:
409 * 'accept_content' => supply Accept: header with 'accept_content' as the value
410 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
411 * 'http_auth' => username:password
412 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
413 * 'nobody' => only return the header
414 * 'cookiejar' => path to cookie jar file
416 * @return object CurlResult
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
422 $owner = User::getOwnerDataById($uid);
427 // Header data that is about to be signed.
428 $host = parse_url($request, PHP_URL_HOST);
429 $path = parse_url($request, PHP_URL_PATH);
430 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
432 $headers = ['Date: ' . $date, 'Host: ' . $host];
434 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
436 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
438 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
443 if (!empty($opts['accept_content'])) {
444 $headers[] = 'Accept: ' . $opts['accept_content'];
448 $curl_opts['header'] = $headers;
450 $curlResult = Network::curl($request, false, $curl_opts);
451 $return_code = $curlResult->getReturnCode();
453 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
459 * Gets a signer from a given HTTP request
462 * @param $http_headers
464 * @return string Signer
465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
467 public static function getSigner($content, $http_headers)
469 if (empty($http_headers['HTTP_SIGNATURE'])) {
473 if (!empty($content)) {
474 $object = json_decode($content, true);
475 if (empty($object)) {
479 $actor = JsonLD::fetchElement($object, 'actor', 'id');
485 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
487 // First take every header
488 foreach ($http_headers as $k => $v) {
489 $field = str_replace('_', '-', strtolower($k));
490 $headers[$field] = $v;
493 // Now add every http header
494 foreach ($http_headers as $k => $v) {
495 if (strpos($k, 'HTTP_') === 0) {
496 $field = str_replace('_', '-', strtolower(substr($k, 5)));
497 $headers[$field] = $v;
501 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
503 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
508 foreach ($sig_block['headers'] as $h) {
509 if (array_key_exists($h, $headers)) {
510 $signed_data .= $h . ': ' . $headers[$h] . "\n";
513 $signed_data = rtrim($signed_data, "\n");
515 if (empty($signed_data)) {
521 if ($sig_block['algorithm'] === 'rsa-sha256') {
522 $algorithm = 'sha256';
525 if ($sig_block['algorithm'] === 'rsa-sha512') {
526 $algorithm = 'sha512';
529 if (empty($algorithm)) {
533 $key = self::fetchKey($sig_block['keyId'], $actor);
539 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
543 $hasGoodSignedContent = false;
545 // Check the digest when it is part of the signed data
546 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
547 $digest = explode('=', $headers['digest'], 2);
548 if ($digest[0] === 'SHA-256') {
551 if ($digest[0] === 'SHA-512') {
555 /// @todo add all hashes from the rfc
557 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
561 $hasGoodSignedContent = true;
564 // Check if the signed date field is in an acceptable range
565 if (in_array('date', $sig_block['headers'])) {
566 $diff = abs(strtotime($headers['date']) - time());
568 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
571 $hasGoodSignedContent = true;
574 // Check the content-length when it is part of the signed data
575 if (in_array('content-length', $sig_block['headers'])) {
576 if (strlen($content) != $headers['content-length']) {
581 // Ensure that the authentication had been done with some content
582 // Without this check someone could authenticate with fakeable data
583 if (!$hasGoodSignedContent) {
591 * fetches a key for a given id and actor
596 * @return array with actor url and public key
599 private static function fetchKey($id, $actor)
601 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
603 $profile = APContact::getByURL($url);
604 if (!empty($profile)) {
605 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
606 return ['url' => $url, 'pubkey' => $profile['pubkey']];
607 } elseif ($url != $actor) {
608 $profile = APContact::getByURL($actor);
609 if (!empty($profile)) {
610 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
611 return ['url' => $actor, 'pubkey' => $profile['pubkey']];