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