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