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