]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
cca1ab0bdb9d7f577f8a00b19b4a5a7310a2a012
[friendica.git] / src / Util / HTTPSignature.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Logger;
25 use Friendica\Database\Database;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\APContact;
29 use Friendica\Model\Contact;
30 use Friendica\Model\ItemURI;
31 use Friendica\Model\User;
32 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
33 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35
36 /**
37  * Implements HTTP Signatures per draft-cavage-http-signatures-07.
38  *
39  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
40  *
41  * Other parts of the code for HTTP signing are taken from the Osada project.
42  * https://framagit.org/macgirvin/osada
43  *
44  * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
45  */
46
47 class HTTPSignature
48 {
49         // See draft-cavage-http-signatures-08
50         /**
51          * Verifies a magic request
52          *
53          * @param $key
54          *
55          * @return array with verification data
56          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57          */
58         public static function verifyMagic(string $key): array
59         {
60                 $headers   = null;
61                 $spoofable = false;
62                 $result = [
63                         'signer'         => '',
64                         'header_signed'  => false,
65                         'header_valid'   => false
66                 ];
67
68                 // Decide if $data arrived via controller submission or curl.
69                 $headers = [];
70                 $headers['(request-target)'] = strtolower(DI::args()->getMethod()).' '.$_SERVER['REQUEST_URI'];
71
72                 foreach ($_SERVER as $k => $v) {
73                         if (strpos($k, 'HTTP_') === 0) {
74                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
75                                 $headers[$field] = $v;
76                         }
77                 }
78
79                 $sig_block = null;
80
81                 $sig_block = self::parseSigheader($headers['authorization']);
82
83                 if (!$sig_block) {
84                         Logger::notice('no signature provided.');
85                         return $result;
86                 }
87
88                 $result['header_signed'] = true;
89
90                 $signed_headers = $sig_block['headers'];
91                 if (!$signed_headers) {
92                         $signed_headers = ['date'];
93                 }
94
95                 $signed_data = '';
96                 foreach ($signed_headers as $h) {
97                         if (array_key_exists($h, $headers)) {
98                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
99                         }
100                         if (strpos($h, '.')) {
101                                 $spoofable = true;
102                         }
103                 }
104
105                 $signed_data = rtrim($signed_data, "\n");
106
107                 $algorithm = 'sha512';
108
109                 if ($key && function_exists($key)) {
110                         $result['signer'] = $sig_block['keyId'];
111                         $key = $key($sig_block['keyId']);
112                 }
113
114                 Logger::info('Got keyID ' . $sig_block['keyId']);
115
116                 if (!$key) {
117                         return $result;
118                 }
119
120                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
121
122                 Logger::info('verified: ' . $x);
123
124                 if (!$x) {
125                         return $result;
126                 }
127
128                 if (!$spoofable) {
129                         $result['header_valid'] = true;
130                 }
131
132                 return $result;
133         }
134
135         /**
136          * @param array   $head
137          * @param string  $prvkey
138          * @param string  $keyid (optional, default 'Key')
139          *
140          * @return array
141          */
142         public static function createSig(array $head, string $prvkey, string $keyid = 'Key'): array
143         {
144                 $return_headers = [];
145                 if (!empty($head)) {
146                         $return_headers = $head;
147                 }
148
149                 $alg = 'sha512';
150                 $algorithm = 'rsa-sha512';
151
152                 $x = self::sign($head, $prvkey, $alg);
153
154                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
155                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
156
157                 $return_headers['Authorization'] = ['Signature ' . $headerval];
158
159                 return $return_headers;
160         }
161
162         /**
163          * @param array  $head
164          * @param string $prvkey
165          * @param string $alg (optional) default 'sha256'
166          *
167          * @return array
168          */
169         private static function sign(array $head, string $prvkey, string $alg = 'sha256'): array
170         {
171                 $ret = [];
172                 $headers = '';
173                 $fields  = '';
174
175                 foreach ($head as $k => $v) {
176                         if (is_array($v)) {
177                                 $v = implode(', ', $v);
178                         }
179                         $headers .= strtolower($k) . ': ' . trim($v) . "\n";
180                         if ($fields) {
181                                 $fields .= ' ';
182                         }
183                         $fields .= strtolower($k);
184                 }
185                 // strip the trailing linefeed
186                 $headers = rtrim($headers, "\n");
187
188                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
189
190                 $ret['headers']   = $fields;
191                 $ret['signature'] = $sig;
192
193                 return $ret;
194         }
195
196         /**
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
206          */
207         public static function parseSigheader(string $header): array
208         {
209                 // Remove obsolete folds
210                 $header = preg_replace('/\n\s+/', ' ', $header);
211
212                 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
213
214                 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
215
216                 $regex = "/($token+)=($quotedString|$token+)/ism";
217
218                 $matches = [];
219                 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
220
221                 $headers = [];
222                 foreach ($matches as $match) {
223                         $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
224                 }
225
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);
230                 }
231
232                 $return = [
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'] ?? '')),
239                 ];
240
241                 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
242                         $return['headers'] = ['date'];
243                 }
244
245                 return $return;
246         }
247
248         /**
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
253          */
254         private static function decryptSigheader(array $headers, string $prvkey): string
255         {
256                 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
257                         return Crypto::unencapsulate($headers, $prvkey);
258                 }
259
260                 return '';
261         }
262
263         /*
264          * Functions for ActivityPub
265          */
266
267         /**
268          * Post given data to a target for a user, returns the result class
269          *
270          * @param array  $data   Data that is about to be sent
271          * @param string $target The URL of the inbox
272          * @param array  $owner  Sender owner-view record
273          *
274          * @return ICanHandleHttpResponses
275          */
276         public static function post(array $data, string $target, array $owner): ICanHandleHttpResponses
277         {
278                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
279
280                 // Header data that is about to be signed.
281                 $host = parse_url($target, PHP_URL_HOST);
282                 $path = parse_url($target, PHP_URL_PATH);
283                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
284                 $content_length = strlen($content);
285                 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
286
287                 $headers = [
288                         'Date' => $date,
289                         'Content-Length' => $content_length,
290                         'Digest' => $digest,
291                         'Host' => $host
292                 ];
293
294                 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
295
296                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
297
298                 $headers['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
299
300                 $headers['Content-Type'] = 'application/activity+json';
301
302                 $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'));
303                 $return_code = $postResult->getReturnCode();
304
305                 Logger::info('Transmit to ' . $target . ' returned ' . $return_code);
306
307                 self::setInboxStatus($target, ($return_code >= 200) && ($return_code <= 299));
308
309                 return $postResult;
310         }
311
312         /**
313          * Transmit given data to a target for a user
314          *
315          * @param array  $data   Data that is about to be sent
316          * @param string $target The URL of the inbox
317          * @param array  $owner  Sender owner-vew record
318          *
319          * @return boolean Was the transmission successful?
320          */
321         public static function transmit(array $data, string $target, array $owner): bool
322         {
323                 $postResult = self::post($data, $target, $owner);
324                 $return_code = $postResult->getReturnCode();
325
326                 return ($return_code >= 200) && ($return_code <= 299);
327         }
328
329         /**
330          * Set the delivery status for a given inbox
331          *
332          * @param string  $url     The URL of the inbox
333          * @param boolean $success Transmission status
334          * @param boolean $shared  The inbox is a shared inbox
335          * @param int     $gsid    Server ID
336          * @throws \Exception
337          */
338         static public function setInboxStatus(string $url, bool $success, bool $shared = false, int $gsid = null)
339         {
340                 $now = DateTimeFormat::utcNow();
341
342                 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
343                 if (!DBA::isResult($status)) {
344                         $insertFields = ['url' => $url, 'uri-id' => ItemURI::getIdByURI($url), 'created' => $now, 'shared' => $shared];
345                         if (!empty($gsid)) {
346                                 $insertFields['gsid'] = $gsid;
347                         }
348                         if (!DBA::insert('inbox-status', $insertFields, Database::INSERT_IGNORE)) {
349                                 Logger::warning('Unable to insert inbox-status row', $insertFields);
350                                 return;
351                         }
352
353                         $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
354                 }
355
356                 if ($success) {
357                         $fields = ['success' => $now];
358                 } else {
359                         $fields = ['failure' => $now];
360                 }
361
362                 if (!empty($gsid)) {
363                         $fields['gsid'] = $gsid;
364                 }
365
366                 if ($status['failure'] > DBA::NULL_DATETIME) {
367                         $new_previous_stamp = strtotime($status['failure']);
368                         $old_previous_stamp = strtotime($status['previous']);
369
370                         // Only set "previous" with at least one day difference.
371                         // We use this to assure to not accidentally archive too soon.
372                         if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
373                                 $fields['previous'] = $status['failure'];
374                         }
375                 }
376
377                 if (!$success) {
378                         if ($status['success'] <= DBA::NULL_DATETIME) {
379                                 $stamp1 = strtotime($status['created']);
380                         } else {
381                                 $stamp1 = strtotime($status['success']);
382                         }
383
384                         $stamp2 = strtotime($now);
385                         $previous_stamp = strtotime($status['previous']);
386
387                         // Archive the inbox when there had been failures for five days.
388                         // Additionally ensure that at least one previous attempt has to be in between.
389                         if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
390                                 $fields['archive'] = true;
391                         }
392                 } else {
393                         $fields['archive'] = false;
394                 }
395
396                 if (empty($status['uri-id'])) {
397                         $fields['uri-id'] = ItemURI::getIdByURI($url);
398                 }
399
400                 DBA::update('inbox-status', $fields, ['url' => $url]);
401         }
402
403         /**
404          * Fetches JSON data for a user
405          *
406          * @param string  $request request url
407          * @param integer $uid     User id of the requester
408          *
409          * @return array JSON array
410          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
411          */
412         public static function fetch(string $request, int $uid): array
413         {
414                 $curlResult = self::fetchRaw($request, $uid);
415
416                 if (empty($curlResult)) {
417                         return [];
418                 }
419
420                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
421                         return [];
422                 }
423
424                 $content = json_decode($curlResult->getBody(), true);
425                 if (empty($content) || !is_array($content)) {
426                         return [];
427                 }
428
429                 return $content;
430         }
431
432         /**
433          * Fetches raw data for a user
434          *
435          * @param string  $request request url
436          * @param integer $uid     User id of the requester
437          * @param boolean $binary  TRUE if asked to return binary results (file download) (default is "false")
438          * @param array   $opts    (optional parameters) assoziative array with:
439          *                         'accept_content' => supply Accept: header with 'accept_content' as the value
440          *                         'timeout' => int Timeout in seconds, default system config value or 60 seconds
441          *                         'nobody' => only return the header
442          *                         'cookiejar' => path to cookie jar file
443          *
444          * @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
445          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446          */
447         public static function fetchRaw(string $request, int $uid = 0, array $opts = [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::JSON_AS]])
448         {
449                 $header = [];
450
451                 if (!empty($uid)) {
452                         $owner = User::getOwnerDataById($uid);
453                         if (!$owner) {
454                                 return;
455                         }
456                 } else {
457                         $owner = User::getSystemAccount();
458                         if (!$owner) {
459                                 return;
460                         }
461                 }
462
463                 if (!empty($owner['uprvkey'])) {
464                         // Header data that is about to be signed.
465                         $host = parse_url($request, PHP_URL_HOST);
466                         $path = parse_url($request, PHP_URL_PATH);
467                         $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
468
469                         $header['Date'] = $date;
470                         $header['Host'] = $host;
471
472                         $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
473
474                         $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
475
476                         $header['Signature'] = 'keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
477                 }
478
479                 $curl_opts                             = $opts;
480                 $curl_opts[HttpClientOptions::HEADERS] = $header;
481
482                 if (!empty($opts['nobody'])) {
483                         $curlResult = DI::httpClient()->head($request, $curl_opts);
484                 } else {
485                         $curlResult = DI::httpClient()->get($request, HttpClientAccept::JSON_AS, $curl_opts);
486                 }
487                 $return_code = $curlResult->getReturnCode();
488
489                 Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
490
491                 return $curlResult;
492         }
493
494         /**
495          * Fetch the apcontact entry of the keyId in the given header
496          *
497          * @param array $http_headers
498          *
499          * @return array APContact entry
500          */
501         public static function getKeyIdContact(array $http_headers): array
502         {
503                 if (empty($http_headers['HTTP_SIGNATURE'])) {
504                         Logger::debug('No HTTP_SIGNATURE header', ['header' => $http_headers]);
505                         return [];
506                 }
507
508                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
509
510                 if (empty($sig_block['keyId'])) {
511                         Logger::debug('No keyId', ['sig_block' => $sig_block]);
512                         return [];
513                 }
514
515                 $url = (strpos($sig_block['keyId'], '#') ? substr($sig_block['keyId'], 0, strpos($sig_block['keyId'], '#')) : $sig_block['keyId']);
516                 return APContact::getByURL($url);
517         }
518
519         /**
520          * Gets a signer from a given HTTP request
521          *
522          * @param string $content
523          * @param array $http_headers
524          *
525          * @return string|null|false Signer
526          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527          */
528         public static function getSigner(string $content, array $http_headers)
529         {
530                 if (empty($http_headers['HTTP_SIGNATURE'])) {
531                         Logger::debug('No HTTP_SIGNATURE header');
532                         return false;
533                 }
534
535                 if (!empty($content)) {
536                         $object = json_decode($content, true);
537                         if (empty($object)) {
538                                 Logger::info('No object');
539                                 return false;
540                         }
541
542                         $actor = JsonLD::fetchElement($object, 'actor', 'id') ?? '';
543                 } else {
544                         $actor = '';
545                 }
546
547                 $headers = [];
548                 $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
549
550                 // First take every header
551                 foreach ($http_headers as $k => $v) {
552                         $field = str_replace('_', '-', strtolower($k));
553                         $headers[$field] = $v;
554                 }
555
556                 // Now add every http header
557                 foreach ($http_headers as $k => $v) {
558                         if (strpos($k, 'HTTP_') === 0) {
559                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
560                                 $headers[$field] = $v;
561                         }
562                 }
563
564                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
565
566                 // Add fields from the signature block to the header. See issue 8845
567                 if (!empty($sig_block['created']) && empty($headers['(created)'])) {
568                         $headers['(created)'] = $sig_block['created'];
569                 }
570
571                 if (!empty($sig_block['expires']) && empty($headers['(expires)'])) {
572                         $headers['(expires)'] = $sig_block['expires'];
573                 }
574
575                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
576                         Logger::info('No headers or keyId');
577                         return false;
578                 }
579
580                 $signed_data = '';
581                 foreach ($sig_block['headers'] as $h) {
582                         if (array_key_exists($h, $headers)) {
583                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
584                         } else {
585                                 Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]);
586                         }
587                 }
588                 $signed_data = rtrim($signed_data, "\n");
589
590                 if (empty($signed_data)) {
591                         Logger::info('Signed data is empty');
592                         return false;
593                 }
594
595                 $algorithm = null;
596
597                 // Wildcard value where signing algorithm should be derived from keyId
598                 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
599                 // Defaulting to SHA256 as it seems to be the prevalent implementation
600                 // @see https://arewehs2019yet.vpzom.click
601                 if ($sig_block['algorithm'] === 'hs2019') {
602                         $algorithm = 'sha256';
603                 }
604
605                 if ($sig_block['algorithm'] === 'rsa-sha256') {
606                         $algorithm = 'sha256';
607                 }
608
609                 if ($sig_block['algorithm'] === 'rsa-sha512') {
610                         $algorithm = 'sha512';
611                 }
612
613                 if (empty($algorithm)) {
614                         Logger::info('No alagorithm');
615                         return false;
616                 }
617
618                 $key = self::fetchKey($sig_block['keyId'], $actor);
619                 if (empty($key)) {
620                         Logger::info('Empty key');
621                         return false;
622                 }
623
624                 if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
625                         Logger::info('Actor is a tombstone', ['key' => $key]);
626
627                         if (!Contact::isLocal($key['url'])) {
628                                 // We now delete everything that we possibly knew from this actor
629                                 Contact::deleteContactByUrl($key['url']);
630                         }
631                         return null;
632                 }
633
634                 if (empty($key['pubkey'])) {
635                         Logger::info('Empty pubkey');
636                         return false;
637                 }
638
639                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
640                         Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
641                         return false;
642                 }
643
644                 $hasGoodSignedContent = false;
645
646                 // Check the digest when it is part of the signed data
647                 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
648                         $digest = explode('=', $headers['digest'], 2);
649                         if ($digest[0] === 'SHA-256') {
650                                 $hashalg = 'sha256';
651                         }
652                         if ($digest[0] === 'SHA-512') {
653                                 $hashalg = 'sha512';
654                         }
655
656                         /// @todo add all hashes from the rfc
657
658                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
659                                 Logger::info('Digest does not match');
660                                 return false;
661                         }
662
663                         $hasGoodSignedContent = true;
664                 }
665
666                 if (in_array('date', $sig_block['headers']) && !empty($headers['date'])) {
667                         $created = strtotime($headers['date']);
668                 } elseif (in_array('(created)', $sig_block['headers']) && !empty($sig_block['created'])) {
669                         $created = $sig_block['created'];
670                 } else {
671                         $created = 0;
672                 }
673
674                 if (in_array('(expires)', $sig_block['headers']) && !empty($sig_block['expires'])) {
675                         $expired = min($sig_block['expires'], $created + 300);
676                 } else {
677                         $expired = $created + 300;
678                 }
679
680                 //  Check if the signed date field is in an acceptable range
681                 if (!empty($created)) {
682                         $current = time();
683
684                         // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers
685                         if (($created - 60) > $current) {
686                                 Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
687                                 return false;
688                         }
689
690                         if ($current > $expired) {
691                                 Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
692                                 return false;
693                         }
694
695                         Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
696                         $hasGoodSignedContent = true;
697                 }
698
699                 // Check the content-length when it is part of the signed data
700                 if (in_array('content-length', $sig_block['headers'])) {
701                         if (strlen($content) != $headers['content-length']) {
702                                 Logger::info('Content length does not match');
703                                 return false;
704                         }
705                 }
706
707                 // Ensure that the authentication had been done with some content
708                 // Without this check someone could authenticate with fakeable data
709                 if (!$hasGoodSignedContent) {
710                         Logger::info('No good signed content');
711                         return false;
712                 }
713
714                 return $key['url'];
715         }
716
717         /**
718          * fetches a key for a given id and actor
719          *
720          * @param string $id
721          * @param string $actor
722          *
723          * @return array with actor url and public key
724          * @throws \Exception
725          */
726         private static function fetchKey(string $id, string $actor): array
727         {
728                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
729
730                 $profile = APContact::getByURL($url);
731                 if (!empty($profile)) {
732                         Logger::info('Taking key from id', ['id' => $id]);
733                         return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
734                 } elseif ($url != $actor) {
735                         $profile = APContact::getByURL($actor);
736                         if (!empty($profile)) {
737                                 Logger::info('Taking key from actor', ['actor' => $actor]);
738                                 return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
739                         }
740                 }
741
742                 Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);
743                 return [];
744         }
745 }