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