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