]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
e4d2e93ff0ac9bf09587768722602a45689682d2
[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\Database\DBA;
25 use Friendica\Core\Logger;
26 use Friendica\DI;
27 use Friendica\Model\User;
28 use Friendica\Model\APContact;
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 associate array with
195          *   - \e string \b keyID
196          *   - \e string \b algorithm
197          *   - \e array  \b headers
198          *   - \e string \b signature
199          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
200          */
201         public static function parseSigheader($header)
202         {
203                 $ret = [];
204                 $matches = [];
205
206                 // if the header is encrypted, decrypt with (default) site private key and continue
207                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
208                         $header = self::decryptSigheader($header);
209                 }
210
211                 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
212                         $ret['keyId'] = $matches[1];
213                 }
214
215                 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
216                         $ret['algorithm'] = $matches[1];
217                 } else {
218                         $ret['algorithm'] = 'rsa-sha256';
219                 }
220
221                 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
222                         $ret['headers'] = explode(' ', $matches[1]);
223                 }
224
225                 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
226                         $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
227                 }
228
229                 if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
230                         $ret['headers'] = ['date'];
231                 }
232
233                 return $ret;
234         }
235
236         /**
237          * @param string $header
238          * @param string $prvkey (optional), if not set use site private key
239          *
240          * @return array|string associative array, empty string if failue
241          *   - \e string \b iv
242          *   - \e string \b key
243          *   - \e string \b alg
244          *   - \e string \b data
245          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
246          */
247         private static function decryptSigheader($header, $prvkey = null)
248         {
249                 $iv = $key = $alg = $data = null;
250
251                 if (!$prvkey) {
252                         $prvkey = DI::config()->get('system', 'prvkey');
253                 }
254
255                 $matches = [];
256
257                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
258                         $iv = $matches[1];
259                 }
260
261                 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
262                         $key = $matches[1];
263                 }
264
265                 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
266                         $alg = $matches[1];
267                 }
268
269                 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
270                         $data = $matches[1];
271                 }
272
273                 if ($iv && $key && $alg && $data) {
274                         return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
275                 }
276
277                 return '';
278         }
279
280         /*
281          * Functions for ActivityPub
282          */
283
284         /**
285          * Transmit given data to a target for a user
286          *
287          * @param array   $data   Data that is about to be send
288          * @param string  $target The URL of the inbox
289          * @param integer $uid    User id of the sender
290          *
291          * @return boolean Was the transmission successful?
292          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
293          */
294         public static function transmit($data, $target, $uid)
295         {
296                 $owner = User::getOwnerDataById($uid);
297
298                 if (!$owner) {
299                         return;
300                 }
301
302                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
303
304                 // Header data that is about to be signed.
305                 $host = parse_url($target, PHP_URL_HOST);
306                 $path = parse_url($target, PHP_URL_PATH);
307                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
308                 $content_length = strlen($content);
309                 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
310
311                 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
312
313                 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
314
315                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
316
317                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
318
319                 $headers[] = 'Content-Type: application/activity+json';
320
321                 $postResult = Network::post($target, $content, $headers);
322                 $return_code = $postResult->getReturnCode();
323
324                 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
325
326                 $success = ($return_code >= 200) && ($return_code <= 299);
327
328                 self::setInboxStatus($target, $success);
329
330                 return $success;
331         }
332
333         /**
334          * Set the delivery status for a given inbox
335          *
336          * @param string  $url     The URL of the inbox
337          * @param boolean $success Transmission status
338          */
339         static private function setInboxStatus($url, $success)
340         {
341                 $now = DateTimeFormat::utcNow();
342
343                 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
344                 if (!DBA::isResult($status)) {
345                         DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
346                         $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
347                 }
348
349                 if ($success) {
350                         $fields = ['success' => $now];
351                 } else {
352                         $fields = ['failure' => $now];
353                 }
354
355                 if ($status['failure'] > DBA::NULL_DATETIME) {
356                         $new_previous_stamp = strtotime($status['failure']);
357                         $old_previous_stamp = strtotime($status['previous']);
358
359                         // Only set "previous" with at least one day difference.
360                         // We use this to assure to not accidentally archive too soon.
361                         if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
362                                 $fields['previous'] = $status['failure'];
363                         }
364                 }
365
366                 if (!$success) {
367                         if ($status['success'] <= DBA::NULL_DATETIME) {
368                                 $stamp1 = strtotime($status['created']);
369                         } else {
370                                 $stamp1 = strtotime($status['success']);
371                         }
372
373                         $stamp2 = strtotime($now);
374                         $previous_stamp = strtotime($status['previous']);
375
376                         // Archive the inbox when there had been failures for five days.
377                         // Additionally ensure that at least one previous attempt has to be in between.
378                         if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
379                                 $fields['archive'] = true;
380                         }
381                 } else {
382                         $fields['archive'] = false;
383                 }
384
385                 DBA::update('inbox-status', $fields, ['url' => $url]);
386         }
387
388         /**
389          * Fetches JSON data for a user
390          *
391          * @param string  $request request url
392          * @param integer $uid     User id of the requester
393          *
394          * @return array JSON array
395          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396          */
397         public static function fetch($request, $uid)
398         {
399                 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
400                 $curlResult = self::fetchRaw($request, $uid, false, $opts);
401
402                 if (empty($curlResult)) {
403                         return false;
404                 }
405
406                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
407                         return false;
408                 }
409
410                 $content = json_decode($curlResult->getBody(), true);
411                 if (empty($content) || !is_array($content)) {
412                         return false;
413                 }
414
415                 return $content;
416         }
417
418         /**
419          * Fetches raw data for a user
420          *
421          * @param string  $request request url
422          * @param integer $uid     User id of the requester
423          * @param boolean $binary  TRUE if asked to return binary results (file download) (default is "false")
424          * @param array   $opts    (optional parameters) assoziative array with:
425          *                         'accept_content' => supply Accept: header with 'accept_content' as the value
426          *                         'timeout' => int Timeout in seconds, default system config value or 60 seconds
427          *                         'http_auth' => username:password
428          *                         'novalidate' => do not validate SSL certs, default is to validate using our CA list
429          *                         'nobody' => only return the header
430          *                         'cookiejar' => path to cookie jar file
431          *
432          * @return object CurlResult
433          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434          */
435         public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
436         {
437                 if (!empty($uid)) {
438                         $owner = User::getOwnerDataById($uid);
439                         if (!$owner) {
440                                 return;
441                         }
442
443                         // Header data that is about to be signed.
444                         $host = parse_url($request, PHP_URL_HOST);
445                         $path = parse_url($request, PHP_URL_PATH);
446                         $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
447
448                         $headers = ['Date: ' . $date, 'Host: ' . $host];
449
450                         $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
451
452                         $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
453
454                         $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
455                 } else {
456                         $headers = [];
457                 }
458
459                 if (!empty($opts['accept_content'])) {
460                         $headers[] = 'Accept: ' . $opts['accept_content'];
461                 }
462
463                 $curl_opts = $opts;
464                 $curl_opts['header'] = $headers;
465
466                 $curlResult = Network::curl($request, false, $curl_opts);
467                 $return_code = $curlResult->getReturnCode();
468
469                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
470
471                 return $curlResult;
472         }
473
474         /**
475          * Gets a signer from a given HTTP request
476          *
477          * @param $content
478          * @param $http_headers
479          *
480          * @return string Signer
481          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482          */
483         public static function getSigner($content, $http_headers)
484         {
485                 if (empty($http_headers['HTTP_SIGNATURE'])) {
486                         return false;
487                 }
488
489                 if (!empty($content)) {
490                         $object = json_decode($content, true);
491                         if (empty($object)) {
492                                 return false;
493                         }
494
495                         $actor = JsonLD::fetchElement($object, 'actor', 'id');
496                 } else {
497                         $actor = '';
498                 }
499
500                 $headers = [];
501                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
502
503                 // First take every header
504                 foreach ($http_headers as $k => $v) {
505                         $field = str_replace('_', '-', strtolower($k));
506                         $headers[$field] = $v;
507                 }
508
509                 // Now add every http header
510                 foreach ($http_headers as $k => $v) {
511                         if (strpos($k, 'HTTP_') === 0) {
512                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
513                                 $headers[$field] = $v;
514                         }
515                 }
516
517                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
518
519                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
520                         return false;
521                 }
522
523                 $signed_data = '';
524                 foreach ($sig_block['headers'] as $h) {
525                         if (array_key_exists($h, $headers)) {
526                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
527                         }
528                 }
529                 $signed_data = rtrim($signed_data, "\n");
530
531                 if (empty($signed_data)) {
532                         return false;
533                 }
534
535                 $algorithm = null;
536
537                 if ($sig_block['algorithm'] === 'rsa-sha256') {
538                         $algorithm = 'sha256';
539                 }
540
541                 if ($sig_block['algorithm'] === 'rsa-sha512') {
542                         $algorithm = 'sha512';
543                 }
544
545                 if (empty($algorithm)) {
546                         return false;
547                 }
548
549                 $key = self::fetchKey($sig_block['keyId'], $actor);
550
551                 if (empty($key)) {
552                         return false;
553                 }
554
555                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
556                         return false;
557                 }
558
559                 $hasGoodSignedContent = false;
560
561                 // Check the digest when it is part of the signed data
562                 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
563                         $digest = explode('=', $headers['digest'], 2);
564                         if ($digest[0] === 'SHA-256') {
565                                 $hashalg = 'sha256';
566                         }
567                         if ($digest[0] === 'SHA-512') {
568                                 $hashalg = 'sha512';
569                         }
570
571                         /// @todo add all hashes from the rfc
572
573                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
574                                 return false;
575                         }
576
577                         $hasGoodSignedContent = true;
578                 }
579
580                 //  Check if the signed date field is in an acceptable range
581                 if (in_array('date', $sig_block['headers'])) {
582                         $diff = abs(strtotime($headers['date']) - time());
583                         if ($diff > 300) {
584                                 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
585                                 return false;
586                         }
587                         $hasGoodSignedContent = true;
588                 }
589
590                 // Check the content-length when it is part of the signed data
591                 if (in_array('content-length', $sig_block['headers'])) {
592                         if (strlen($content) != $headers['content-length']) {
593                                 return false;
594                         }
595                 }
596
597                 // Ensure that the authentication had been done with some content
598                 // Without this check someone could authenticate with fakeable data
599                 if (!$hasGoodSignedContent) {
600                         return false;
601                 }
602
603                 return $key['url'];
604         }
605
606         /**
607          * fetches a key for a given id and actor
608          *
609          * @param $id
610          * @param $actor
611          *
612          * @return array with actor url and public key
613          * @throws \Exception
614          */
615         private static function fetchKey($id, $actor)
616         {
617                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
618
619                 $profile = APContact::getByURL($url);
620                 if (!empty($profile)) {
621                         Logger::log('Taking key from id ' . $id, Logger::DEBUG);
622                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
623                 } elseif ($url != $actor) {
624                         $profile = APContact::getByURL($actor);
625                         if (!empty($profile)) {
626                                 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
627                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
628                         }
629                 }
630
631                 return false;
632         }
633 }