]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
1d2e7d9f76b6a692e15c7453397c914e012c6593
[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\Database\DBA;
11 use Friendica\Model\User;
12 use Friendica\Model\APContact;
13 use Friendica\Protocol\ActivityPub;
14
15 /**
16  * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
17  *
18  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
19  *
20  * Other parts of the code for HTTP signing are taken from the Osada project.
21  * https://framagit.org/macgirvin/osada
22  *
23  * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
24  */
25
26 class HTTPSignature
27 {
28         // See draft-cavage-http-signatures-08
29         /**
30          * @brief Verifies a magic request
31          *
32          * @param $key
33          *
34          * @return array with verification data
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('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('Got keyID ' . $sig_block['keyId']);
93
94                 if (!$key) {
95                         return $result;
96                 }
97
98                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
99
100                 logger('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          * @brief
115          *
116          * @param array   $head
117          * @param string  $prvkey
118          * @param string  $keyid (optional, default 'Key')
119          *
120          * @return array
121          */
122         public static function createSig($head, $prvkey, $keyid = 'Key')
123         {
124                 $return_headers = [];
125
126                 $alg = 'sha512';
127                 $algorithm = 'rsa-sha512';
128
129                 $x = self::sign($head, $prvkey, $alg);
130
131                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
132                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
133
134                 $sighead = 'Authorization: Signature ' . $headerval;
135
136                 if ($head) {
137                         foreach ($head as $k => $v) {
138                                 $return_headers[] = $k . ': ' . $v;
139                         }
140                 }
141
142                 $return_headers[] = $sighead;
143
144                 return $return_headers;
145         }
146
147         /**
148          * @brief
149          *
150          * @param array  $head
151          * @param string $prvkey
152          * @param string $alg (optional) default 'sha256'
153          *
154          * @return array
155          */
156         private static function sign($head, $prvkey, $alg = 'sha256')
157         {
158                 $ret = [];
159                 $headers = '';
160                 $fields  = '';
161
162                 foreach ($head as $k => $v) {
163                         $headers .= strtolower($k) . ': ' . trim($v) . "\n";
164                         if ($fields) {
165                                 $fields .= ' ';
166                         }
167                         $fields .= strtolower($k);
168                 }
169                 // strip the trailing linefeed
170                 $headers = rtrim($headers, "\n");
171
172                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
173
174                 $ret['headers']   = $fields;
175                 $ret['signature'] = $sig;
176
177                 return $ret;
178         }
179
180         /**
181          * @brief
182          *
183          * @param string $header
184          * @return array associate array with
185          *   - \e string \b keyID
186          *   - \e string \b algorithm
187          *   - \e array  \b headers
188          *   - \e string \b signature
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                 }
207
208                 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
209                         $ret['headers'] = explode(' ', $matches[1]);
210                 }
211
212                 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
213                         $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
214                 }
215
216                 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
217                         $ret['headers'] = ['date'];
218                 }
219
220                 return $ret;
221         }
222
223         /**
224          * @brief
225          *
226          * @param string $header
227          * @param string $prvkey (optional), if not set use site private key
228          *
229          * @return array|string associative array, empty string if failue
230          *   - \e string \b iv
231          *   - \e string \b key
232          *   - \e string \b alg
233          *   - \e string \b data
234          */
235         private static function decryptSigheader($header, $prvkey = null)
236         {
237                 $iv = $key = $alg = $data = null;
238
239                 if (!$prvkey) {
240                         $prvkey = Config::get('system', 'prvkey');
241                 }
242
243                 $matches = [];
244
245                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
246                         $iv = $matches[1];
247                 }
248
249                 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
250                         $key = $matches[1];
251                 }
252
253                 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
254                         $alg = $matches[1];
255                 }
256
257                 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
258                         $data = $matches[1];
259                 }
260
261                 if ($iv && $key && $alg && $data) {
262                         return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
263                 }
264
265                 return '';
266         }
267
268         /*
269          * Functions for ActivityPub
270          */
271
272         /**
273          * @brief Transmit given data to a target for a user
274          *
275          * @param array $data Data that is about to be send
276          * @param string $target The URL of the inbox
277          * @param integer $uid User id of the sender
278          *
279          * @return boolean Was the transmission successful?
280          */
281         public static function transmit($data, $target, $uid)
282         {
283                 $owner = User::getOwnerDataById($uid);
284
285                 if (!$owner) {
286                         return;
287                 }
288
289                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
290
291                 // Header data that is about to be signed.
292                 $host = parse_url($target, PHP_URL_HOST);
293                 $path = parse_url($target, PHP_URL_PATH);
294                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
295                 $content_length = strlen($content);
296
297                 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
298
299                 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
300
301                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
302
303                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
304
305                 $headers[] = 'Content-Type: application/activity+json';
306
307                 $postResult = Network::post($target, $content, $headers);
308                 $return_code = $postResult->getReturnCode();
309
310                 logger('Transmit to ' . $target . ' returned ' . $return_code);
311
312                 return ($return_code >= 200) && ($return_code <= 299);
313         }
314
315         /**
316          * @brief Gets a signer from a given HTTP request
317          *
318          * @param $content
319          * @param $http_headers
320          *
321          * @return signer string
322          */
323         public static function getSigner($content, $http_headers)
324         {
325                 $object = json_decode($content, true);
326
327                 if (empty($object)) {
328                         return false;
329                 }
330
331                 $actor = JsonLD::fetchElement($object, 'actor', 'id');
332
333                 $headers = [];
334                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
335
336                 // First take every header
337                 foreach ($http_headers as $k => $v) {
338                         $field = str_replace('_', '-', strtolower($k));
339                         $headers[$field] = $v;
340                 }
341
342                 // Now add every http header
343                 foreach ($http_headers as $k => $v) {
344                         if (strpos($k, 'HTTP_') === 0) {
345                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
346                                 $headers[$field] = $v;
347                         }
348                 }
349
350                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
351
352                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
353                         return false;
354                 }
355
356                 $signed_data = '';
357                 foreach ($sig_block['headers'] as $h) {
358                         if (array_key_exists($h, $headers)) {
359                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
360                         }
361                 }
362                 $signed_data = rtrim($signed_data, "\n");
363
364                 if (empty($signed_data)) {
365                         return false;
366                 }
367
368                 $algorithm = null;
369
370                 if ($sig_block['algorithm'] === 'rsa-sha256') {
371                         $algorithm = 'sha256';
372                 }
373
374                 if ($sig_block['algorithm'] === 'rsa-sha512') {
375                         $algorithm = 'sha512';
376                 }
377
378                 if (empty($algorithm)) {
379                         return false;
380                 }
381
382                 $key = self::fetchKey($sig_block['keyId'], $actor);
383
384                 if (empty($key)) {
385                         return false;
386                 }
387
388                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
389                         return false;
390                 }
391
392                 // Check the digest when it is part of the signed data
393                 if (in_array('digest', $sig_block['headers'])) {
394                         $digest = explode('=', $headers['digest'], 2);
395                         if ($digest[0] === 'SHA-256') {
396                                 $hashalg = 'sha256';
397                         }
398                         if ($digest[0] === 'SHA-512') {
399                                 $hashalg = 'sha512';
400                         }
401
402                         /// @todo add all hashes from the rfc
403
404                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
405                                 return false;
406                         }
407                 }
408
409                 // Check the content-length when it is part of the signed data
410                 if (in_array('content-length', $sig_block['headers'])) {
411                         if (strlen($content) != $headers['content-length']) {
412                                 return false;
413                         }
414                 }
415
416                 return $key['url'];
417         }
418
419         /**
420          * @brief fetches a key for a given id and actor
421          *
422          * @param $id
423          * @param $actor
424          *
425          * @return array with actor url and public key
426          */
427         private static function fetchKey($id, $actor)
428         {
429                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
430
431                 $profile = APContact::getByURL($url);
432                 if (!empty($profile)) {
433                         logger('Taking key from id ' . $id, LOGGER_DEBUG);
434                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
435                 } elseif ($url != $actor) {
436                         $profile = APContact::getByURL($actor);
437                         if (!empty($profile)) {
438                                 logger('Taking key from actor ' . $actor, LOGGER_DEBUG);
439                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
440                         }
441                 }
442
443                 return false;
444         }
445 }