]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Make "HTTPRequest::curl" dynamic
[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 use Friendica\Network\HTTPRequest;
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 = 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          */
319         static private function setInboxStatus($url, $success)
320         {
321                 $now = DateTimeFormat::utcNow();
322
323                 $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
324                 if (!DBA::isResult($status)) {
325                         DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
326                         $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
327                 }
328
329                 if ($success) {
330                         $fields = ['success' => $now];
331                 } else {
332                         $fields = ['failure' => $now];
333                 }
334
335                 if ($status['failure'] > DBA::NULL_DATETIME) {
336                         $new_previous_stamp = strtotime($status['failure']);
337                         $old_previous_stamp = strtotime($status['previous']);
338
339                         // Only set "previous" with at least one day difference.
340                         // We use this to assure to not accidentally archive too soon.
341                         if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
342                                 $fields['previous'] = $status['failure'];
343                         }
344                 }
345
346                 if (!$success) {
347                         if ($status['success'] <= DBA::NULL_DATETIME) {
348                                 $stamp1 = strtotime($status['created']);
349                         } else {
350                                 $stamp1 = strtotime($status['success']);
351                         }
352
353                         $stamp2 = strtotime($now);
354                         $previous_stamp = strtotime($status['previous']);
355
356                         // Archive the inbox when there had been failures for five days.
357                         // Additionally ensure that at least one previous attempt has to be in between.
358                         if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
359                                 $fields['archive'] = true;
360                         }
361                 } else {
362                         $fields['archive'] = false;
363                 }
364
365                 DBA::update('inbox-status', $fields, ['url' => $url]);
366         }
367
368         /**
369          * Fetches JSON data for a user
370          *
371          * @param string  $request request url
372          * @param integer $uid     User id of the requester
373          *
374          * @return array JSON array
375          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376          */
377         public static function fetch($request, $uid)
378         {
379                 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
380                 $curlResult = self::fetchRaw($request, $uid, false, $opts);
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          *                         'http_auth' => username:password
408          *                         'novalidate' => do not validate SSL certs, default is to validate using our CA list
409          *                         'nobody' => only return the header
410          *                         'cookiejar' => path to cookie jar file
411          *
412          * @return object CurlResult
413          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
414          */
415         public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
416         {
417                 if (!empty($uid)) {
418                         $owner = User::getOwnerDataById($uid);
419                         if (!$owner) {
420                                 return;
421                         }
422
423                         // Header data that is about to be signed.
424                         $host = parse_url($request, PHP_URL_HOST);
425                         $path = parse_url($request, PHP_URL_PATH);
426                         $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
427
428                         $headers = ['Date: ' . $date, 'Host: ' . $host];
429
430                         $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
431
432                         $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
433
434                         $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
435                 } else {
436                         $headers = [];
437                 }
438
439                 if (!empty($opts['accept_content'])) {
440                         $headers[] = 'Accept: ' . $opts['accept_content'];
441                 }
442
443                 $curl_opts = $opts;
444                 $curl_opts['header'] = $headers;
445
446                 $curlResult = DI::httpRequest()->curl($request, false, $curl_opts);
447                 $return_code = $curlResult->getReturnCode();
448
449                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
450
451                 return $curlResult;
452         }
453
454         /**
455          * Gets a signer from a given HTTP request
456          *
457          * @param $content
458          * @param $http_headers
459          *
460          * @return string Signer
461          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462          */
463         public static function getSigner($content, $http_headers)
464         {
465                 if (empty($http_headers['HTTP_SIGNATURE'])) {
466                         return false;
467                 }
468
469                 if (!empty($content)) {
470                         $object = json_decode($content, true);
471                         if (empty($object)) {
472                                 return false;
473                         }
474
475                         $actor = JsonLD::fetchElement($object, 'actor', 'id');
476                 } else {
477                         $actor = '';
478                 }
479
480                 $headers = [];
481                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
482
483                 // First take every header
484                 foreach ($http_headers as $k => $v) {
485                         $field = str_replace('_', '-', strtolower($k));
486                         $headers[$field] = $v;
487                 }
488
489                 // Now add every http header
490                 foreach ($http_headers as $k => $v) {
491                         if (strpos($k, 'HTTP_') === 0) {
492                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
493                                 $headers[$field] = $v;
494                         }
495                 }
496
497                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
498
499                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
500                         return false;
501                 }
502
503                 $signed_data = '';
504                 foreach ($sig_block['headers'] as $h) {
505                         if (array_key_exists($h, $headers)) {
506                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
507                         }
508                 }
509                 $signed_data = rtrim($signed_data, "\n");
510
511                 if (empty($signed_data)) {
512                         return false;
513                 }
514
515                 $algorithm = null;
516
517                 // Wildcard value where signing algorithm should be derived from keyId
518                 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
519                 // Defaulting to SHA256 as it seems to be the prevalent implementation
520                 // @see https://arewehs2019yet.vpzom.click
521                 if ($sig_block['algorithm'] === 'hs2019') {
522                         $algorithm = 'sha256';
523                 }
524
525                 if ($sig_block['algorithm'] === 'rsa-sha256') {
526                         $algorithm = 'sha256';
527                 }
528
529                 if ($sig_block['algorithm'] === 'rsa-sha512') {
530                         $algorithm = 'sha512';
531                 }
532
533                 if (empty($algorithm)) {
534                         return false;
535                 }
536
537                 $key = self::fetchKey($sig_block['keyId'], $actor);
538
539                 if (empty($key)) {
540                         return false;
541                 }
542
543                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
544                         return false;
545                 }
546
547                 $hasGoodSignedContent = false;
548
549                 // Check the digest when it is part of the signed data
550                 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
551                         $digest = explode('=', $headers['digest'], 2);
552                         if ($digest[0] === 'SHA-256') {
553                                 $hashalg = 'sha256';
554                         }
555                         if ($digest[0] === 'SHA-512') {
556                                 $hashalg = 'sha512';
557                         }
558
559                         /// @todo add all hashes from the rfc
560
561                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
562                                 return false;
563                         }
564
565                         $hasGoodSignedContent = true;
566                 }
567
568                 //  Check if the signed date field is in an acceptable range
569                 if (in_array('date', $sig_block['headers'])) {
570                         $diff = abs(strtotime($headers['date']) - time());
571                         if ($diff > 300) {
572                                 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
573                                 return false;
574                         }
575                         $hasGoodSignedContent = true;
576                 }
577
578                 // Check the content-length when it is part of the signed data
579                 if (in_array('content-length', $sig_block['headers'])) {
580                         if (strlen($content) != $headers['content-length']) {
581                                 return false;
582                         }
583                 }
584
585                 // Ensure that the authentication had been done with some content
586                 // Without this check someone could authenticate with fakeable data
587                 if (!$hasGoodSignedContent) {
588                         return false;
589                 }
590
591                 return $key['url'];
592         }
593
594         /**
595          * fetches a key for a given id and actor
596          *
597          * @param $id
598          * @param $actor
599          *
600          * @return array with actor url and public key
601          * @throws \Exception
602          */
603         private static function fetchKey($id, $actor)
604         {
605                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
606
607                 $profile = APContact::getByURL($url);
608                 if (!empty($profile)) {
609                         Logger::log('Taking key from id ' . $id, Logger::DEBUG);
610                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
611                 } elseif ($url != $actor) {
612                         $profile = APContact::getByURL($actor);
613                         if (!empty($profile)) {
614                                 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
615                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
616                         }
617                 }
618
619                 return false;
620         }
621 }