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