]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Added doxygen data
[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                 Network::post($target, $content, $headers);
306                 $return_code = BaseObject::getApp()->get_curl_code();
307
308                 logger('Transmit to ' . $target . ' returned ' . $return_code);
309         }
310
311         /**
312          * @brief Gets a signer from a given HTTP request
313          *
314          * @param $content
315          * @param $http_headers
316          *
317          * @return signer string
318          */
319         public static function getSigner($content, $http_headers)
320         {
321                 $object = json_decode($content, true);
322
323                 if (empty($object)) {
324                         return false;
325                 }
326
327                 $actor = JsonLD::fetchElement($object, 'actor', 'id');
328
329                 $headers = [];
330                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
331
332                 // First take every header
333                 foreach ($http_headers as $k => $v) {
334                         $field = str_replace('_', '-', strtolower($k));
335                         $headers[$field] = $v;
336                 }
337
338                 // Now add every http header
339                 foreach ($http_headers as $k => $v) {
340                         if (strpos($k, 'HTTP_') === 0) {
341                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
342                                 $headers[$field] = $v;
343                         }
344                 }
345
346                 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
347
348                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
349                         return false;
350                 }
351
352                 $signed_data = '';
353                 foreach ($sig_block['headers'] as $h) {
354                         if (array_key_exists($h, $headers)) {
355                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
356                         }
357                 }
358                 $signed_data = rtrim($signed_data, "\n");
359
360                 if (empty($signed_data)) {
361                         return false;
362                 }
363
364                 $algorithm = null;
365
366                 if ($sig_block['algorithm'] === 'rsa-sha256') {
367                         $algorithm = 'sha256';
368                 }
369
370                 if ($sig_block['algorithm'] === 'rsa-sha512') {
371                         $algorithm = 'sha512';
372                 }
373
374                 if (empty($algorithm)) {
375                         return false;
376                 }
377
378                 $key = self::fetchKey($sig_block['keyId'], $actor);
379
380                 if (empty($key)) {
381                         return false;
382                 }
383
384                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
385                         return false;
386                 }
387
388                 // Check the digest when it is part of the signed data
389                 if (in_array('digest', $sig_block['headers'])) {
390                         $digest = explode('=', $headers['digest'], 2);
391                         if ($digest[0] === 'SHA-256') {
392                                 $hashalg = 'sha256';
393                         }
394                         if ($digest[0] === 'SHA-512') {
395                                 $hashalg = 'sha512';
396                         }
397
398                         /// @todo add all hashes from the rfc
399
400                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
401                                 return false;
402                         }
403                 }
404
405                 // Check the content-length when it is part of the signed data
406                 if (in_array('content-length', $sig_block['headers'])) {
407                         if (strlen($content) != $headers['content-length']) {
408                                 return false;
409                         }
410                 }
411
412                 return $key['url'];
413         }
414
415         /**
416          * @brief fetches a key for a given id and actor
417          *
418          * @param $id
419          * @param $actor
420          *
421          * @return array with actor url and public key
422          */
423         private static function fetchKey($id, $actor)
424         {
425                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
426
427                 $profile = APContact::getProfileByURL($url);
428                 if (!empty($profile)) {
429                         logger('Taking key from id ' . $id, LOGGER_DEBUG);
430                         return ['url' => $url, 'pubkey' => $profile['pubkey']];
431                 } elseif ($url != $actor) {
432                         $profile = APContact::getProfileByURL($actor);
433                         if (!empty($profile)) {
434                                 logger('Taking key from actor ' . $actor, LOGGER_DEBUG);
435                                 return ['url' => $actor, 'pubkey' => $profile['pubkey']];
436                         }
437                 }
438
439                 return false;
440         }
441 }