]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Merge pull request #5253 from rabuzarus/20180616_-_magic_auth_test_2
[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\Core\Config;
9 use Friendica\Database\DBM;
10 use Friendica\Util\Crypto;
11 use Friendica\Util\HTTPHeaders;
12 use dba;
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  * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
20  */
21
22 class HTTPSignature
23 {
24         /**
25          * @brief RFC5843
26          *
27          * Disabled until Friendica's ActivityPub implementation
28          * is ready.
29          * 
30          * @see https://tools.ietf.org/html/rfc5843
31          *
32          * @param string  $body The value to create the digest for
33          * @param boolean $set  (optional, default true)
34          *   If set send a Digest HTTP header
35          * 
36          * @return string The generated digest of $body
37          */
38 //      public static function generateDigest($body, $set = true)
39 //      {
40 //              $digest = base64_encode(hash('sha256', $body, true));
41 //
42 //              if($set) {
43 //                      header('Digest: SHA-256=' . $digest);
44 //              }
45 //              return $digest;
46 //      }
47
48         // See draft-cavage-http-signatures-08
49         public static function verify($data, $key = '')
50         {
51                 $body      = $data;
52                 $headers   = null;
53                 $spoofable = false;
54                 $result = [
55                         'signer'         => '',
56                         'header_signed'  => false,
57                         'header_valid'   => false,
58                         'content_signed' => false,
59                         'content_valid'  => false
60                 ];
61
62                 // Decide if $data arrived via controller submission or curl.
63                 if (is_array($data) && $data['header']) {
64                         if (!$data['success']) {
65                                 return $result;
66                         }
67
68                         $h = new HTTPHeaders($data['header']);
69                         $headers = $h->fetch();
70                         $body = $data['body'];
71                 } else {
72                         $headers = [];
73                         $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
74
75                         foreach ($_SERVER as $k => $v) {
76                                 if (strpos($k, 'HTTP_') === 0) {
77                                         $field = str_replace('_', '-', strtolower(substr($k, 5)));
78                                         $headers[$field] = $v;
79                                 }
80                         }
81                 }
82
83                 $sig_block = null;
84
85                 if (array_key_exists('signature', $headers)) {
86                         $sig_block = self::parseSigheader($headers['signature']);
87                 } elseif (array_key_exists('authorization', $headers)) {
88                         $sig_block = self::parseSigheader($headers['authorization']);
89                 }
90
91                 if (!$sig_block) {
92                         logger('no signature provided.');
93                         return $result;
94                 }
95
96                 // Warning: This log statement includes binary data
97                 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
98
99                 $result['header_signed'] = true;
100
101                 $signed_headers = $sig_block['headers'];
102                 if (!$signed_headers) {
103                         $signed_headers = ['date'];
104                 }
105
106                 $signed_data = '';
107                 foreach ($signed_headers as $h) {
108                         if (array_key_exists($h, $headers)) {
109                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
110                         }
111                         if (strpos($h, '.')) {
112                                 $spoofable = true;
113                         }
114                 }
115
116                 $signed_data = rtrim($signed_data, "\n");
117
118                 $algorithm = null;
119                 if ($sig_block['algorithm'] === 'rsa-sha256') {
120                         $algorithm = 'sha256';
121                 }
122                 if ($sig_block['algorithm'] === 'rsa-sha512') {
123                         $algorithm = 'sha512';
124                 }
125
126                 if ($key && function_exists($key)) {
127                         $result['signer'] = $sig_block['keyId'];
128                         $key = $key($sig_block['keyId']);
129                 }
130
131                 // We don't use Activity Pub at the moment.
132 //              if (!$key) {
133 //                      $result['signer'] = $sig_block['keyId'];
134 //                      $key = self::getActivitypubKey($sig_block['keyId']);
135 //              }
136
137                 if (!$key) {
138                         return $result;
139                 }
140
141                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
142
143                 logger('verified: ' . $x, LOGGER_DEBUG);
144
145                 if (!$x) {
146                         return $result;
147                 }
148
149                 if (!$spoofable) {
150                         $result['header_valid'] = true;
151                 }
152
153                 if (in_array('digest', $signed_headers)) {
154                         $result['content_signed'] = true;
155                         $digest = explode('=', $headers['digest']);
156
157                         if ($digest[0] === 'SHA-256') {
158                                 $hashalg = 'sha256';
159                         }
160                         if ($digest[0] === 'SHA-512') {
161                                 $hashalg = 'sha512';
162                         }
163
164                         // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
165                         if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
166                                 $result['content_valid'] = true;
167                         }
168                 }
169
170                 logger('Content_Valid: ' . $result['content_valid']);
171
172                 return $result;
173         }
174
175         /**
176          * Fetch the public key for Activity Pub contact.
177          * 
178          * @param string|int The identifier (contact addr or contact ID).
179          * @return string|boolean The public key or false on failure.
180          */
181         private static function getActivitypubKey($id)
182         {
183                 if (strpos($id, 'acct:') === 0) {
184                         $contact = dba::selectFirst('contact', ['pubkey'], ['uid' => 0, 'addr' => str_replace('acct:', '', $id)]);
185                 } else {
186                         $contact = dba::selectFirst('contact', ['pubkey'], ['id' => $id, 'network' => 'activitypub']);
187                 }
188
189                 if (DBM::is_result($contact)) {
190                         return $contact['pubkey'];
191                 }
192
193                 if(function_exists('as_fetch')) {
194                         $r = as_fetch($id);
195                 }
196
197                 if ($r) {
198                         $j = json_decode($r, true);
199
200                         if (array_key_exists('publicKey', $j) && array_key_exists('publicKeyPem', $j['publicKey'])) {
201                                 if ((array_key_exists('id', $j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id) {
202                                         return false;
203                                 }
204
205                                 return $j['publicKey']['publicKeyPem'];
206                         }
207                 }
208
209                 return false;
210         }
211
212         /**
213          * @brief
214          *
215          * @param string  $request
216          * @param array   $head
217          * @param string  $prvkey
218          * @param string  $keyid (optional, default 'Key')
219          * @param boolean $send_headers (optional, default false)
220          *   If set send a HTTP header
221          * @param boolean $auth (optional, default false)
222          * @param string  $alg (optional, default 'sha256')
223          * @param string  $crypt_key (optional, default null)
224          * @param string  $crypt_algo (optional, default 'aes256ctr')
225          * 
226          * @return array
227          */
228         public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
229         {
230                 $return_headers = [];
231
232                 if ($alg === 'sha256') {
233                         $algorithm = 'rsa-sha256';
234                 }
235
236                 if ($alg === 'sha512') {
237                         $algorithm = 'rsa-sha512';
238                 }
239
240                 $x = self::sign($request, $head, $prvkey, $alg);
241
242                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
243                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
244
245                 if ($crypt_key) {
246                         $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
247                         $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
248                 }
249
250                 if ($auth) {
251                         $sighead = 'Authorization: Signature ' . $headerval;
252                 } else {
253                         $sighead = 'Signature: ' . $headerval;
254                 }
255
256                 if ($head) {
257                         foreach ($head as $k => $v) {
258                                 if ($send_headers) {
259                                         // This is for ActivityPub implementation.
260                                         // Since the Activity Pub implementation isn't
261                                         // ready at the moment, we comment it out.
262                                         // header($k . ': ' . $v);
263                                 } else {
264                                         $return_headers[] = $k . ': ' . $v;
265                                 }
266                         }
267                 }
268
269                 if ($send_headers) {
270                         // This is for ActivityPub implementation.
271                         // Since the Activity Pub implementation isn't
272                         // ready at the moment, we comment it out.
273                         // header($sighead);
274                 } else {
275                         $return_headers[] = $sighead;
276                 }
277
278                 return $return_headers;
279         }
280
281         /**
282          * @brief
283          *
284          * @param string $request
285          * @param array  $head
286          * @param string $prvkey
287          * @param string $alg (optional) default 'sha256'
288          * 
289          * @return array
290          */
291         private static function sign($request, $head, $prvkey, $alg = 'sha256')
292         {
293                 $ret = [];
294                 $headers = '';
295                 $fields  = '';
296
297                 if ($request) {
298                         $headers = '(request-target)' . ': ' . trim($request) . "\n";
299                         $fields = '(request-target)';
300                 }
301
302                 if ($head) {
303                         foreach ($head as $k => $v) {
304                                 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
305                                 if ($fields) {
306                                         $fields .= ' ';
307                                 }
308                                 $fields .= strtolower($k);
309                         }
310                         // strip the trailing linefeed
311                         $headers = rtrim($headers, "\n");
312                 }
313
314                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
315
316                 $ret['headers']   = $fields;
317                 $ret['signature'] = $sig;
318         
319                 return $ret;
320         }
321
322         /**
323          * @brief
324          *
325          * @param string $header
326          * @return array associate array with
327          *   - \e string \b keyID
328          *   - \e string \b algorithm
329          *   - \e array  \b headers
330          *   - \e string \b signature
331          */
332         public static function parseSigheader($header)
333         {
334                 $ret = [];
335                 $matches = [];
336
337                 // if the header is encrypted, decrypt with (default) site private key and continue
338                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
339                         $header = self::decryptSigheader($header);
340                 }
341
342                 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
343                         $ret['keyId'] = $matches[1];
344                 }
345
346                 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
347                         $ret['algorithm'] = $matches[1];
348                 }
349
350                 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
351                         $ret['headers'] = explode(' ', $matches[1]);
352                 }
353
354                 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
355                         $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
356                 }
357
358                 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
359                         $ret['headers'] = ['date'];
360                 }
361
362                 return $ret;
363         }
364
365         /**
366          * @brief
367          *
368          * @param string $header
369          * @param string $prvkey (optional), if not set use site private key
370          * 
371          * @return array|string associative array, empty string if failue
372          *   - \e string \b iv
373          *   - \e string \b key
374          *   - \e string \b alg
375          *   - \e string \b data
376          */
377         private static function decryptSigheader($header, $prvkey = null)
378         {
379                 $iv = $key = $alg = $data = null;
380
381                 if (!$prvkey) {
382                         $prvkey = Config::get('system', 'prvkey');
383                 }
384
385                 $matches = [];
386
387                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
388                         $iv = $matches[1];
389                 }
390
391                 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
392                         $key = $matches[1];
393                 }
394
395                 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
396                         $alg = $matches[1];
397                 }
398
399                 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
400                         $data = $matches[1];
401                 }
402
403                 if ($iv && $key && $alg && $data) {
404                         return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
405                 }
406
407                 return '';
408         }
409 }