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\CurlResult;
32 use Friendica\Network\IHTTPResult;
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($_SERVER['REQUEST_METHOD']).' '.$_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::log('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::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
118 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
120 Logger::log('verified: ' . $x, Logger::DEBUG);
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 = [];
145 $algorithm = 'rsa-sha512';
147 $x = self::sign($head, $prvkey, $alg);
149 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
150 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
152 $sighead = 'Authorization: Signature ' . $headerval;
155 foreach ($head as $k => $v) {
156 $return_headers[] = $k . ': ' . $v;
160 $return_headers[] = $sighead;
162 return $return_headers;
167 * @param string $prvkey
168 * @param string $alg (optional) default 'sha256'
172 private static function sign($head, $prvkey, $alg = 'sha256')
178 foreach ($head as $k => $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($header)
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)
256 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
257 return Crypto::unencapsulate($headers, $prvkey);
264 * Functions for ActivityPub
268 * Transmit given data to a target for a user
270 * @param array $data Data that is about to be send
271 * @param string $target The URL of the inbox
272 * @param integer $uid User id of the sender
274 * @return boolean Was the transmission successful?
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 public static function transmit($data, $target, $uid)
279 $owner = User::getOwnerDataById($uid);
285 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
287 // Header data that is about to be signed.
288 $host = parse_url($target, PHP_URL_HOST);
289 $path = parse_url($target, PHP_URL_PATH);
290 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
291 $content_length = strlen($content);
292 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
296 'Content-Length' => $content_length,
301 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
303 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
305 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
307 $headers['Content-Type'] = 'application/activity+json';
309 $postResult = DI::httpRequest()->post($target, $content, $headers);
310 $return_code = $postResult->getReturnCode();
312 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
314 $success = ($return_code >= 200) && ($return_code <= 299);
316 self::setInboxStatus($target, $success);
322 * Set the delivery status for a given inbox
324 * @param string $url The URL of the inbox
325 * @param boolean $success Transmission status
326 * @param boolean $shared The inbox is a shared inbox
328 static public function setInboxStatus($url, $success, $shared = false)
330 $now = DateTimeFormat::utcNow();
332 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
333 if (!DBA::isResult($status)) {
334 DBA::insert('inbox-status', ['url' => $url, 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
335 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
339 $fields = ['success' => $now];
341 $fields = ['failure' => $now];
344 if ($status['failure'] > DBA::NULL_DATETIME) {
345 $new_previous_stamp = strtotime($status['failure']);
346 $old_previous_stamp = strtotime($status['previous']);
348 // Only set "previous" with at least one day difference.
349 // We use this to assure to not accidentally archive too soon.
350 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
351 $fields['previous'] = $status['failure'];
356 if ($status['success'] <= DBA::NULL_DATETIME) {
357 $stamp1 = strtotime($status['created']);
359 $stamp1 = strtotime($status['success']);
362 $stamp2 = strtotime($now);
363 $previous_stamp = strtotime($status['previous']);
365 // Archive the inbox when there had been failures for five days.
366 // Additionally ensure that at least one previous attempt has to be in between.
367 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
368 $fields['archive'] = true;
371 $fields['archive'] = false;
374 DBA::update('inbox-status', $fields, ['url' => $url]);
378 * Fetches JSON data for a user
380 * @param string $request request url
381 * @param integer $uid User id of the requester
383 * @return array JSON array
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
386 public static function fetch($request, $uid)
388 $curlResult = self::fetchRaw($request, $uid);
390 if (empty($curlResult)) {
394 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
398 $content = json_decode($curlResult->getBody(), true);
399 if (empty($content) || !is_array($content)) {
407 * Fetches raw data for a user
409 * @param string $request request url
410 * @param integer $uid User id of the requester
411 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
412 * @param array $opts (optional parameters) assoziative array with:
413 * 'accept_content' => supply Accept: header with 'accept_content' as the value
414 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
415 * 'nobody' => only return the header
416 * 'cookiejar' => path to cookie jar file
418 * @return IHTTPResult CurlResult
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 public static function fetchRaw($request, $uid = 0, $opts = ['accept_content' => ['application/activity+json', 'application/ld+json']])
426 $owner = User::getOwnerDataById($uid);
431 $owner = User::getSystemAccount();
437 if (!empty($owner['uprvkey'])) {
438 // Header data that is about to be signed.
439 $host = parse_url($request, PHP_URL_HOST);
440 $path = parse_url($request, PHP_URL_PATH);
441 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
443 $header['Date'] = $date;
444 $header['Host'] = $host;
446 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
448 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
450 $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
454 $curl_opts['header'] = $header;
456 if (!empty($opts['nobody'])) {
457 $curlResult = DI::httpRequest()->head($request, $curl_opts);
459 $curlResult = DI::httpRequest()->get($request, $curl_opts);
461 $return_code = $curlResult->getReturnCode();
463 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
469 * Gets a signer from a given HTTP request
472 * @param $http_headers
474 * @return string Signer
475 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
477 public static function getSigner($content, $http_headers)
479 if (empty($http_headers['HTTP_SIGNATURE'])) {
480 Logger::info('No HTTP_SIGNATURE header');
484 if (!empty($content)) {
485 $object = json_decode($content, true);
486 if (empty($object)) {
487 Logger::info('No object');
491 $actor = JsonLD::fetchElement($object, 'actor', 'id');
497 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
499 // First take every header
500 foreach ($http_headers as $k => $v) {
501 $field = str_replace('_', '-', strtolower($k));
502 $headers[$field] = $v;
505 // Now add every http header
506 foreach ($http_headers as $k => $v) {
507 if (strpos($k, 'HTTP_') === 0) {
508 $field = str_replace('_', '-', strtolower(substr($k, 5)));
509 $headers[$field] = $v;
513 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
515 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
516 Logger::info('No headers or keyId');
521 foreach ($sig_block['headers'] as $h) {
522 if (array_key_exists($h, $headers)) {
523 $signed_data .= $h . ': ' . $headers[$h] . "\n";
526 $signed_data = rtrim($signed_data, "\n");
528 if (empty($signed_data)) {
529 Logger::info('Signed data is empty');
535 // Wildcard value where signing algorithm should be derived from keyId
536 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
537 // Defaulting to SHA256 as it seems to be the prevalent implementation
538 // @see https://arewehs2019yet.vpzom.click
539 if ($sig_block['algorithm'] === 'hs2019') {
540 $algorithm = 'sha256';
543 if ($sig_block['algorithm'] === 'rsa-sha256') {
544 $algorithm = 'sha256';
547 if ($sig_block['algorithm'] === 'rsa-sha512') {
548 $algorithm = 'sha512';
551 if (empty($algorithm)) {
552 Logger::info('No alagorithm');
556 $key = self::fetchKey($sig_block['keyId'], $actor);
558 Logger::info('Empty key');
562 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
563 Logger::info('Actor is a tombstone', ['key' => $key]);
565 if (!Contact::isLocal($key['url'])) {
566 // We now delete everything that we possibly knew from this actor
567 Contact::deleteContactByUrl($key['url']);
572 if (empty($key['pubkey'])) {
573 Logger::info('Empty pubkey');
577 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
578 Logger::info('Verification failed');
582 $hasGoodSignedContent = false;
584 // Check the digest when it is part of the signed data
585 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
586 $digest = explode('=', $headers['digest'], 2);
587 if ($digest[0] === 'SHA-256') {
590 if ($digest[0] === 'SHA-512') {
594 /// @todo add all hashes from the rfc
596 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
597 Logger::info('Digest does not match');
601 $hasGoodSignedContent = true;
604 // Check if the signed date field is in an acceptable range
605 if (in_array('date', $sig_block['headers'])) {
606 $diff = abs(strtotime($headers['date']) - time());
608 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
611 $hasGoodSignedContent = true;
614 // Check the content-length when it is part of the signed data
615 if (in_array('content-length', $sig_block['headers'])) {
616 if (strlen($content) != $headers['content-length']) {
617 Logger::info('Content length does not match');
622 // Ensure that the authentication had been done with some content
623 // Without this check someone could authenticate with fakeable data
624 if (!$hasGoodSignedContent) {
625 Logger::info('No good signed content');
633 * fetches a key for a given id and actor
638 * @return array with actor url and public key
641 private static function fetchKey($id, $actor)
643 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
645 $profile = APContact::getByURL($url);
646 if (!empty($profile)) {
647 Logger::info('Taking key from id', ['id' => $id]);
648 return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
649 } elseif ($url != $actor) {
650 $profile = APContact::getByURL($actor);
651 if (!empty($profile)) {
652 Logger::info('Taking key from actor', ['actor' => $actor]);
653 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
657 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);