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