3 * @copyright Copyright (C) 2020, Friendica
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\DBA;
27 use Friendica\Model\APContact;
28 use Friendica\Model\User;
31 * Implements HTTP Signatures per draft-cavage-http-signatures-07.
33 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
35 * Other parts of the code for HTTP signing are taken from the Osada project.
36 * https://framagit.org/macgirvin/osada
38 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
43 // See draft-cavage-http-signatures-08
45 * Verifies a magic request
49 * @return array with verification data
50 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52 public static function verifyMagic($key)
58 'header_signed' => false,
59 'header_valid' => false
62 // Decide if $data arrived via controller submission or curl.
64 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
66 foreach ($_SERVER as $k => $v) {
67 if (strpos($k, 'HTTP_') === 0) {
68 $field = str_replace('_', '-', strtolower(substr($k, 5)));
69 $headers[$field] = $v;
75 $sig_block = self::parseSigheader($headers['authorization']);
78 Logger::log('no signature provided.');
82 $result['header_signed'] = true;
84 $signed_headers = $sig_block['headers'];
85 if (!$signed_headers) {
86 $signed_headers = ['date'];
90 foreach ($signed_headers as $h) {
91 if (array_key_exists($h, $headers)) {
92 $signed_data .= $h . ': ' . $headers[$h] . "\n";
94 if (strpos($h, '.')) {
99 $signed_data = rtrim($signed_data, "\n");
101 $algorithm = 'sha512';
103 if ($key && function_exists($key)) {
104 $result['signer'] = $sig_block['keyId'];
105 $key = $key($sig_block['keyId']);
108 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
114 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
116 Logger::log('verified: ' . $x, Logger::DEBUG);
123 $result['header_valid'] = true;
131 * @param string $prvkey
132 * @param string $keyid (optional, default 'Key')
136 public static function createSig($head, $prvkey, $keyid = 'Key')
138 $return_headers = [];
141 $algorithm = 'rsa-sha512';
143 $x = self::sign($head, $prvkey, $alg);
145 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
146 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
148 $sighead = 'Authorization: Signature ' . $headerval;
151 foreach ($head as $k => $v) {
152 $return_headers[] = $k . ': ' . $v;
156 $return_headers[] = $sighead;
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) {
175 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
179 $fields .= strtolower($k);
181 // strip the trailing linefeed
182 $headers = rtrim($headers, "\n");
184 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
186 $ret['headers'] = $fields;
187 $ret['signature'] = $sig;
193 * @param string $header
194 * @return array associative array with
195 * - \e string \b keyID
196 * - \e string \b created
197 * - \e string \b expires
198 * - \e string \b algorithm
199 * - \e array \b headers
200 * - \e string \b signature
201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203 public static function parseSigheader($header)
205 // Remove obsolete folds
206 $header = preg_replace('/\n\s+/', ' ', $header);
208 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
210 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
212 $regex = "/($token+)=($quotedString|$token+)/ism";
215 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
218 foreach ($matches as $match) {
219 $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
222 // if the header is encrypted, decrypt with (default) site private key and continue
223 if (!empty($headers['iv'])) {
224 $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
225 return self::parseSigheader($header);
229 'keyId' => $headers['keyId'] ?? '',
230 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
231 'created' => $headers['created'] ?? null,
232 'expires' => $headers['expires'] ?? null,
233 'headers' => explode(' ', $headers['headers'] ?? ''),
234 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
237 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
238 $return['headers'] = ['date'];
245 * @param array $headers Signature headers
246 * @param string $prvkey The site private key
247 * @return string Decrypted signature string
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 private static function decryptSigheader(array $headers, string $prvkey)
252 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
253 return Crypto::unencapsulate($headers, $prvkey);
260 * Functions for ActivityPub
264 * Transmit given data to a target for a user
266 * @param array $data Data that is about to be send
267 * @param string $target The URL of the inbox
268 * @param integer $uid User id of the sender
270 * @return boolean Was the transmission successful?
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273 public static function transmit($data, $target, $uid)
275 $owner = User::getOwnerDataById($uid);
281 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
283 // Header data that is about to be signed.
284 $host = parse_url($target, PHP_URL_HOST);
285 $path = parse_url($target, PHP_URL_PATH);
286 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
287 $content_length = strlen($content);
288 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
290 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
292 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
294 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
296 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
298 $headers[] = 'Content-Type: application/activity+json';
300 $postResult = DI::httpRequest()->post($target, $content, $headers);
301 $return_code = $postResult->getReturnCode();
303 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
305 $success = ($return_code >= 200) && ($return_code <= 299);
307 self::setInboxStatus($target, $success);
313 * Set the delivery status for a given inbox
315 * @param string $url The URL of the inbox
316 * @param boolean $success Transmission status
317 * @param boolean $shared The inbox is a shared inbox
319 static public function setInboxStatus($url, $success, $shared = false)
321 $now = DateTimeFormat::utcNow();
323 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
324 if (!DBA::isResult($status)) {
325 DBA::insert('inbox-status', ['url' => $url, 'created' => $now, 'shared' => $shared]);
326 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
330 $fields = ['success' => $now];
332 $fields = ['failure' => $now];
335 if ($status['failure'] > DBA::NULL_DATETIME) {
336 $new_previous_stamp = strtotime($status['failure']);
337 $old_previous_stamp = strtotime($status['previous']);
339 // Only set "previous" with at least one day difference.
340 // We use this to assure to not accidentally archive too soon.
341 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
342 $fields['previous'] = $status['failure'];
347 if ($status['success'] <= DBA::NULL_DATETIME) {
348 $stamp1 = strtotime($status['created']);
350 $stamp1 = strtotime($status['success']);
353 $stamp2 = strtotime($now);
354 $previous_stamp = strtotime($status['previous']);
356 // Archive the inbox when there had been failures for five days.
357 // Additionally ensure that at least one previous attempt has to be in between.
358 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
359 $fields['archive'] = true;
362 $fields['archive'] = false;
365 DBA::update('inbox-status', $fields, ['url' => $url]);
369 * Fetches JSON data for a user
371 * @param string $request request url
372 * @param integer $uid User id of the requester
374 * @return array JSON array
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 public static function fetch($request, $uid)
379 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
380 $curlResult = self::fetchRaw($request, $uid, false, $opts);
382 if (empty($curlResult)) {
386 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
390 $content = json_decode($curlResult->getBody(), true);
391 if (empty($content) || !is_array($content)) {
399 * Fetches raw data for a user
401 * @param string $request request url
402 * @param integer $uid User id of the requester
403 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
404 * @param array $opts (optional parameters) assoziative array with:
405 * 'accept_content' => supply Accept: header with 'accept_content' as the value
406 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
407 * 'nobody' => only return the header
408 * 'cookiejar' => path to cookie jar file
410 * @return object CurlResult
411 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
413 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
418 $owner = User::getOwnerDataById($uid);
423 $owner = User::getSystemAccount();
429 if (!empty($owner['uprvkey'])) {
430 // Header data that is about to be signed.
431 $host = parse_url($request, PHP_URL_HOST);
432 $path = parse_url($request, PHP_URL_PATH);
433 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
435 $header = ['Date: ' . $date, 'Host: ' . $host];
437 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
439 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
441 $header[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
444 if (!empty($opts['accept_content'])) {
445 $header[] = 'Accept: ' . $opts['accept_content'];
449 $curl_opts['header'] = $header;
451 if (!empty($opts['nobody'])) {
452 $curlResult = DI::httpRequest()->head($request, $curl_opts);
454 $curlResult = DI::httpRequest()->get($request, $curl_opts);
456 $return_code = $curlResult->getReturnCode();
458 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
464 * Gets a signer from a given HTTP request
467 * @param $http_headers
469 * @return string Signer
470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472 public static function getSigner($content, $http_headers)
474 if (empty($http_headers['HTTP_SIGNATURE'])) {
478 if (!empty($content)) {
479 $object = json_decode($content, true);
480 if (empty($object)) {
484 $actor = JsonLD::fetchElement($object, 'actor', 'id');
490 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
492 // First take every header
493 foreach ($http_headers as $k => $v) {
494 $field = str_replace('_', '-', strtolower($k));
495 $headers[$field] = $v;
498 // Now add every http header
499 foreach ($http_headers as $k => $v) {
500 if (strpos($k, 'HTTP_') === 0) {
501 $field = str_replace('_', '-', strtolower(substr($k, 5)));
502 $headers[$field] = $v;
506 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
508 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
513 foreach ($sig_block['headers'] as $h) {
514 if (array_key_exists($h, $headers)) {
515 $signed_data .= $h . ': ' . $headers[$h] . "\n";
518 $signed_data = rtrim($signed_data, "\n");
520 if (empty($signed_data)) {
526 // Wildcard value where signing algorithm should be derived from keyId
527 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
528 // Defaulting to SHA256 as it seems to be the prevalent implementation
529 // @see https://arewehs2019yet.vpzom.click
530 if ($sig_block['algorithm'] === 'hs2019') {
531 $algorithm = 'sha256';
534 if ($sig_block['algorithm'] === 'rsa-sha256') {
535 $algorithm = 'sha256';
538 if ($sig_block['algorithm'] === 'rsa-sha512') {
539 $algorithm = 'sha512';
542 if (empty($algorithm)) {
546 $key = self::fetchKey($sig_block['keyId'], $actor);
552 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
556 $hasGoodSignedContent = false;
558 // Check the digest when it is part of the signed data
559 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
560 $digest = explode('=', $headers['digest'], 2);
561 if ($digest[0] === 'SHA-256') {
564 if ($digest[0] === 'SHA-512') {
568 /// @todo add all hashes from the rfc
570 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
574 $hasGoodSignedContent = true;
577 // Check if the signed date field is in an acceptable range
578 if (in_array('date', $sig_block['headers'])) {
579 $diff = abs(strtotime($headers['date']) - time());
581 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
584 $hasGoodSignedContent = true;
587 // Check the content-length when it is part of the signed data
588 if (in_array('content-length', $sig_block['headers'])) {
589 if (strlen($content) != $headers['content-length']) {
594 // Ensure that the authentication had been done with some content
595 // Without this check someone could authenticate with fakeable data
596 if (!$hasGoodSignedContent) {
604 * fetches a key for a given id and actor
609 * @return array with actor url and public key
612 private static function fetchKey($id, $actor)
614 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
616 $profile = APContact::getByURL($url);
617 if (!empty($profile)) {
618 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
619 return ['url' => $url, 'pubkey' => $profile['pubkey']];
620 } elseif ($url != $actor) {
621 $profile = APContact::getByURL($actor);
622 if (!empty($profile)) {
623 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
624 return ['url' => $actor, 'pubkey' => $profile['pubkey']];