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