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