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\HttpClientOptions;
34 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
36 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
38 * Other parts of the code for HTTP signing are taken from the Osada project.
39 * https://framagit.org/macgirvin/osada
41 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
46 // See draft-cavage-http-signatures-08
48 * Verifies a magic request
52 * @return array with verification data
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55 public static function verifyMagic($key)
61 'header_signed' => false,
62 'header_valid' => false
65 // Decide if $data arrived via controller submission or curl.
67 $headers['(request-target)'] = strtolower(DI::args()->getMethod()).' '.$_SERVER['REQUEST_URI'];
69 foreach ($_SERVER as $k => $v) {
70 if (strpos($k, 'HTTP_') === 0) {
71 $field = str_replace('_', '-', strtolower(substr($k, 5)));
72 $headers[$field] = $v;
78 $sig_block = self::parseSigheader($headers['authorization']);
81 Logger::notice('no signature provided.');
85 $result['header_signed'] = true;
87 $signed_headers = $sig_block['headers'];
88 if (!$signed_headers) {
89 $signed_headers = ['date'];
93 foreach ($signed_headers as $h) {
94 if (array_key_exists($h, $headers)) {
95 $signed_data .= $h . ': ' . $headers[$h] . "\n";
97 if (strpos($h, '.')) {
102 $signed_data = rtrim($signed_data, "\n");
104 $algorithm = 'sha512';
106 if ($key && function_exists($key)) {
107 $result['signer'] = $sig_block['keyId'];
108 $key = $key($sig_block['keyId']);
111 Logger::info('Got keyID ' . $sig_block['keyId']);
117 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
119 Logger::info('verified: ' . $x);
126 $result['header_valid'] = true;
134 * @param string $prvkey
135 * @param string $keyid (optional, default 'Key')
139 public static function createSig($head, $prvkey, $keyid = 'Key')
141 $return_headers = [];
143 $return_headers = $head;
147 $algorithm = 'rsa-sha512';
149 $x = self::sign($head, $prvkey, $alg);
151 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
152 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
154 $return_headers['Authorization'] = ['Signature ' . $headerval];
156 return $return_headers;
161 * @param string $prvkey
162 * @param string $alg (optional) default 'sha256'
166 private static function sign($head, $prvkey, $alg = 'sha256')
172 foreach ($head as $k => $v) {
174 $v = implode(', ', $v);
176 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
180 $fields .= strtolower($k);
182 // strip the trailing linefeed
183 $headers = rtrim($headers, "\n");
185 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
187 $ret['headers'] = $fields;
188 $ret['signature'] = $sig;
194 * @param string $header
195 * @return array associative array with
196 * - \e string \b keyID
197 * - \e string \b created
198 * - \e string \b expires
199 * - \e string \b algorithm
200 * - \e array \b headers
201 * - \e string \b signature
202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
204 public static function parseSigheader($header)
206 // Remove obsolete folds
207 $header = preg_replace('/\n\s+/', ' ', $header);
209 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
211 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
213 $regex = "/($token+)=($quotedString|$token+)/ism";
216 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
219 foreach ($matches as $match) {
220 $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
223 // if the header is encrypted, decrypt with (default) site private key and continue
224 if (!empty($headers['iv'])) {
225 $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
226 return self::parseSigheader($header);
230 'keyId' => $headers['keyId'] ?? '',
231 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
232 'created' => $headers['created'] ?? null,
233 'expires' => $headers['expires'] ?? null,
234 'headers' => explode(' ', $headers['headers'] ?? ''),
235 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
238 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
239 $return['headers'] = ['date'];
246 * @param array $headers Signature headers
247 * @param string $prvkey The site private key
248 * @return string Decrypted signature string
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 private static function decryptSigheader(array $headers, string $prvkey)
253 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
254 return Crypto::unencapsulate($headers, $prvkey);
261 * Functions for ActivityPub
265 * Transmit given data to a target for a user
267 * @param array $data Data that is about to be send
268 * @param string $target The URL of the inbox
269 * @param integer $uid User id of the sender
271 * @return boolean Was the transmission successful?
272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 public static function transmit($data, $target, $uid)
276 $owner = User::getOwnerDataById($uid);
282 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
284 // Header data that is about to be signed.
285 $host = parse_url($target, PHP_URL_HOST);
286 $path = parse_url($target, PHP_URL_PATH);
287 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
288 $content_length = strlen($content);
289 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
293 'Content-Length' => $content_length,
298 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
300 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
302 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
304 $headers['Content-Type'] = 'application/activity+json';
306 $postResult = DI::httpClient()->post($target, $content, $headers);
307 $return_code = $postResult->getReturnCode();
309 Logger::info('Transmit to ' . $target . ' returned ' . $return_code);
311 $success = ($return_code >= 200) && ($return_code <= 299);
313 self::setInboxStatus($target, $success);
319 * Set the delivery status for a given inbox
321 * @param string $url The URL of the inbox
322 * @param boolean $success Transmission status
323 * @param boolean $shared The inbox is a shared inbox
325 static public function setInboxStatus($url, $success, $shared = false)
327 $now = DateTimeFormat::utcNow();
329 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
330 if (!DBA::isResult($status)) {
331 DBA::insert('inbox-status', ['url' => $url, 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
332 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
336 $fields = ['success' => $now];
338 $fields = ['failure' => $now];
341 if ($status['failure'] > DBA::NULL_DATETIME) {
342 $new_previous_stamp = strtotime($status['failure']);
343 $old_previous_stamp = strtotime($status['previous']);
345 // Only set "previous" with at least one day difference.
346 // We use this to assure to not accidentally archive too soon.
347 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
348 $fields['previous'] = $status['failure'];
353 if ($status['success'] <= DBA::NULL_DATETIME) {
354 $stamp1 = strtotime($status['created']);
356 $stamp1 = strtotime($status['success']);
359 $stamp2 = strtotime($now);
360 $previous_stamp = strtotime($status['previous']);
362 // Archive the inbox when there had been failures for five days.
363 // Additionally ensure that at least one previous attempt has to be in between.
364 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
365 $fields['archive'] = true;
368 $fields['archive'] = false;
371 DBA::update('inbox-status', $fields, ['url' => $url]);
375 * Fetches JSON data for a user
377 * @param string $request request url
378 * @param integer $uid User id of the requester
380 * @return array JSON array
381 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383 public static function fetch($request, $uid)
385 $curlResult = self::fetchRaw($request, $uid);
387 if (empty($curlResult)) {
391 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
395 $content = json_decode($curlResult->getBody(), true);
396 if (empty($content) || !is_array($content)) {
404 * Fetches raw data for a user
406 * @param string $request request url
407 * @param integer $uid User id of the requester
408 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
409 * @param array $opts (optional parameters) assoziative array with:
410 * 'accept_content' => supply Accept: header with 'accept_content' as the value
411 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
412 * 'nobody' => only return the header
413 * 'cookiejar' => path to cookie jar file
415 * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 public static function fetchRaw($request, $uid = 0, $opts = ['accept_content' => ['application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"']])
423 $owner = User::getOwnerDataById($uid);
428 $owner = User::getSystemAccount();
434 if (!empty($owner['uprvkey'])) {
435 // Header data that is about to be signed.
436 $host = parse_url($request, PHP_URL_HOST);
437 $path = parse_url($request, PHP_URL_PATH);
438 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
440 $header['Date'] = $date;
441 $header['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 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
451 $curl_opts[HttpClientOptions::HEADERS] = $header;
453 if (!empty($opts['nobody'])) {
454 $curlResult = DI::httpClient()->head($request, $curl_opts);
456 $curlResult = DI::httpClient()->get($request, $curl_opts);
458 $return_code = $curlResult->getReturnCode();
460 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
466 * Gets a signer from a given HTTP request
469 * @param $http_headers
471 * @return string Signer
472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
474 public static function getSigner($content, $http_headers)
476 if (empty($http_headers['HTTP_SIGNATURE'])) {
477 Logger::debug('No HTTP_SIGNATURE header');
481 if (!empty($content)) {
482 $object = json_decode($content, true);
483 if (empty($object)) {
484 Logger::info('No object');
488 $actor = JsonLD::fetchElement($object, 'actor', 'id');
494 $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
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 // Add fields from the signature block to the header. See issue 8845
513 if (!empty($sig_block['created']) && empty($headers['(created)'])) {
514 $headers['(created)'] = $sig_block['created'];
517 if (!empty($sig_block['expires']) && empty($headers['(expires)'])) {
518 $headers['(expires)'] = $sig_block['expires'];
521 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
522 Logger::info('No headers or keyId');
527 foreach ($sig_block['headers'] as $h) {
528 if (array_key_exists($h, $headers)) {
529 $signed_data .= $h . ': ' . $headers[$h] . "\n";
531 Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]);
534 $signed_data = rtrim($signed_data, "\n");
536 if (empty($signed_data)) {
537 Logger::info('Signed data is empty');
543 // Wildcard value where signing algorithm should be derived from keyId
544 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
545 // Defaulting to SHA256 as it seems to be the prevalent implementation
546 // @see https://arewehs2019yet.vpzom.click
547 if ($sig_block['algorithm'] === 'hs2019') {
548 $algorithm = 'sha256';
551 if ($sig_block['algorithm'] === 'rsa-sha256') {
552 $algorithm = 'sha256';
555 if ($sig_block['algorithm'] === 'rsa-sha512') {
556 $algorithm = 'sha512';
559 if (empty($algorithm)) {
560 Logger::info('No alagorithm');
564 $key = self::fetchKey($sig_block['keyId'], $actor);
566 Logger::info('Empty key');
570 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
571 Logger::info('Actor is a tombstone', ['key' => $key]);
573 if (!Contact::isLocal($key['url'])) {
574 // We now delete everything that we possibly knew from this actor
575 Contact::deleteContactByUrl($key['url']);
580 if (empty($key['pubkey'])) {
581 Logger::info('Empty pubkey');
585 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
586 Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
590 $hasGoodSignedContent = false;
592 // Check the digest when it is part of the signed data
593 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
594 $digest = explode('=', $headers['digest'], 2);
595 if ($digest[0] === 'SHA-256') {
598 if ($digest[0] === 'SHA-512') {
602 /// @todo add all hashes from the rfc
604 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
605 Logger::info('Digest does not match');
609 $hasGoodSignedContent = true;
612 if (in_array('date', $sig_block['headers']) && !empty($headers['date'])) {
613 $created = strtotime($headers['date']);
614 } elseif (in_array('(created)', $sig_block['headers']) && !empty($sig_block['created'])) {
615 $created = $sig_block['created'];
620 if (in_array('(expires)', $sig_block['headers']) && !empty($sig_block['expires'])) {
621 $expired = min($sig_block['expires'], $created + 300);
623 $expired = $created + 300;
626 // Check if the signed date field is in an acceptable range
627 if (!empty($created)) {
630 if ($created > $current) {
631 Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
635 if ($current > $expired) {
636 Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
640 Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
641 $hasGoodSignedContent = true;
644 // Check the content-length when it is part of the signed data
645 if (in_array('content-length', $sig_block['headers'])) {
646 if (strlen($content) != $headers['content-length']) {
647 Logger::info('Content length does not match');
652 // Ensure that the authentication had been done with some content
653 // Without this check someone could authenticate with fakeable data
654 if (!$hasGoodSignedContent) {
655 Logger::info('No good signed content');
663 * fetches a key for a given id and actor
668 * @return array with actor url and public key
671 private static function fetchKey($id, $actor)
673 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
675 $profile = APContact::getByURL($url);
676 if (!empty($profile)) {
677 Logger::info('Taking key from id', ['id' => $id]);
678 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
679 } elseif ($url != $actor) {
680 $profile = APContact::getByURL($actor);
681 if (!empty($profile)) {
682 Logger::info('Taking key from actor', ['actor' => $actor]);
683 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
687 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);