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