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