]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Update function calls
[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                 }
208
209                 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
210                         $ret['headers'] = explode(' ', $matches[1]);
211                 }
212
213                 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
214                         $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
215                 }
216
217                 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
218                         $ret['headers'] = ['date'];
219                 }
220
221                 return $ret;
222         }
223
224         /**
225          * @brief
226          *
227          * @param string $header
228          * @param string $prvkey (optional), if not set use site private key
229          *
230          * @return array|string associative array, empty string if failue
231          *   - \e string \b iv
232          *   - \e string \b key
233          *   - \e string \b alg
234          *   - \e string \b data
235          */
236         private static function decryptSigheader($header, $prvkey = null)
237         {
238                 $iv = $key = $alg = $data = null;
239
240                 if (!$prvkey) {
241                         $prvkey = Config::get('system', 'prvkey');
242                 }
243
244                 $matches = [];
245
246                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
247                         $iv = $matches[1];
248                 }
249
250                 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
251                         $key = $matches[1];
252                 }
253
254                 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
255                         $alg = $matches[1];
256                 }
257
258                 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
259                         $data = $matches[1];
260                 }
261
262                 if ($iv && $key && $alg && $data) {
263                         return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
264                 }
265
266                 return '';
267         }
268
269         /*
270          * Functions for ActivityPub
271          */
272
273         /**
274          * @brief Transmit given data to a target for a user
275          *
276          * @param array $data Data that is about to be send
277          * @param string $target The URL of the inbox
278          * @param integer $uid User id of the sender
279          *
280          * @return boolean Was the transmission successful?
281          */
282         public static function transmit($data, $target, $uid)
283         {
284                 $owner = User::getOwnerDataById($uid);
285
286                 if (!$owner) {
287                         return;
288                 }
289
290                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
291
292                 // Header data that is about to be signed.
293                 $host = parse_url($target, PHP_URL_HOST);
294                 $path = parse_url($target, PHP_URL_PATH);
295                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
296                 $content_length = strlen($content);
297
298                 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
299
300                 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
301
302                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
303
304                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
305
306                 $headers[] = 'Content-Type: application/activity+json';
307
308                 $postResult = Network::post($target, $content, $headers);
309                 $return_code = $postResult->getReturnCode();
310
311                 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
312
313                 return ($return_code >= 200) && ($return_code <= 299);
314         }
315
316         /**
317          * @brief Fetches JSON data for a user
318          *
319          * @param string $request request url
320          * @param integer $uid User id of the requester
321          *
322          * @return array JSON array
323          */
324         public static function fetch($request, $uid)
325         {
326                 $owner = User::getOwnerDataById($uid);
327
328                 if (!$owner) {
329                         return;
330                 }
331
332                 // Header data that is about to be signed.
333                 $host = parse_url($request, PHP_URL_HOST);
334                 $path = parse_url($request, PHP_URL_PATH);
335
336                 $headers = ['Host: ' . $host];
337
338                 $signed_data = "(request-target): get " . $path . "\nhost: " . $host;
339
340                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
341
342                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) host",signature="' . $signature . '"';
343
344                 $headers[] = 'Accept: application/activity+json, application/ld+json';
345
346                 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
347                 $return_code = $curlResult->getReturnCode();
348
349                 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
350
351                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
352                         return false;
353                 }
354
355                 $content = json_decode($curlResult->getBody(), true);
356
357                 if (empty($content) || !is_array($content)) {
358                         return false;
359                 }
360
361                 return $content;
362         }
363
364         /**
365          * @brief Gets a signer from a given HTTP request
366          *
367          * @param $content
368          * @param $http_headers
369          *
370          * @return signer string
371          */
372         public static function getSigner($content, $http_headers)
373         {
374                 $object = json_decode($content, true);
375
376                 if (empty($object)) {
377                         return false;
378                 }
379
380                 $actor = JsonLD::fetchElement($object, 'actor', 'id');
381
382                 $headers = [];
383                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
384
385                 // First take every header
386                 foreach ($http_headers as $k => $v) {
387                         $field = str_replace('_', '-', strtolower($k));
388                         $headers[$field] = $v;
389                 }
390
391                 // Now add every http header
392                 foreach ($http_headers as $k => $v) {
393                         if (strpos($k, 'HTTP_') === 0) {
394                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
395                                 $headers[$field] = $v;
396                         }
397                 }
398
399                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
400
401                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
402                         return false;
403                 }
404
405                 $signed_data = '';
406                 foreach ($sig_block['headers'] as $h) {
407                         if (array_key_exists($h, $headers)) {
408                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
409                         }
410                 }
411                 $signed_data = rtrim($signed_data, "\n");
412
413                 if (empty($signed_data)) {
414                         return false;
415                 }
416
417                 $algorithm = null;
418
419                 if ($sig_block['algorithm'] === 'rsa-sha256') {
420                         $algorithm = 'sha256';
421                 }
422
423                 if ($sig_block['algorithm'] === 'rsa-sha512') {
424                         $algorithm = 'sha512';
425                 }
426
427                 if (empty($algorithm)) {
428                         return false;
429                 }
430
431                 $key = self::fetchKey($sig_block['keyId'], $actor);
432
433                 if (empty($key)) {
434                         return false;
435                 }
436
437                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
438                         return false;
439                 }
440
441                 // Check the digest when it is part of the signed data
442                 if (in_array('digest', $sig_block['headers'])) {
443                         $digest = explode('=', $headers['digest'], 2);
444                         if ($digest[0] === 'SHA-256') {
445                                 $hashalg = 'sha256';
446                         }
447                         if ($digest[0] === 'SHA-512') {
448                                 $hashalg = 'sha512';
449                         }
450
451                         /// @todo add all hashes from the rfc
452
453                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
454                                 return false;
455                         }
456                 }
457
458                 /// @todo Check if the signed date field is in an acceptable range
459
460                 // Check the content-length when it is part of the signed data
461                 if (in_array('content-length', $sig_block['headers'])) {
462                         if (strlen($content) != $headers['content-length']) {
463                                 return false;
464                         }
465                 }
466
467                 return $key['url'];
468         }
469
470         /**
471          * @brief fetches a key for a given id and actor
472          *
473          * @param $id
474          * @param $actor
475          *
476          * @return array with actor url and public key
477          */
478         private static function fetchKey($id, $actor)
479         {
480                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
481
482                 $profile = APContact::getByURL($url);
483                 if (!empty($profile)) {
484                         Logger::log('Taking key from id ' . $id, Logger::DEBUG);
485                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
486                 } elseif ($url != $actor) {
487                         $profile = APContact::getByURL($actor);
488                         if (!empty($profile)) {
489                                 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
490                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
491                         }
492                 }
493
494                 return false;
495         }
496 }