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\ItemURI;
31 use Friendica\Model\User;
32 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
33 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
39 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
41 * Other parts of the code for HTTP signing are taken from the Osada project.
42 * https://framagit.org/macgirvin/osada
44 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
49 // See draft-cavage-http-signatures-08
51 * Verifies a magic request
55 * @return array with verification data
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 public static function verifyMagic(string $key): array
64 'header_signed' => false,
65 'header_valid' => false
68 // Decide if $data arrived via controller submission or curl.
70 $headers['(request-target)'] = strtolower(DI::args()->getMethod()).' '.$_SERVER['REQUEST_URI'];
72 foreach ($_SERVER as $k => $v) {
73 if (strpos($k, 'HTTP_') === 0) {
74 $field = str_replace('_', '-', strtolower(substr($k, 5)));
75 $headers[$field] = $v;
81 $sig_block = self::parseSigheader($headers['authorization']);
84 Logger::notice('no signature provided.');
88 $result['header_signed'] = true;
90 $signed_headers = $sig_block['headers'];
91 if (!$signed_headers) {
92 $signed_headers = ['date'];
96 foreach ($signed_headers as $h) {
97 if (array_key_exists($h, $headers)) {
98 $signed_data .= $h . ': ' . $headers[$h] . "\n";
100 if (strpos($h, '.')) {
105 $signed_data = rtrim($signed_data, "\n");
107 $algorithm = 'sha512';
109 if ($key && function_exists($key)) {
110 $result['signer'] = $sig_block['keyId'];
111 $key = $key($sig_block['keyId']);
114 Logger::info('Got keyID ' . $sig_block['keyId']);
120 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
122 Logger::info('verified: ' . $x);
129 $result['header_valid'] = true;
137 * @param string $prvkey
138 * @param string $keyid (optional, default 'Key')
142 public static function createSig(array $head, string $prvkey, string $keyid = 'Key'): array
144 $return_headers = [];
146 $return_headers = $head;
150 $algorithm = 'rsa-sha512';
152 $x = self::sign($head, $prvkey, $alg);
154 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
155 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
157 $return_headers['Authorization'] = ['Signature ' . $headerval];
159 return $return_headers;
164 * @param string $prvkey
165 * @param string $alg (optional) default 'sha256'
169 private static function sign(array $head, string $prvkey, string $alg = 'sha256'): array
175 foreach ($head as $k => $v) {
177 $v = implode(', ', $v);
179 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
183 $fields .= strtolower($k);
185 // strip the trailing linefeed
186 $headers = rtrim($headers, "\n");
188 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
190 $ret['headers'] = $fields;
191 $ret['signature'] = $sig;
197 * @param string $header
198 * @return array associative array with
199 * - \e string \b keyID
200 * - \e string \b created
201 * - \e string \b expires
202 * - \e string \b algorithm
203 * - \e array \b headers
204 * - \e string \b signature
205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
207 public static function parseSigheader(string $header): array
209 // Remove obsolete folds
210 $header = preg_replace('/\n\s+/', ' ', $header);
212 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
214 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
216 $regex = "/($token+)=($quotedString|$token+)/ism";
219 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
222 foreach ($matches as $match) {
223 $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
226 // if the header is encrypted, decrypt with (default) site private key and continue
227 if (!empty($headers['iv'])) {
228 $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
229 return self::parseSigheader($header);
233 'keyId' => $headers['keyId'] ?? '',
234 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
235 'created' => $headers['created'] ?? null,
236 'expires' => $headers['expires'] ?? null,
237 'headers' => explode(' ', $headers['headers'] ?? ''),
238 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
241 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
242 $return['headers'] = ['date'];
249 * @param array $headers Signature headers
250 * @param string $prvkey The site private key
251 * @return string Decrypted signature string
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 private static function decryptSigheader(array $headers, string $prvkey): string
256 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
257 return Crypto::unencapsulate($headers, $prvkey);
264 * Functions for ActivityPub
268 * Post given data to a target for a user, returns the result class
270 * @param array $data Data that is about to be sent
271 * @param string $target The URL of the inbox
272 * @param array $owner Sender owner-view record
274 * @return ICanHandleHttpResponses
276 public static function post(array $data, string $target, array $owner): ICanHandleHttpResponses
278 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
280 // Header data that is about to be signed.
281 $host = parse_url($target, PHP_URL_HOST);
282 $path = parse_url($target, PHP_URL_PATH);
283 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
284 $content_length = strlen($content);
285 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
289 'Content-Length' => $content_length,
294 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
296 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
298 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
300 $headers['Content-Type'] = 'application/activity+json';
302 $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'));
303 $return_code = $postResult->getReturnCode();
305 Logger::info('Transmit to ' . $target . ' returned ' . $return_code);
307 self::setInboxStatus($target, ($return_code >= 200) && ($return_code <= 299));
313 * Transmit given data to a target for a user
315 * @param array $data Data that is about to be sent
316 * @param string $target The URL of the inbox
317 * @param array $owner Sender owner-vew record
319 * @return boolean Was the transmission successful?
321 public static function transmit(array $data, string $target, array $owner): bool
323 $postResult = self::post($data, $target, $owner);
324 $return_code = $postResult->getReturnCode();
326 return ($return_code >= 200) && ($return_code <= 299);
330 * Set the delivery status for a given inbox
332 * @param string $url The URL of the inbox
333 * @param boolean $success Transmission status
334 * @param boolean $shared The inbox is a shared inbox
336 static public function setInboxStatus(string $url, bool $success, bool $shared = false)
338 $now = DateTimeFormat::utcNow();
340 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
341 if (!DBA::isResult($status)) {
342 DBA::insert('inbox-status', ['url' => $url, 'uri-id' => ItemURI::getIdByURI($url), 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
343 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
347 $fields = ['success' => $now];
349 $fields = ['failure' => $now];
352 if ($status['failure'] > DBA::NULL_DATETIME) {
353 $new_previous_stamp = strtotime($status['failure']);
354 $old_previous_stamp = strtotime($status['previous']);
356 // Only set "previous" with at least one day difference.
357 // We use this to assure to not accidentally archive too soon.
358 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
359 $fields['previous'] = $status['failure'];
364 if ($status['success'] <= DBA::NULL_DATETIME) {
365 $stamp1 = strtotime($status['created']);
367 $stamp1 = strtotime($status['success']);
370 $stamp2 = strtotime($now);
371 $previous_stamp = strtotime($status['previous']);
373 // Archive the inbox when there had been failures for five days.
374 // Additionally ensure that at least one previous attempt has to be in between.
375 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
376 $fields['archive'] = true;
379 $fields['archive'] = false;
382 if (empty($status['uri-id'])) {
383 $fields['uri-id'] = ItemURI::getIdByURI($url);
386 DBA::update('inbox-status', $fields, ['url' => $url]);
390 * Fetches JSON data for a user
392 * @param string $request request url
393 * @param integer $uid User id of the requester
395 * @return array JSON array
396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
398 public static function fetch(string $request, int $uid): array
400 $curlResult = self::fetchRaw($request, $uid);
402 if (empty($curlResult)) {
406 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
410 $content = json_decode($curlResult->getBody(), true);
411 if (empty($content) || !is_array($content)) {
419 * Fetches raw data for a user
421 * @param string $request request url
422 * @param integer $uid User id of the requester
423 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
424 * @param array $opts (optional parameters) assoziative array with:
425 * 'accept_content' => supply Accept: header with 'accept_content' as the value
426 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
427 * 'nobody' => only return the header
428 * 'cookiejar' => path to cookie jar file
430 * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433 public static function fetchRaw(string $request, int $uid = 0, array $opts = [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::JSON_AS]])
438 $owner = User::getOwnerDataById($uid);
443 $owner = User::getSystemAccount();
449 if (!empty($owner['uprvkey'])) {
450 // Header data that is about to be signed.
451 $host = parse_url($request, PHP_URL_HOST);
452 $path = parse_url($request, PHP_URL_PATH);
453 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
455 $header['Date'] = $date;
456 $header['Host'] = $host;
458 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
460 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
462 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
466 $curl_opts[HttpClientOptions::HEADERS] = $header;
468 if (!empty($opts['nobody'])) {
469 $curlResult = DI::httpClient()->head($request, $curl_opts);
471 $curlResult = DI::httpClient()->get($request, HttpClientAccept::JSON_AS, $curl_opts);
473 $return_code = $curlResult->getReturnCode();
475 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
481 * Fetch the apcontact entry of the keyId in the given header
483 * @param array $http_headers
485 * @return array APContact entry
487 public static function getKeyIdContact(array $http_headers): array
489 if (empty($http_headers['HTTP_SIGNATURE'])) {
490 Logger::debug('No HTTP_SIGNATURE header', ['header' => $http_headers]);
494 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
496 if (empty($sig_block['keyId'])) {
497 Logger::debug('No keyId', ['sig_block' => $sig_block]);
501 $url = (strpos($sig_block['keyId'], '#') ? substr($sig_block['keyId'], 0, strpos($sig_block['keyId'], '#')) : $sig_block['keyId']);
502 return APContact::getByURL($url);
506 * Gets a signer from a given HTTP request
508 * @param string $content
509 * @param array $http_headers
511 * @return string|null|false Signer
512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
514 public static function getSigner(string $content, array $http_headers)
516 if (empty($http_headers['HTTP_SIGNATURE'])) {
517 Logger::debug('No HTTP_SIGNATURE header');
521 if (!empty($content)) {
522 $object = json_decode($content, true);
523 if (empty($object)) {
524 Logger::info('No object');
528 $actor = JsonLD::fetchElement($object, 'actor', 'id') ?? '';
534 $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
536 // First take every header
537 foreach ($http_headers as $k => $v) {
538 $field = str_replace('_', '-', strtolower($k));
539 $headers[$field] = $v;
542 // Now add every http header
543 foreach ($http_headers as $k => $v) {
544 if (strpos($k, 'HTTP_') === 0) {
545 $field = str_replace('_', '-', strtolower(substr($k, 5)));
546 $headers[$field] = $v;
550 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
552 // Add fields from the signature block to the header. See issue 8845
553 if (!empty($sig_block['created']) && empty($headers['(created)'])) {
554 $headers['(created)'] = $sig_block['created'];
557 if (!empty($sig_block['expires']) && empty($headers['(expires)'])) {
558 $headers['(expires)'] = $sig_block['expires'];
561 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
562 Logger::info('No headers or keyId');
567 foreach ($sig_block['headers'] as $h) {
568 if (array_key_exists($h, $headers)) {
569 $signed_data .= $h . ': ' . $headers[$h] . "\n";
571 Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]);
574 $signed_data = rtrim($signed_data, "\n");
576 if (empty($signed_data)) {
577 Logger::info('Signed data is empty');
583 // Wildcard value where signing algorithm should be derived from keyId
584 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
585 // Defaulting to SHA256 as it seems to be the prevalent implementation
586 // @see https://arewehs2019yet.vpzom.click
587 if ($sig_block['algorithm'] === 'hs2019') {
588 $algorithm = 'sha256';
591 if ($sig_block['algorithm'] === 'rsa-sha256') {
592 $algorithm = 'sha256';
595 if ($sig_block['algorithm'] === 'rsa-sha512') {
596 $algorithm = 'sha512';
599 if (empty($algorithm)) {
600 Logger::info('No alagorithm');
604 $key = self::fetchKey($sig_block['keyId'], $actor);
606 Logger::info('Empty key');
610 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
611 Logger::info('Actor is a tombstone', ['key' => $key]);
613 if (!Contact::isLocal($key['url'])) {
614 // We now delete everything that we possibly knew from this actor
615 Contact::deleteContactByUrl($key['url']);
620 if (empty($key['pubkey'])) {
621 Logger::info('Empty pubkey');
625 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
626 Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
630 $hasGoodSignedContent = false;
632 // Check the digest when it is part of the signed data
633 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
634 $digest = explode('=', $headers['digest'], 2);
635 if ($digest[0] === 'SHA-256') {
638 if ($digest[0] === 'SHA-512') {
642 /// @todo add all hashes from the rfc
644 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
645 Logger::info('Digest does not match');
649 $hasGoodSignedContent = true;
652 if (in_array('date', $sig_block['headers']) && !empty($headers['date'])) {
653 $created = strtotime($headers['date']);
654 } elseif (in_array('(created)', $sig_block['headers']) && !empty($sig_block['created'])) {
655 $created = $sig_block['created'];
660 if (in_array('(expires)', $sig_block['headers']) && !empty($sig_block['expires'])) {
661 $expired = min($sig_block['expires'], $created + 300);
663 $expired = $created + 300;
666 // Check if the signed date field is in an acceptable range
667 if (!empty($created)) {
670 // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers
671 if (($created - 60) > $current) {
672 Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
676 if ($current > $expired) {
677 Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
681 Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
682 $hasGoodSignedContent = true;
685 // Check the content-length when it is part of the signed data
686 if (in_array('content-length', $sig_block['headers'])) {
687 if (strlen($content) != $headers['content-length']) {
688 Logger::info('Content length does not match');
693 // Ensure that the authentication had been done with some content
694 // Without this check someone could authenticate with fakeable data
695 if (!$hasGoodSignedContent) {
696 Logger::info('No good signed content');
704 * fetches a key for a given id and actor
707 * @param string $actor
709 * @return array with actor url and public key
712 private static function fetchKey(string $id, string $actor): array
714 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
716 $profile = APContact::getByURL($url);
717 if (!empty($profile)) {
718 Logger::info('Taking key from id', ['id' => $id]);
719 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
720 } elseif ($url != $actor) {
721 $profile = APContact::getByURL($actor);
722 if (!empty($profile)) {
723 Logger::info('Taking key from actor', ['actor' => $actor]);
724 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
728 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);