3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
24 use Friendica\Core\Logger;
25 use Friendica\Database\Database;
26 use Friendica\Database\DBA;
28 use Friendica\Model\APContact;
29 use Friendica\Model\Contact;
30 use Friendica\Model\User;
31 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
32 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
37 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
39 * Other parts of the code for HTTP signing are taken from the Osada project.
40 * https://framagit.org/macgirvin/osada
42 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
47 // See draft-cavage-http-signatures-08
49 * Verifies a magic request
53 * @return array with verification data
54 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 public static function verifyMagic($key)
62 'header_signed' => false,
63 'header_valid' => false
66 // Decide if $data arrived via controller submission or curl.
68 $headers['(request-target)'] = strtolower(DI::args()->getMethod()).' '.$_SERVER['REQUEST_URI'];
70 foreach ($_SERVER as $k => $v) {
71 if (strpos($k, 'HTTP_') === 0) {
72 $field = str_replace('_', '-', strtolower(substr($k, 5)));
73 $headers[$field] = $v;
79 $sig_block = self::parseSigheader($headers['authorization']);
82 Logger::notice('no signature provided.');
86 $result['header_signed'] = true;
88 $signed_headers = $sig_block['headers'];
89 if (!$signed_headers) {
90 $signed_headers = ['date'];
94 foreach ($signed_headers as $h) {
95 if (array_key_exists($h, $headers)) {
96 $signed_data .= $h . ': ' . $headers[$h] . "\n";
98 if (strpos($h, '.')) {
103 $signed_data = rtrim($signed_data, "\n");
105 $algorithm = 'sha512';
107 if ($key && function_exists($key)) {
108 $result['signer'] = $sig_block['keyId'];
109 $key = $key($sig_block['keyId']);
112 Logger::info('Got keyID ' . $sig_block['keyId']);
118 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
120 Logger::info('verified: ' . $x);
127 $result['header_valid'] = true;
135 * @param string $prvkey
136 * @param string $keyid (optional, default 'Key')
140 public static function createSig($head, $prvkey, $keyid = 'Key')
142 $return_headers = [];
144 $return_headers = $head;
148 $algorithm = 'rsa-sha512';
150 $x = self::sign($head, $prvkey, $alg);
152 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
153 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
155 $return_headers['Authorization'] = ['Signature ' . $headerval];
157 return $return_headers;
162 * @param string $prvkey
163 * @param string $alg (optional) default 'sha256'
167 private static function sign($head, $prvkey, $alg = 'sha256')
173 foreach ($head as $k => $v) {
175 $v = implode(', ', $v);
177 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
181 $fields .= strtolower($k);
183 // strip the trailing linefeed
184 $headers = rtrim($headers, "\n");
186 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
188 $ret['headers'] = $fields;
189 $ret['signature'] = $sig;
195 * @param string $header
196 * @return array associative array with
197 * - \e string \b keyID
198 * - \e string \b created
199 * - \e string \b expires
200 * - \e string \b algorithm
201 * - \e array \b headers
202 * - \e string \b signature
203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
205 public static function parseSigheader($header)
207 // Remove obsolete folds
208 $header = preg_replace('/\n\s+/', ' ', $header);
210 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
212 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
214 $regex = "/($token+)=($quotedString|$token+)/ism";
217 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
220 foreach ($matches as $match) {
221 $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
224 // if the header is encrypted, decrypt with (default) site private key and continue
225 if (!empty($headers['iv'])) {
226 $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
227 return self::parseSigheader($header);
231 'keyId' => $headers['keyId'] ?? '',
232 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
233 'created' => $headers['created'] ?? null,
234 'expires' => $headers['expires'] ?? null,
235 'headers' => explode(' ', $headers['headers'] ?? ''),
236 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
239 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
240 $return['headers'] = ['date'];
247 * @param array $headers Signature headers
248 * @param string $prvkey The site private key
249 * @return string Decrypted signature string
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 private static function decryptSigheader(array $headers, string $prvkey)
254 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
255 return Crypto::unencapsulate($headers, $prvkey);
262 * Functions for ActivityPub
266 * Transmit given data to a target for a user
268 * @param array $data Data that is about to be send
269 * @param string $target The URL of the inbox
270 * @param integer $uid User id of the sender
272 * @return boolean Was the transmission successful?
273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275 public static function transmit($data, $target, $uid)
277 $owner = User::getOwnerDataById($uid);
283 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
285 // Header data that is about to be signed.
286 $host = parse_url($target, PHP_URL_HOST);
287 $path = parse_url($target, PHP_URL_PATH);
288 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
289 $content_length = strlen($content);
290 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
294 'Content-Length' => $content_length,
299 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
301 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
303 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
305 $headers['Content-Type'] = 'application/activity+json';
307 $postResult = DI::httpClient()->post($target, $content, $headers);
308 $return_code = $postResult->getReturnCode();
310 Logger::info('Transmit to ' . $target . ' returned ' . $return_code);
312 $success = ($return_code >= 200) && ($return_code <= 299);
314 self::setInboxStatus($target, $success);
320 * Set the delivery status for a given inbox
322 * @param string $url The URL of the inbox
323 * @param boolean $success Transmission status
324 * @param boolean $shared The inbox is a shared inbox
326 static public function setInboxStatus($url, $success, $shared = false)
328 $now = DateTimeFormat::utcNow();
330 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
331 if (!DBA::isResult($status)) {
332 DBA::insert('inbox-status', ['url' => $url, 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
333 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
337 $fields = ['success' => $now];
339 $fields = ['failure' => $now];
342 if ($status['failure'] > DBA::NULL_DATETIME) {
343 $new_previous_stamp = strtotime($status['failure']);
344 $old_previous_stamp = strtotime($status['previous']);
346 // Only set "previous" with at least one day difference.
347 // We use this to assure to not accidentally archive too soon.
348 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
349 $fields['previous'] = $status['failure'];
354 if ($status['success'] <= DBA::NULL_DATETIME) {
355 $stamp1 = strtotime($status['created']);
357 $stamp1 = strtotime($status['success']);
360 $stamp2 = strtotime($now);
361 $previous_stamp = strtotime($status['previous']);
363 // Archive the inbox when there had been failures for five days.
364 // Additionally ensure that at least one previous attempt has to be in between.
365 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
366 $fields['archive'] = true;
369 $fields['archive'] = false;
372 DBA::update('inbox-status', $fields, ['url' => $url]);
376 * Fetches JSON data for a user
378 * @param string $request request url
379 * @param integer $uid User id of the requester
381 * @return array JSON array
382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
384 public static function fetch($request, $uid)
386 $curlResult = self::fetchRaw($request, $uid);
388 if (empty($curlResult)) {
392 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
396 $content = json_decode($curlResult->getBody(), true);
397 if (empty($content) || !is_array($content)) {
405 * Fetches raw data for a user
407 * @param string $request request url
408 * @param integer $uid User id of the requester
409 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
410 * @param array $opts (optional parameters) assoziative array with:
411 * 'accept_content' => supply Accept: header with 'accept_content' as the value
412 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
413 * 'nobody' => only return the header
414 * 'cookiejar' => path to cookie jar file
416 * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 public static function fetchRaw($request, $uid = 0, $opts = [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::JSON_AS]])
424 $owner = User::getOwnerDataById($uid);
429 $owner = User::getSystemAccount();
435 if (!empty($owner['uprvkey'])) {
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 $header['Date'] = $date;
442 $header['Host'] = $host;
444 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
446 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
448 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
452 $curl_opts[HttpClientOptions::HEADERS] = $header;
454 if (!empty($opts['nobody'])) {
455 $curlResult = DI::httpClient()->head($request, $curl_opts);
457 $curlResult = DI::httpClient()->get($request, $curl_opts);
459 $return_code = $curlResult->getReturnCode();
461 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
467 * 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'])) {
478 Logger::debug('No HTTP_SIGNATURE header');
482 if (!empty($content)) {
483 $object = json_decode($content, true);
484 if (empty($object)) {
485 Logger::info('No object');
489 $actor = JsonLD::fetchElement($object, 'actor', 'id');
495 $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
497 // First take every header
498 foreach ($http_headers as $k => $v) {
499 $field = str_replace('_', '-', strtolower($k));
500 $headers[$field] = $v;
503 // Now add every http header
504 foreach ($http_headers as $k => $v) {
505 if (strpos($k, 'HTTP_') === 0) {
506 $field = str_replace('_', '-', strtolower(substr($k, 5)));
507 $headers[$field] = $v;
511 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
513 // Add fields from the signature block to the header. See issue 8845
514 if (!empty($sig_block['created']) && empty($headers['(created)'])) {
515 $headers['(created)'] = $sig_block['created'];
518 if (!empty($sig_block['expires']) && empty($headers['(expires)'])) {
519 $headers['(expires)'] = $sig_block['expires'];
522 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
523 Logger::info('No headers or keyId');
528 foreach ($sig_block['headers'] as $h) {
529 if (array_key_exists($h, $headers)) {
530 $signed_data .= $h . ': ' . $headers[$h] . "\n";
532 Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]);
535 $signed_data = rtrim($signed_data, "\n");
537 if (empty($signed_data)) {
538 Logger::info('Signed data is empty');
544 // Wildcard value where signing algorithm should be derived from keyId
545 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
546 // Defaulting to SHA256 as it seems to be the prevalent implementation
547 // @see https://arewehs2019yet.vpzom.click
548 if ($sig_block['algorithm'] === 'hs2019') {
549 $algorithm = 'sha256';
552 if ($sig_block['algorithm'] === 'rsa-sha256') {
553 $algorithm = 'sha256';
556 if ($sig_block['algorithm'] === 'rsa-sha512') {
557 $algorithm = 'sha512';
560 if (empty($algorithm)) {
561 Logger::info('No alagorithm');
565 $key = self::fetchKey($sig_block['keyId'], $actor);
567 Logger::info('Empty key');
571 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
572 Logger::info('Actor is a tombstone', ['key' => $key]);
574 if (!Contact::isLocal($key['url'])) {
575 // We now delete everything that we possibly knew from this actor
576 Contact::deleteContactByUrl($key['url']);
581 if (empty($key['pubkey'])) {
582 Logger::info('Empty pubkey');
586 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
587 Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
591 $hasGoodSignedContent = false;
593 // Check the digest when it is part of the signed data
594 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
595 $digest = explode('=', $headers['digest'], 2);
596 if ($digest[0] === 'SHA-256') {
599 if ($digest[0] === 'SHA-512') {
603 /// @todo add all hashes from the rfc
605 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
606 Logger::info('Digest does not match');
610 $hasGoodSignedContent = true;
613 if (in_array('date', $sig_block['headers']) && !empty($headers['date'])) {
614 $created = strtotime($headers['date']);
615 } elseif (in_array('(created)', $sig_block['headers']) && !empty($sig_block['created'])) {
616 $created = $sig_block['created'];
621 if (in_array('(expires)', $sig_block['headers']) && !empty($sig_block['expires'])) {
622 $expired = min($sig_block['expires'], $created + 300);
624 $expired = $created + 300;
627 // Check if the signed date field is in an acceptable range
628 if (!empty($created)) {
631 // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers
632 if (($created - 60) > $current) {
633 Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
637 if ($current > $expired) {
638 Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
642 Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
643 $hasGoodSignedContent = true;
646 // Check the content-length when it is part of the signed data
647 if (in_array('content-length', $sig_block['headers'])) {
648 if (strlen($content) != $headers['content-length']) {
649 Logger::info('Content length does not match');
654 // Ensure that the authentication had been done with some content
655 // Without this check someone could authenticate with fakeable data
656 if (!$hasGoodSignedContent) {
657 Logger::info('No good signed content');
665 * fetches a key for a given id and actor
670 * @return array with actor url and public key
673 private static function fetchKey($id, $actor)
675 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
677 $profile = APContact::getByURL($url);
678 if (!empty($profile)) {
679 Logger::info('Taking key from id', ['id' => $id]);
680 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
681 } elseif ($url != $actor) {
682 $profile = APContact::getByURL($actor);
683 if (!empty($profile)) {
684 Logger::info('Taking key from actor', ['actor' => $actor]);
685 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
689 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);