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