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\Client\HttpClientAccept;
33 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
38 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
40 * Other parts of the code for HTTP signing are taken from the Osada project.
41 * https://framagit.org/macgirvin/osada
43 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
48 // See draft-cavage-http-signatures-08
50 * Verifies a magic request
54 * @return array with verification data
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 public static function verifyMagic($key)
63 'header_signed' => false,
64 'header_valid' => false
67 // Decide if $data arrived via controller submission or curl.
69 $headers['(request-target)'] = strtolower(DI::args()->getMethod()).' '.$_SERVER['REQUEST_URI'];
71 foreach ($_SERVER as $k => $v) {
72 if (strpos($k, 'HTTP_') === 0) {
73 $field = str_replace('_', '-', strtolower(substr($k, 5)));
74 $headers[$field] = $v;
80 $sig_block = self::parseSigheader($headers['authorization']);
83 Logger::notice('no signature provided.');
87 $result['header_signed'] = true;
89 $signed_headers = $sig_block['headers'];
90 if (!$signed_headers) {
91 $signed_headers = ['date'];
95 foreach ($signed_headers as $h) {
96 if (array_key_exists($h, $headers)) {
97 $signed_data .= $h . ': ' . $headers[$h] . "\n";
99 if (strpos($h, '.')) {
104 $signed_data = rtrim($signed_data, "\n");
106 $algorithm = 'sha512';
108 if ($key && function_exists($key)) {
109 $result['signer'] = $sig_block['keyId'];
110 $key = $key($sig_block['keyId']);
113 Logger::info('Got keyID ' . $sig_block['keyId']);
119 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
121 Logger::info('verified: ' . $x);
128 $result['header_valid'] = true;
136 * @param string $prvkey
137 * @param string $keyid (optional, default 'Key')
141 public static function createSig($head, $prvkey, $keyid = 'Key')
143 $return_headers = [];
145 $return_headers = $head;
149 $algorithm = 'rsa-sha512';
151 $x = self::sign($head, $prvkey, $alg);
153 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
154 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
156 $return_headers['Authorization'] = ['Signature ' . $headerval];
158 return $return_headers;
163 * @param string $prvkey
164 * @param string $alg (optional) default 'sha256'
168 private static function sign($head, $prvkey, $alg = 'sha256')
174 foreach ($head as $k => $v) {
176 $v = implode(', ', $v);
178 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
182 $fields .= strtolower($k);
184 // strip the trailing linefeed
185 $headers = rtrim($headers, "\n");
187 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
189 $ret['headers'] = $fields;
190 $ret['signature'] = $sig;
196 * @param string $header
197 * @return array associative array with
198 * - \e string \b keyID
199 * - \e string \b created
200 * - \e string \b expires
201 * - \e string \b algorithm
202 * - \e array \b headers
203 * - \e string \b signature
204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206 public static function parseSigheader($header)
208 // Remove obsolete folds
209 $header = preg_replace('/\n\s+/', ' ', $header);
211 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
213 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
215 $regex = "/($token+)=($quotedString|$token+)/ism";
218 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
221 foreach ($matches as $match) {
222 $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
225 // if the header is encrypted, decrypt with (default) site private key and continue
226 if (!empty($headers['iv'])) {
227 $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
228 return self::parseSigheader($header);
232 'keyId' => $headers['keyId'] ?? '',
233 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
234 'created' => $headers['created'] ?? null,
235 'expires' => $headers['expires'] ?? null,
236 'headers' => explode(' ', $headers['headers'] ?? ''),
237 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
240 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
241 $return['headers'] = ['date'];
248 * @param array $headers Signature headers
249 * @param string $prvkey The site private key
250 * @return string Decrypted signature string
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 private static function decryptSigheader(array $headers, string $prvkey)
255 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
256 return Crypto::unencapsulate($headers, $prvkey);
263 * Functions for ActivityPub
267 * Transmit given data to a target for a user
269 * @param array $data Data that is about to be send
270 * @param string $target The URL of the inbox
271 * @param integer $uid User id of the sender
273 * @return boolean Was the transmission successful?
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 public static function transmit($data, $target, $uid)
278 $owner = User::getOwnerDataById($uid);
284 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
286 // Header data that is about to be signed.
287 $host = parse_url($target, PHP_URL_HOST);
288 $path = parse_url($target, PHP_URL_PATH);
289 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
290 $content_length = strlen($content);
291 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
295 'Content-Length' => $content_length,
300 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
302 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
304 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
306 $headers['Content-Type'] = 'application/activity+json';
308 $postResult = DI::httpClient()->post($target, $content, $headers);
309 $return_code = $postResult->getReturnCode();
311 Logger::info('Transmit to ' . $target . ' returned ' . $return_code);
313 $success = ($return_code >= 200) && ($return_code <= 299);
315 self::setInboxStatus($target, $success);
321 * Set the delivery status for a given inbox
323 * @param string $url The URL of the inbox
324 * @param boolean $success Transmission status
325 * @param boolean $shared The inbox is a shared inbox
327 static public function setInboxStatus($url, $success, $shared = false)
329 $now = DateTimeFormat::utcNow();
331 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
332 if (!DBA::isResult($status)) {
333 DBA::insert('inbox-status', ['url' => $url, 'uri-id' => ItemURI::getIdByURI($url), 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
334 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
338 $fields = ['success' => $now];
340 $fields = ['failure' => $now];
343 if ($status['failure'] > DBA::NULL_DATETIME) {
344 $new_previous_stamp = strtotime($status['failure']);
345 $old_previous_stamp = strtotime($status['previous']);
347 // Only set "previous" with at least one day difference.
348 // We use this to assure to not accidentally archive too soon.
349 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
350 $fields['previous'] = $status['failure'];
355 if ($status['success'] <= DBA::NULL_DATETIME) {
356 $stamp1 = strtotime($status['created']);
358 $stamp1 = strtotime($status['success']);
361 $stamp2 = strtotime($now);
362 $previous_stamp = strtotime($status['previous']);
364 // Archive the inbox when there had been failures for five days.
365 // Additionally ensure that at least one previous attempt has to be in between.
366 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
367 $fields['archive'] = true;
370 $fields['archive'] = false;
373 if (empty($status['uri-id'])) {
374 $fields['uri-id'] = ItemURI::getIdByURI($url);
377 DBA::update('inbox-status', $fields, ['url' => $url]);
381 * 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 $curlResult = self::fetchRaw($request, $uid);
393 if (empty($curlResult)) {
397 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
401 $content = json_decode($curlResult->getBody(), true);
402 if (empty($content) || !is_array($content)) {
410 * Fetches raw data for a user
412 * @param string $request request url
413 * @param integer $uid User id of the requester
414 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
415 * @param array $opts (optional parameters) assoziative array with:
416 * 'accept_content' => supply Accept: header with 'accept_content' as the value
417 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
418 * 'nobody' => only return the header
419 * 'cookiejar' => path to cookie jar file
421 * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
422 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424 public static function fetchRaw($request, $uid = 0, $opts = [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::JSON_AS]])
429 $owner = User::getOwnerDataById($uid);
434 $owner = User::getSystemAccount();
440 if (!empty($owner['uprvkey'])) {
441 // Header data that is about to be signed.
442 $host = parse_url($request, PHP_URL_HOST);
443 $path = parse_url($request, PHP_URL_PATH);
444 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
446 $header['Date'] = $date;
447 $header['Host'] = $host;
449 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
451 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
453 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
457 $curl_opts[HttpClientOptions::HEADERS] = $header;
459 if (!empty($opts['nobody'])) {
460 $curlResult = DI::httpClient()->head($request, $curl_opts);
462 $curlResult = DI::httpClient()->get($request, HttpClientAccept::JSON_AS, $curl_opts);
464 $return_code = $curlResult->getReturnCode();
466 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
472 * Gets a signer from a given HTTP request
475 * @param $http_headers
477 * @return string Signer
478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
480 public static function getSigner($content, $http_headers)
482 if (empty($http_headers['HTTP_SIGNATURE'])) {
483 Logger::debug('No HTTP_SIGNATURE header');
487 if (!empty($content)) {
488 $object = json_decode($content, true);
489 if (empty($object)) {
490 Logger::info('No object');
494 $actor = JsonLD::fetchElement($object, 'actor', 'id');
500 $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
502 // First take every header
503 foreach ($http_headers as $k => $v) {
504 $field = str_replace('_', '-', strtolower($k));
505 $headers[$field] = $v;
508 // Now add every http header
509 foreach ($http_headers as $k => $v) {
510 if (strpos($k, 'HTTP_') === 0) {
511 $field = str_replace('_', '-', strtolower(substr($k, 5)));
512 $headers[$field] = $v;
516 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
518 // Add fields from the signature block to the header. See issue 8845
519 if (!empty($sig_block['created']) && empty($headers['(created)'])) {
520 $headers['(created)'] = $sig_block['created'];
523 if (!empty($sig_block['expires']) && empty($headers['(expires)'])) {
524 $headers['(expires)'] = $sig_block['expires'];
527 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
528 Logger::info('No headers or keyId');
533 foreach ($sig_block['headers'] as $h) {
534 if (array_key_exists($h, $headers)) {
535 $signed_data .= $h . ': ' . $headers[$h] . "\n";
537 Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]);
540 $signed_data = rtrim($signed_data, "\n");
542 if (empty($signed_data)) {
543 Logger::info('Signed data is empty');
549 // Wildcard value where signing algorithm should be derived from keyId
550 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
551 // Defaulting to SHA256 as it seems to be the prevalent implementation
552 // @see https://arewehs2019yet.vpzom.click
553 if ($sig_block['algorithm'] === 'hs2019') {
554 $algorithm = 'sha256';
557 if ($sig_block['algorithm'] === 'rsa-sha256') {
558 $algorithm = 'sha256';
561 if ($sig_block['algorithm'] === 'rsa-sha512') {
562 $algorithm = 'sha512';
565 if (empty($algorithm)) {
566 Logger::info('No alagorithm');
570 $key = self::fetchKey($sig_block['keyId'], $actor);
572 Logger::info('Empty key');
576 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
577 Logger::info('Actor is a tombstone', ['key' => $key]);
579 if (!Contact::isLocal($key['url'])) {
580 // We now delete everything that we possibly knew from this actor
581 Contact::deleteContactByUrl($key['url']);
586 if (empty($key['pubkey'])) {
587 Logger::info('Empty pubkey');
591 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
592 Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
596 $hasGoodSignedContent = false;
598 // Check the digest when it is part of the signed data
599 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
600 $digest = explode('=', $headers['digest'], 2);
601 if ($digest[0] === 'SHA-256') {
604 if ($digest[0] === 'SHA-512') {
608 /// @todo add all hashes from the rfc
610 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
611 Logger::info('Digest does not match');
615 $hasGoodSignedContent = true;
618 if (in_array('date', $sig_block['headers']) && !empty($headers['date'])) {
619 $created = strtotime($headers['date']);
620 } elseif (in_array('(created)', $sig_block['headers']) && !empty($sig_block['created'])) {
621 $created = $sig_block['created'];
626 if (in_array('(expires)', $sig_block['headers']) && !empty($sig_block['expires'])) {
627 $expired = min($sig_block['expires'], $created + 300);
629 $expired = $created + 300;
632 // Check if the signed date field is in an acceptable range
633 if (!empty($created)) {
636 // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers
637 if (($created - 60) > $current) {
638 Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
642 if ($current > $expired) {
643 Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
647 Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
648 $hasGoodSignedContent = true;
651 // Check the content-length when it is part of the signed data
652 if (in_array('content-length', $sig_block['headers'])) {
653 if (strlen($content) != $headers['content-length']) {
654 Logger::info('Content length does not match');
659 // Ensure that the authentication had been done with some content
660 // Without this check someone could authenticate with fakeable data
661 if (!$hasGoodSignedContent) {
662 Logger::info('No good signed content');
670 * fetches a key for a given id and actor
675 * @return array with actor url and public key
678 private static function fetchKey($id, $actor)
680 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
682 $profile = APContact::getByURL($url);
683 if (!empty($profile)) {
684 Logger::info('Taking key from id', ['id' => $id]);
685 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
686 } elseif ($url != $actor) {
687 $profile = APContact::getByURL($actor);
688 if (!empty($profile)) {
689 Logger::info('Taking key from actor', ['actor' => $actor]);
690 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
694 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);