]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Merge pull request #6340 from MrPetovan/bug/1495-fix-admin-theme-settings
[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
16 /**
17  * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
18  *
19  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
20  *
21  * Other parts of the code for HTTP signing are taken from the Osada project.
22  * https://framagit.org/macgirvin/osada
23  *
24  * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
25  */
26
27 class HTTPSignature
28 {
29         // See draft-cavage-http-signatures-08
30         /**
31          * @brief Verifies a magic request
32          *
33          * @param $key
34          *
35          * @return array with verification data
36          */
37         public static function verifyMagic($key)
38         {
39                 $headers   = null;
40                 $spoofable = false;
41                 $result = [
42                         'signer'         => '',
43                         'header_signed'  => false,
44                         'header_valid'   => false
45                 ];
46
47                 // Decide if $data arrived via controller submission or curl.
48                 $headers = [];
49                 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
50
51                 foreach ($_SERVER as $k => $v) {
52                         if (strpos($k, 'HTTP_') === 0) {
53                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
54                                 $headers[$field] = $v;
55                         }
56                 }
57
58                 $sig_block = null;
59
60                 $sig_block = self::parseSigheader($headers['authorization']);
61
62                 if (!$sig_block) {
63                         Logger::log('no signature provided.');
64                         return $result;
65                 }
66
67                 $result['header_signed'] = true;
68
69                 $signed_headers = $sig_block['headers'];
70                 if (!$signed_headers) {
71                         $signed_headers = ['date'];
72                 }
73
74                 $signed_data = '';
75                 foreach ($signed_headers as $h) {
76                         if (array_key_exists($h, $headers)) {
77                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
78                         }
79                         if (strpos($h, '.')) {
80                                 $spoofable = true;
81                         }
82                 }
83
84                 $signed_data = rtrim($signed_data, "\n");
85
86                 $algorithm = 'sha512';
87
88                 if ($key && function_exists($key)) {
89                         $result['signer'] = $sig_block['keyId'];
90                         $key = $key($sig_block['keyId']);
91                 }
92
93                 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
94
95                 if (!$key) {
96                         return $result;
97                 }
98
99                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
100
101                 Logger::log('verified: ' . $x, Logger::DEBUG);
102
103                 if (!$x) {
104                         return $result;
105                 }
106
107                 if (!$spoofable) {
108                         $result['header_valid'] = true;
109                 }
110
111                 return $result;
112         }
113
114         /**
115          * @brief
116          *
117          * @param array   $head
118          * @param string  $prvkey
119          * @param string  $keyid (optional, default 'Key')
120          *
121          * @return array
122          */
123         public static function createSig($head, $prvkey, $keyid = 'Key')
124         {
125                 $return_headers = [];
126
127                 $alg = 'sha512';
128                 $algorithm = 'rsa-sha512';
129
130                 $x = self::sign($head, $prvkey, $alg);
131
132                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
133                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
134
135                 $sighead = 'Authorization: Signature ' . $headerval;
136
137                 if ($head) {
138                         foreach ($head as $k => $v) {
139                                 $return_headers[] = $k . ': ' . $v;
140                         }
141                 }
142
143                 $return_headers[] = $sighead;
144
145                 return $return_headers;
146         }
147
148         /**
149          * @brief
150          *
151          * @param array  $head
152          * @param string $prvkey
153          * @param string $alg (optional) default 'sha256'
154          *
155          * @return array
156          */
157         private static function sign($head, $prvkey, $alg = 'sha256')
158         {
159                 $ret = [];
160                 $headers = '';
161                 $fields  = '';
162
163                 foreach ($head as $k => $v) {
164                         $headers .= strtolower($k) . ': ' . trim($v) . "\n";
165                         if ($fields) {
166                                 $fields .= ' ';
167                         }
168                         $fields .= strtolower($k);
169                 }
170                 // strip the trailing linefeed
171                 $headers = rtrim($headers, "\n");
172
173                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
174
175                 $ret['headers']   = $fields;
176                 $ret['signature'] = $sig;
177
178                 return $ret;
179         }
180
181         /**
182          * @brief
183          *
184          * @param string $header
185          * @return array associate array with
186          *   - \e string \b keyID
187          *   - \e string \b algorithm
188          *   - \e array  \b headers
189          *   - \e string \b signature
190          */
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 (($ret['signature']) && ($ret['algorithm']) && (!$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          */
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          */
284         public static function transmit($data, $target, $uid)
285         {
286                 $owner = User::getOwnerDataById($uid);
287
288                 if (!$owner) {
289                         return;
290                 }
291
292                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
293
294                 // Header data that is about to be signed.
295                 $host = parse_url($target, PHP_URL_HOST);
296                 $path = parse_url($target, PHP_URL_PATH);
297                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
298                 $content_length = strlen($content);
299
300                 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
301
302                 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
303
304                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
305
306                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
307
308                 $headers[] = 'Content-Type: application/activity+json';
309
310                 $postResult = Network::post($target, $content, $headers);
311                 $return_code = $postResult->getReturnCode();
312
313                 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
314
315                 return ($return_code >= 200) && ($return_code <= 299);
316         }
317
318         /**
319          * @brief Fetches JSON data for a user
320          *
321          * @param string $request request url
322          * @param integer $uid User id of the requester
323          *
324          * @return array JSON array
325          */
326         public static function fetch($request, $uid)
327         {
328                 $owner = User::getOwnerDataById($uid);
329
330                 if (!$owner) {
331                         return;
332                 }
333
334                 // Header data that is about to be signed.
335                 $host = parse_url($request, PHP_URL_HOST);
336                 $path = parse_url($request, PHP_URL_PATH);
337
338                 $headers = ['Host: ' . $host];
339
340                 $signed_data = "(request-target): get " . $path . "\nhost: " . $host;
341
342                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
343
344                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) host",signature="' . $signature . '"';
345
346                 $headers[] = 'Accept: application/activity+json, application/ld+json';
347
348                 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
349                 $return_code = $curlResult->getReturnCode();
350
351                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
352
353                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
354                         return false;
355                 }
356
357                 $content = json_decode($curlResult->getBody(), true);
358
359                 if (empty($content) || !is_array($content)) {
360                         return false;
361                 }
362
363                 return $content;
364         }
365
366         /**
367          * @brief Gets a signer from a given HTTP request
368          *
369          * @param $content
370          * @param $http_headers
371          *
372          * @return signer string
373          */
374         public static function getSigner($content, $http_headers)
375         {
376                 $object = json_decode($content, true);
377
378                 if (empty($object)) {
379                         return false;
380                 }
381
382                 $actor = JsonLD::fetchElement($object, 'actor', 'id');
383
384                 $headers = [];
385                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
386
387                 // First take every header
388                 foreach ($http_headers as $k => $v) {
389                         $field = str_replace('_', '-', strtolower($k));
390                         $headers[$field] = $v;
391                 }
392
393                 // Now add every http header
394                 foreach ($http_headers as $k => $v) {
395                         if (strpos($k, 'HTTP_') === 0) {
396                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
397                                 $headers[$field] = $v;
398                         }
399                 }
400
401                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
402
403                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
404                         return false;
405                 }
406
407                 $signed_data = '';
408                 foreach ($sig_block['headers'] as $h) {
409                         if (array_key_exists($h, $headers)) {
410                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
411                         }
412                 }
413                 $signed_data = rtrim($signed_data, "\n");
414
415                 if (empty($signed_data)) {
416                         return false;
417                 }
418
419                 $algorithm = null;
420
421                 if ($sig_block['algorithm'] === 'rsa-sha256') {
422                         $algorithm = 'sha256';
423                 }
424
425                 if ($sig_block['algorithm'] === 'rsa-sha512') {
426                         $algorithm = 'sha512';
427                 }
428
429                 if (empty($algorithm)) {
430                         return false;
431                 }
432
433                 $key = self::fetchKey($sig_block['keyId'], $actor);
434
435                 if (empty($key)) {
436                         return false;
437                 }
438
439                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
440                         return false;
441                 }
442
443                 // Check the digest when it is part of the signed data
444                 if (in_array('digest', $sig_block['headers'])) {
445                         $digest = explode('=', $headers['digest'], 2);
446                         if ($digest[0] === 'SHA-256') {
447                                 $hashalg = 'sha256';
448                         }
449                         if ($digest[0] === 'SHA-512') {
450                                 $hashalg = 'sha512';
451                         }
452
453                         /// @todo add all hashes from the rfc
454
455                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
456                                 return false;
457                         }
458                 }
459
460                 /// @todo Check if the signed date field is in an acceptable range
461
462                 // Check the content-length when it is part of the signed data
463                 if (in_array('content-length', $sig_block['headers'])) {
464                         if (strlen($content) != $headers['content-length']) {
465                                 return false;
466                         }
467                 }
468
469                 return $key['url'];
470         }
471
472         /**
473          * @brief fetches a key for a given id and actor
474          *
475          * @param $id
476          * @param $actor
477          *
478          * @return array with actor url and public key
479          */
480         private static function fetchKey($id, $actor)
481         {
482                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
483
484                 $profile = APContact::getByURL($url);
485                 if (!empty($profile)) {
486                         Logger::log('Taking key from id ' . $id, Logger::DEBUG);
487                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
488                 } elseif ($url != $actor) {
489                         $profile = APContact::getByURL($actor);
490                         if (!empty($profile)) {
491                                 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
492                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
493                         }
494                 }
495
496                 return false;
497         }
498 }