]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Improved parsing of AP profiles
[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 $data
276          * @param $target
277          * @param $uid
278          */
279         public static function transmit($data, $target, $uid)
280         {
281                 $owner = User::getOwnerDataById($uid);
282
283                 if (!$owner) {
284                         return;
285                 }
286
287                 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
288
289                 // Header data that is about to be signed.
290                 $host = parse_url($target, PHP_URL_HOST);
291                 $path = parse_url($target, PHP_URL_PATH);
292                 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
293                 $content_length = strlen($content);
294
295                 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
296
297                 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
298
299                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
300
301                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
302
303                 $headers[] = 'Content-Type: application/activity+json';
304
305                 $postResult = Network::post($target, $content, $headers);
306
307                 logger('Transmit to ' . $target . ' returned ' . $postResult->getReturnCode());
308         }
309
310         /**
311          * @brief Gets a signer from a given HTTP request
312          *
313          * @param $content
314          * @param $http_headers
315          *
316          * @return signer string
317          */
318         public static function getSigner($content, $http_headers)
319         {
320                 $object = json_decode($content, true);
321
322                 if (empty($object)) {
323                         return false;
324                 }
325
326                 $actor = JsonLD::fetchElement($object, 'actor', 'id');
327
328                 $headers = [];
329                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
330
331                 // First take every header
332                 foreach ($http_headers as $k => $v) {
333                         $field = str_replace('_', '-', strtolower($k));
334                         $headers[$field] = $v;
335                 }
336
337                 // Now add every http header
338                 foreach ($http_headers as $k => $v) {
339                         if (strpos($k, 'HTTP_') === 0) {
340                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
341                                 $headers[$field] = $v;
342                         }
343                 }
344
345                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
346
347                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
348                         return false;
349                 }
350
351                 $signed_data = '';
352                 foreach ($sig_block['headers'] as $h) {
353                         if (array_key_exists($h, $headers)) {
354                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
355                         }
356                 }
357                 $signed_data = rtrim($signed_data, "\n");
358
359                 if (empty($signed_data)) {
360                         return false;
361                 }
362
363                 $algorithm = null;
364
365                 if ($sig_block['algorithm'] === 'rsa-sha256') {
366                         $algorithm = 'sha256';
367                 }
368
369                 if ($sig_block['algorithm'] === 'rsa-sha512') {
370                         $algorithm = 'sha512';
371                 }
372
373                 if (empty($algorithm)) {
374                         return false;
375                 }
376
377                 $key = self::fetchKey($sig_block['keyId'], $actor);
378
379                 if (empty($key)) {
380                         return false;
381                 }
382
383                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
384                         return false;
385                 }
386
387                 // Check the digest when it is part of the signed data
388                 if (in_array('digest', $sig_block['headers'])) {
389                         $digest = explode('=', $headers['digest'], 2);
390                         if ($digest[0] === 'SHA-256') {
391                                 $hashalg = 'sha256';
392                         }
393                         if ($digest[0] === 'SHA-512') {
394                                 $hashalg = 'sha512';
395                         }
396
397                         /// @todo add all hashes from the rfc
398
399                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
400                                 return false;
401                         }
402                 }
403
404                 // Check the content-length when it is part of the signed data
405                 if (in_array('content-length', $sig_block['headers'])) {
406                         if (strlen($content) != $headers['content-length']) {
407                                 return false;
408                         }
409                 }
410
411                 return $key['url'];
412         }
413
414         /**
415          * @brief fetches a key for a given id and actor
416          *
417          * @param $id
418          * @param $actor
419          *
420          * @return array with actor url and public key
421          */
422         private static function fetchKey($id, $actor)
423         {
424                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
425
426                 $profile = APContact::getByURL($url);
427                 if (!empty($profile)) {
428                         logger('Taking key from id ' . $id, LOGGER_DEBUG);
429                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
430                 } elseif ($url != $actor) {
431                         $profile = APContact::getByURL($actor);
432                         if (!empty($profile)) {
433                                 logger('Taking key from actor ' . $actor, LOGGER_DEBUG);
434                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
435                         }
436                 }
437
438                 return false;
439         }
440 }