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
318 static private function setInboxStatus($url, $success)
320 $now = DateTimeFormat::utcNow();
322 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
323 if (!DBA::isResult($status)) {
324 DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
325 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
329 $fields = ['success' => $now];
331 $fields = ['failure' => $now];
334 if ($status['failure'] > DBA::NULL_DATETIME) {
335 $new_previous_stamp = strtotime($status['failure']);
336 $old_previous_stamp = strtotime($status['previous']);
338 // Only set "previous" with at least one day difference.
339 // We use this to assure to not accidentally archive too soon.
340 if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
341 $fields['previous'] = $status['failure'];
346 if ($status['success'] <= DBA::NULL_DATETIME) {
347 $stamp1 = strtotime($status['created']);
349 $stamp1 = strtotime($status['success']);
352 $stamp2 = strtotime($now);
353 $previous_stamp = strtotime($status['previous']);
355 // Archive the inbox when there had been failures for five days.
356 // Additionally ensure that at least one previous attempt has to be in between.
357 if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
358 $fields['archive'] = true;
361 $fields['archive'] = false;
364 DBA::update('inbox-status', $fields, ['url' => $url]);
368 * Fetches JSON data for a user
370 * @param string $request request url
371 * @param integer $uid User id of the requester
373 * @return array JSON array
374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376 public static function fetch($request, $uid)
378 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
379 $curlResult = self::fetchRaw($request, $uid, false, $opts);
381 if (empty($curlResult)) {
385 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
389 $content = json_decode($curlResult->getBody(), true);
390 if (empty($content) || !is_array($content)) {
398 * Fetches raw data for a user
400 * @param string $request request url
401 * @param integer $uid User id of the requester
402 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
403 * @param array $opts (optional parameters) assoziative array with:
404 * 'accept_content' => supply Accept: header with 'accept_content' as the value
405 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
406 * 'nobody' => only return the header
407 * 'cookiejar' => path to cookie jar file
409 * @return object CurlResult
410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
417 $owner = User::getOwnerDataById($uid);
422 $owner = User::getSystemAccount();
428 if (!empty($owner['uprvkey'])) {
429 // Header data that is about to be signed.
430 $host = parse_url($request, PHP_URL_HOST);
431 $path = parse_url($request, PHP_URL_PATH);
432 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
434 $header = ['Date: ' . $date, 'Host: ' . $host];
436 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
438 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
440 $header[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
443 if (!empty($opts['accept_content'])) {
444 $header[] = 'Accept: ' . $opts['accept_content'];
448 $curl_opts['header'] = $header;
450 if (!empty($opts['nobody'])) {
451 $curlResult = DI::httpRequest()->head($request, $curl_opts);
453 $curlResult = DI::httpRequest()->get($request, $curl_opts);
455 $return_code = $curlResult->getReturnCode();
457 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
463 * Gets a signer from a given HTTP request
466 * @param $http_headers
468 * @return string Signer
469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
471 public static function getSigner($content, $http_headers)
473 if (empty($http_headers['HTTP_SIGNATURE'])) {
477 if (!empty($content)) {
478 $object = json_decode($content, true);
479 if (empty($object)) {
483 $actor = JsonLD::fetchElement($object, 'actor', 'id');
489 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
491 // First take every header
492 foreach ($http_headers as $k => $v) {
493 $field = str_replace('_', '-', strtolower($k));
494 $headers[$field] = $v;
497 // Now add every http header
498 foreach ($http_headers as $k => $v) {
499 if (strpos($k, 'HTTP_') === 0) {
500 $field = str_replace('_', '-', strtolower(substr($k, 5)));
501 $headers[$field] = $v;
505 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
507 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
512 foreach ($sig_block['headers'] as $h) {
513 if (array_key_exists($h, $headers)) {
514 $signed_data .= $h . ': ' . $headers[$h] . "\n";
517 $signed_data = rtrim($signed_data, "\n");
519 if (empty($signed_data)) {
525 // Wildcard value where signing algorithm should be derived from keyId
526 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
527 // Defaulting to SHA256 as it seems to be the prevalent implementation
528 // @see https://arewehs2019yet.vpzom.click
529 if ($sig_block['algorithm'] === 'hs2019') {
530 $algorithm = 'sha256';
533 if ($sig_block['algorithm'] === 'rsa-sha256') {
534 $algorithm = 'sha256';
537 if ($sig_block['algorithm'] === 'rsa-sha512') {
538 $algorithm = 'sha512';
541 if (empty($algorithm)) {
545 $key = self::fetchKey($sig_block['keyId'], $actor);
551 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
555 $hasGoodSignedContent = false;
557 // Check the digest when it is part of the signed data
558 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
559 $digest = explode('=', $headers['digest'], 2);
560 if ($digest[0] === 'SHA-256') {
563 if ($digest[0] === 'SHA-512') {
567 /// @todo add all hashes from the rfc
569 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
573 $hasGoodSignedContent = true;
576 // Check if the signed date field is in an acceptable range
577 if (in_array('date', $sig_block['headers'])) {
578 $diff = abs(strtotime($headers['date']) - time());
580 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
583 $hasGoodSignedContent = true;
586 // Check the content-length when it is part of the signed data
587 if (in_array('content-length', $sig_block['headers'])) {
588 if (strlen($content) != $headers['content-length']) {
593 // Ensure that the authentication had been done with some content
594 // Without this check someone could authenticate with fakeable data
595 if (!$hasGoodSignedContent) {
603 * fetches a key for a given id and actor
608 * @return array with actor url and public key
611 private static function fetchKey($id, $actor)
613 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
615 $profile = APContact::getByURL($url);
616 if (!empty($profile)) {
617 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
618 return ['url' => $url, 'pubkey' => $profile['pubkey']];
619 } elseif ($url != $actor) {
620 $profile = APContact::getByURL($actor);
621 if (!empty($profile)) {
622 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
623 return ['url' => $actor, 'pubkey' => $profile['pubkey']];