2b98b1a32e3116e8074d639e4774404bd9353992
[friendica.git/.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          *                         'nobody' => only return the header
407          *                         'cookiejar' => path to cookie jar file
408          *
409          * @return object CurlResult
410          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
411          */
412         public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
413         {
414                 $headers = [];
415
416                 if (!empty($uid)) {
417                         $owner = User::getOwnerDataById($uid);
418                         if (!$owner) {
419                                 return;
420                         }
421                 } else {
422                         $owner = User::getSystemAccount();
423                         if (!$owner) {
424                                 return;
425                         }
426                 }
427
428                 if (!empty($owner['uprvkey'])) {
429                         // Header data that is about to be signed.
430                         $host = parse_url($request, PHP_URL_HOST);
431                         $path = parse_url($request, PHP_URL_PATH);
432                         $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
433
434                         $headers = ['Date: ' . $date, 'Host: ' . $host];
435
436                         $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
437
438                         $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
439
440                         $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
441                 }
442
443                 if (!empty($opts['accept_content'])) {
444                         $headers[] = 'Accept: ' . $opts['accept_content'];
445                 }
446
447                 $curl_opts = $opts;
448                 $curl_opts['header'] = $headers;
449
450                 if ($opts['nobody']) {
451                         $curlResult = DI::httpRequest()->head($request, $curl_opts);
452                 } else {
453                         $curlResult = DI::httpRequest()->get($request, $curl_opts);
454                 }
455                 $return_code = $curlResult->getReturnCode();
456
457                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
458
459                 return $curlResult;
460         }
461
462         /**
463          * Gets a signer from a given HTTP request
464          *
465          * @param $content
466          * @param $http_headers
467          *
468          * @return string Signer
469          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
470          */
471         public static function getSigner($content, $http_headers)
472         {
473                 if (empty($http_headers['HTTP_SIGNATURE'])) {
474                         return false;
475                 }
476
477                 if (!empty($content)) {
478                         $object = json_decode($content, true);
479                         if (empty($object)) {
480                                 return false;
481                         }
482
483                         $actor = JsonLD::fetchElement($object, 'actor', 'id');
484                 } else {
485                         $actor = '';
486                 }
487
488                 $headers = [];
489                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH);
490
491                 // First take every header
492                 foreach ($http_headers as $k => $v) {
493                         $field = str_replace('_', '-', strtolower($k));
494                         $headers[$field] = $v;
495                 }
496
497                 // Now add every http header
498                 foreach ($http_headers as $k => $v) {
499                         if (strpos($k, 'HTTP_') === 0) {
500                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
501                                 $headers[$field] = $v;
502                         }
503                 }
504
505                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
506
507                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
508                         return false;
509                 }
510
511                 $signed_data = '';
512                 foreach ($sig_block['headers'] as $h) {
513                         if (array_key_exists($h, $headers)) {
514                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
515                         }
516                 }
517                 $signed_data = rtrim($signed_data, "\n");
518
519                 if (empty($signed_data)) {
520                         return false;
521                 }
522
523                 $algorithm = null;
524
525                 // Wildcard value where signing algorithm should be derived from keyId
526                 // @see https://tools.ietf.org/html/draft-ietf-httpbis-message-signatures-00#section-4.1
527                 // Defaulting to SHA256 as it seems to be the prevalent implementation
528                 // @see https://arewehs2019yet.vpzom.click
529                 if ($sig_block['algorithm'] === 'hs2019') {
530                         $algorithm = 'sha256';
531                 }
532
533                 if ($sig_block['algorithm'] === 'rsa-sha256') {
534                         $algorithm = 'sha256';
535                 }
536
537                 if ($sig_block['algorithm'] === 'rsa-sha512') {
538                         $algorithm = 'sha512';
539                 }
540
541                 if (empty($algorithm)) {
542                         return false;
543                 }
544
545                 $key = self::fetchKey($sig_block['keyId'], $actor);
546
547                 if (empty($key)) {
548                         return false;
549                 }
550
551                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
552                         return false;
553                 }
554
555                 $hasGoodSignedContent = false;
556
557                 // Check the digest when it is part of the signed data
558                 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
559                         $digest = explode('=', $headers['digest'], 2);
560                         if ($digest[0] === 'SHA-256') {
561                                 $hashalg = 'sha256';
562                         }
563                         if ($digest[0] === 'SHA-512') {
564                                 $hashalg = 'sha512';
565                         }
566
567                         /// @todo add all hashes from the rfc
568
569                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
570                                 return false;
571                         }
572
573                         $hasGoodSignedContent = true;
574                 }
575
576                 //  Check if the signed date field is in an acceptable range
577                 if (in_array('date', $sig_block['headers'])) {
578                         $diff = abs(strtotime($headers['date']) - time());
579                         if ($diff > 300) {
580                                 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
581                                 return false;
582                         }
583                         $hasGoodSignedContent = true;
584                 }
585
586                 // Check the content-length when it is part of the signed data
587                 if (in_array('content-length', $sig_block['headers'])) {
588                         if (strlen($content) != $headers['content-length']) {
589                                 return false;
590                         }
591                 }
592
593                 // Ensure that the authentication had been done with some content
594                 // Without this check someone could authenticate with fakeable data
595                 if (!$hasGoodSignedContent) {
596                         return false;
597                 }
598
599                 return $key['url'];
600         }
601
602         /**
603          * fetches a key for a given id and actor
604          *
605          * @param $id
606          * @param $actor
607          *
608          * @return array with actor url and public key
609          * @throws \Exception
610          */
611         private static function fetchKey($id, $actor)
612         {
613                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
614
615                 $profile = APContact::getByURL($url);
616                 if (!empty($profile)) {
617                         Logger::log('Taking key from id ' . $id, Logger::DEBUG);
618                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
619                 } elseif ($url != $actor) {
620                         $profile = APContact::getByURL($actor);
621                         if (!empty($profile)) {
622                                 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
623                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
624                         }
625                 }
626
627                 return false;
628         }
629 }