3 * @copyright Copyright (C) 2010-2021, 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\Response\CurlResult;
32 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
33 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
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($_SERVER['REQUEST_METHOD']).' '.$_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, '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 DBA::update('inbox-status', $fields, ['url' => $url]);
377 * Fetches JSON data for a user
379 * @param string $request request url
380 * @param integer $uid User id of the requester
382 * @return array JSON array
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 public static function fetch($request, $uid)
387 $curlResult = self::fetchRaw($request, $uid);
389 if (empty($curlResult)) {
393 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
397 $content = json_decode($curlResult->getBody(), true);
398 if (empty($content) || !is_array($content)) {
406 * Fetches raw data for a user
408 * @param string $request request url
409 * @param integer $uid User id of the requester
410 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
411 * @param array $opts (optional parameters) assoziative array with:
412 * 'accept_content' => supply Accept: header with 'accept_content' as the value
413 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
414 * 'nobody' => only return the header
415 * 'cookiejar' => path to cookie jar file
417 * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 public static function fetchRaw($request, $uid = 0, $opts = ['accept_content' => ['application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"']])
425 $owner = User::getOwnerDataById($uid);
430 $owner = User::getSystemAccount();
436 if (!empty($owner['uprvkey'])) {
437 // Header data that is about to be signed.
438 $host = parse_url($request, PHP_URL_HOST);
439 $path = parse_url($request, PHP_URL_PATH);
440 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
442 $header['Date'] = $date;
443 $header['Host'] = $host;
445 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
447 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
449 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
453 $curl_opts[HttpClientOptions::HEADERS] = $header;
455 if (!empty($opts['nobody'])) {
456 $curlResult = DI::httpClient()->head($request, $curl_opts);
458 $curlResult = DI::httpClient()->get($request, $curl_opts);
460 $return_code = $curlResult->getReturnCode();
462 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
468 * Gets a signer from a given HTTP request
471 * @param $http_headers
473 * @return string Signer
474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
476 public static function getSigner($content, $http_headers)
478 if (empty($http_headers['HTTP_SIGNATURE'])) {
479 Logger::debug('No HTTP_SIGNATURE header');
483 if (!empty($content)) {
484 $object = json_decode($content, true);
485 if (empty($object)) {
486 Logger::info('No object');
490 $actor = JsonLD::fetchElement($object, 'actor', 'id');
496 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
498 // First take every header
499 foreach ($http_headers as $k => $v) {
500 $field = str_replace('_', '-', strtolower($k));
501 $headers[$field] = $v;
504 // Now add every http header
505 foreach ($http_headers as $k => $v) {
506 if (strpos($k, 'HTTP_') === 0) {
507 $field = str_replace('_', '-', strtolower(substr($k, 5)));
508 $headers[$field] = $v;
512 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
514 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
515 Logger::info('No headers or keyId');
520 foreach ($sig_block['headers'] as $h) {
521 if (array_key_exists($h, $headers)) {
522 $signed_data .= $h . ': ' . $headers[$h] . "\n";
525 $signed_data = rtrim($signed_data, "\n");
527 if (empty($signed_data)) {
528 Logger::info('Signed data is empty');
534 // Wildcard value where signing algorithm should be derived from keyId
535 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
536 // Defaulting to SHA256 as it seems to be the prevalent implementation
537 // @see https://arewehs2019yet.vpzom.click
538 if ($sig_block['algorithm'] === 'hs2019') {
539 $algorithm = 'sha256';
542 if ($sig_block['algorithm'] === 'rsa-sha256') {
543 $algorithm = 'sha256';
546 if ($sig_block['algorithm'] === 'rsa-sha512') {
547 $algorithm = 'sha512';
550 if (empty($algorithm)) {
551 Logger::info('No alagorithm');
555 $key = self::fetchKey($sig_block['keyId'], $actor);
557 Logger::info('Empty key');
561 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
562 Logger::info('Actor is a tombstone', ['key' => $key]);
564 if (!Contact::isLocal($key['url'])) {
565 // We now delete everything that we possibly knew from this actor
566 Contact::deleteContactByUrl($key['url']);
571 if (empty($key['pubkey'])) {
572 Logger::info('Empty pubkey');
576 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
577 Logger::info('Verification failed');
581 $hasGoodSignedContent = false;
583 // Check the digest when it is part of the signed data
584 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
585 $digest = explode('=', $headers['digest'], 2);
586 if ($digest[0] === 'SHA-256') {
589 if ($digest[0] === 'SHA-512') {
593 /// @todo add all hashes from the rfc
595 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
596 Logger::info('Digest does not match');
600 $hasGoodSignedContent = true;
603 // Check if the signed date field is in an acceptable range
604 if (in_array('date', $sig_block['headers'])) {
605 $diff = abs(strtotime($headers['date']) - time());
607 Logger::notice("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
610 $hasGoodSignedContent = true;
613 // Check the content-length when it is part of the signed data
614 if (in_array('content-length', $sig_block['headers'])) {
615 if (strlen($content) != $headers['content-length']) {
616 Logger::info('Content length does not match');
621 // Ensure that the authentication had been done with some content
622 // Without this check someone could authenticate with fakeable data
623 if (!$hasGoodSignedContent) {
624 Logger::info('No good signed content');
632 * fetches a key for a given id and actor
637 * @return array with actor url and public key
640 private static function fetchKey($id, $actor)
642 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
644 $profile = APContact::getByURL($url);
645 if (!empty($profile)) {
646 Logger::info('Taking key from id', ['id' => $id]);
647 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
648 } elseif ($url != $actor) {
649 $profile = APContact::getByURL($actor);
650 if (!empty($profile)) {
651 Logger::info('Taking key from actor', ['actor' => $actor]);
652 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
656 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);