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