]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
- Revert HTTPSignature change
[friendica.git] / src / Util / HTTPSignature.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\CurlResult;
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($_SERVER['REQUEST_METHOD']).' '.$_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::log('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::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
112
113                 if (!$key) {
114                         return $result;
115                 }
116
117                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
118
119                 Logger::log('verified: ' . $x, Logger::DEBUG);
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
143                 $alg = 'sha512';
144                 $algorithm = 'rsa-sha512';
145
146                 $x = self::sign($head, $prvkey, $alg);
147
148                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
149                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
150
151                 $sighead = 'Authorization: Signature ' . $headerval;
152
153                 if ($head) {
154                         foreach ($head as $k => $v) {
155                                 $return_headers[] = $k . ': ' . $v;
156                         }
157                 }
158
159                 $return_headers[] = $sighead;
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($head, $prvkey, $alg = 'sha256')
172         {
173                 $ret = [];
174                 $headers = '';
175                 $fields  = '';
176
177                 foreach ($head as $k => $v) {
178                         $headers .= strtolower($k) . ': ' . trim($v) . "\n";
179                         if ($fields) {
180                                 $fields .= ' ';
181                         }
182                         $fields .= strtolower($k);
183                 }
184                 // strip the trailing linefeed
185                 $headers = rtrim($headers, "\n");
186
187                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
188
189                 $ret['headers']   = $fields;
190                 $ret['signature'] = $sig;
191
192                 return $ret;
193         }
194
195         /**
196          * @param string $header
197          * @return array associative array with
198          *   - \e string \b keyID
199          *   - \e string \b created
200          *   - \e string \b expires
201          *   - \e string \b algorithm
202          *   - \e array  \b headers
203          *   - \e string \b signature
204          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
205          */
206         public static function parseSigheader($header)
207         {
208                 // Remove obsolete folds
209                 $header = preg_replace('/\n\s+/', ' ', $header);
210
211                 $token = "[!#$%&'*+.^_`|~0-9A-Za-z-]";
212
213                 $quotedString = '"(?:\\\\.|[^"\\\\])*"';
214
215                 $regex = "/($token+)=($quotedString|$token+)/ism";
216
217                 $matches = [];
218                 preg_match_all($regex, $header, $matches, PREG_SET_ORDER);
219
220                 $headers = [];
221                 foreach ($matches as $match) {
222                         $headers[$match[1]] = trim($match[2] ?: $match[3], '"');
223                 }
224
225                 // if the header is encrypted, decrypt with (default) site private key and continue
226                 if (!empty($headers['iv'])) {
227                         $header = self::decryptSigheader($headers, DI::config()->get('system', 'prvkey'));
228                         return self::parseSigheader($header);
229                 }
230
231                 $return = [
232                         'keyId'     => $headers['keyId'] ?? '',
233                         'algorithm' => $headers['algorithm'] ?? 'rsa-sha256',
234                         'created'   => $headers['created'] ?? null,
235                         'expires'   => $headers['expires'] ?? null,
236                         'headers'   => explode(' ', $headers['headers'] ?? ''),
237                         'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')),
238                 ];
239
240                 if (!empty($return['signature']) && !empty($return['algorithm']) && empty($return['headers'])) {
241                         $return['headers'] = ['date'];
242                 }
243
244                 return $return;
245         }
246
247         /**
248          * @param array  $headers Signature headers
249          * @param string $prvkey  The site private key
250          * @return string Decrypted signature string
251          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252          */
253         private static function decryptSigheader(array $headers, string $prvkey)
254         {
255                 if (!empty($headers['iv']) && !empty($headers['key']) && !empty($headers['data'])) {
256                         return Crypto::unencapsulate($headers, $prvkey);
257                 }
258
259                 return '';
260         }
261
262         /*
263          * Functions for ActivityPub
264          */
265
266         /**
267          * Transmit given data to a target for a user
268          *
269          * @param array   $data   Data that is about to be send
270          * @param string  $target The URL of the inbox
271          * @param integer $uid    User id of the sender
272          *
273          * @return boolean Was the transmission successful?
274          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275          */
276         public static function transmit($data, $target, $uid)
277         {
278                 $owner = User::getOwnerDataById($uid);
279
280                 if (!$owner) {
281                         return;
282                 }
283
284                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
285
286                 // Header data that is about to be signed.
287                 $host = parse_url($target, PHP_URL_HOST);
288                 $path = parse_url($target, PHP_URL_PATH);
289                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
290                 $content_length = strlen($content);
291                 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
292
293                 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
294
295                 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
296
297                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
298
299                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
300
301                 $headers[] = 'Content-Type: application/activity+json';
302
303                 $postResult = DI::httpRequest()->post($target, $content, $headers);
304                 $return_code = $postResult->getReturnCode();
305
306                 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
307
308                 $success = ($return_code >= 200) && ($return_code <= 299);
309
310                 self::setInboxStatus($target, $success);
311
312                 return $success;
313         }
314
315         /**
316          * Set the delivery status for a given inbox
317          *
318          * @param string  $url     The URL of the inbox
319          * @param boolean $success Transmission status
320          * @param boolean $shared  The inbox is a shared inbox
321          */
322         static public function setInboxStatus($url, $success, $shared = false)
323         {
324                 $now = DateTimeFormat::utcNow();
325
326                 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
327                 if (!DBA::isResult($status)) {
328                         DBA::insert('inbox-status', ['url' => $url, 'created' => $now, 'shared' => $shared], Database::INSERT_IGNORE);
329                         $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
330                 }
331
332                 if ($success) {
333                         $fields = ['success' => $now];
334                 } else {
335                         $fields = ['failure' => $now];
336                 }
337
338                 if ($status['failure'] > DBA::NULL_DATETIME) {
339                         $new_previous_stamp = strtotime($status['failure']);
340                         $old_previous_stamp = strtotime($status['previous']);
341
342                         // Only set "previous" with at least one day difference.
343                         // We use this to assure to not accidentally archive too soon.
344                         if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
345                                 $fields['previous'] = $status['failure'];
346                         }
347                 }
348
349                 if (!$success) {
350                         if ($status['success'] <= DBA::NULL_DATETIME) {
351                                 $stamp1 = strtotime($status['created']);
352                         } else {
353                                 $stamp1 = strtotime($status['success']);
354                         }
355
356                         $stamp2 = strtotime($now);
357                         $previous_stamp = strtotime($status['previous']);
358
359                         // Archive the inbox when there had been failures for five days.
360                         // Additionally ensure that at least one previous attempt has to be in between.
361                         if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
362                                 $fields['archive'] = true;
363                         }
364                 } else {
365                         $fields['archive'] = false;
366                 }
367
368                 DBA::update('inbox-status', $fields, ['url' => $url]);
369         }
370
371         /**
372          * Fetches JSON data for a user
373          *
374          * @param string  $request request url
375          * @param integer $uid     User id of the requester
376          *
377          * @return array JSON array
378          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
379          */
380         public static function fetch($request, $uid)
381         {
382                 $curlResult = self::fetchRaw($request, $uid);
383
384                 if (empty($curlResult)) {
385                         return false;
386                 }
387
388                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
389                         return false;
390                 }
391
392                 $content = json_decode($curlResult->getBody(), true);
393                 if (empty($content) || !is_array($content)) {
394                         return false;
395                 }
396
397                 return $content;
398         }
399
400         /**
401          * Fetches raw data for a user
402          *
403          * @param string  $request request url
404          * @param integer $uid     User id of the requester
405          * @param boolean $binary  TRUE if asked to return binary results (file download) (default is "false")
406          * @param array   $opts    (optional parameters) assoziative array with:
407          *                         'accept_content' => supply Accept: header with 'accept_content' as the value
408          *                         'timeout' => int Timeout in seconds, default system config value or 60 seconds
409          *                         'nobody' => only return the header
410          *                         'cookiejar' => path to cookie jar file
411          *
412          * @return CurlResult CurlResult
413          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
414          */
415         public static function fetchRaw($request, $uid = 0, $opts = ['accept_content' => 'application/activity+json, application/ld+json'])
416         {
417                 $header = [];
418
419                 if (!empty($uid)) {
420                         $owner = User::getOwnerDataById($uid);
421                         if (!$owner) {
422                                 return;
423                         }
424                 } else {
425                         $owner = User::getSystemAccount();
426                         if (!$owner) {
427                                 return;
428                         }
429                 }
430
431                 if (!empty($owner['uprvkey'])) {
432                         // Header data that is about to be signed.
433                         $host = parse_url($request, PHP_URL_HOST);
434                         $path = parse_url($request, PHP_URL_PATH);
435                         $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
436
437                         $header = ['Date: ' . $date, 'Host: ' . $host];
438
439                         $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
440
441                         $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
442
443                         $header[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
444                 }
445
446                 if (!empty($opts['accept_content'])) {
447                         $header[] = 'Accept: ' . $opts['accept_content'];
448                 }
449
450                 $curl_opts = $opts;
451                 $curl_opts['header'] = $header;
452
453                 if (!empty($opts['nobody'])) {
454                         $curlResult = DI::httpRequest()->head($request, $curl_opts);
455                 } else {
456                         $curlResult = DI::httpRequest()->get($request, $curl_opts);
457                 }
458                 $return_code = $curlResult->getReturnCode();
459
460                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
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::info('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($http_headers['REQUEST_METHOD']) . ' ' . 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::log("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 }