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