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