]> git.mxchange.org Git - friendica.git/blob - src/Util/HTTPSignature.php
Rename DBM method calls to DBA method calls
[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                 // We don't use Activity Pub at the moment.
129 //              if (!$key) {
130 //                      $result['signer'] = $sig_block['keyId'];
131 //                      $key = self::getActivitypubKey($sig_block['keyId']);
132 //              }
133
134                 if (!$key) {
135                         return $result;
136                 }
137
138                 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
139
140                 logger('verified: ' . $x, LOGGER_DEBUG);
141
142                 if (!$x) {
143                         return $result;
144                 }
145
146                 if (!$spoofable) {
147                         $result['header_valid'] = true;
148                 }
149
150                 if (in_array('digest', $signed_headers)) {
151                         $result['content_signed'] = true;
152                         $digest = explode('=', $headers['digest']);
153
154                         if ($digest[0] === 'SHA-256') {
155                                 $hashalg = 'sha256';
156                         }
157                         if ($digest[0] === 'SHA-512') {
158                                 $hashalg = 'sha512';
159                         }
160
161                         // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
162                         if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
163                                 $result['content_valid'] = true;
164                         }
165                 }
166
167                 logger('Content_Valid: ' . $result['content_valid']);
168
169                 return $result;
170         }
171
172         /**
173          * Fetch the public key for Activity Pub contact.
174          *
175          * @param string|int The identifier (contact addr or contact ID).
176          * @return string|boolean The public key or false on failure.
177          */
178         private static function getActivitypubKey($id)
179         {
180                 if (strpos($id, 'acct:') === 0) {
181                         $contact = DBA::selectFirst('contact', ['pubkey'], ['uid' => 0, 'addr' => str_replace('acct:', '', $id)]);
182                 } else {
183                         $contact = DBA::selectFirst('contact', ['pubkey'], ['id' => $id, 'network' => 'activitypub']);
184                 }
185
186                 if (DBA::is_result($contact)) {
187                         return $contact['pubkey'];
188                 }
189
190                 if(function_exists('as_fetch')) {
191                         $r = as_fetch($id);
192                 }
193
194                 if ($r) {
195                         $j = json_decode($r, true);
196
197                         if (array_key_exists('publicKey', $j) && array_key_exists('publicKeyPem', $j['publicKey'])) {
198                                 if ((array_key_exists('id', $j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id) {
199                                         return false;
200                                 }
201
202                                 return $j['publicKey']['publicKeyPem'];
203                         }
204                 }
205
206                 return false;
207         }
208
209         /**
210          * @brief
211          *
212          * @param string  $request
213          * @param array   $head
214          * @param string  $prvkey
215          * @param string  $keyid (optional, default 'Key')
216          * @param boolean $send_headers (optional, default false)
217          *   If set send a HTTP header
218          * @param boolean $auth (optional, default false)
219          * @param string  $alg (optional, default 'sha256')
220          * @param string  $crypt_key (optional, default null)
221          * @param string  $crypt_algo (optional, default 'aes256ctr')
222          *
223          * @return array
224          */
225         public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
226         {
227                 $return_headers = [];
228
229                 if ($alg === 'sha256') {
230                         $algorithm = 'rsa-sha256';
231                 }
232
233                 if ($alg === 'sha512') {
234                         $algorithm = 'rsa-sha512';
235                 }
236
237                 $x = self::sign($request, $head, $prvkey, $alg);
238
239                 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
240                         . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
241
242                 if ($crypt_key) {
243                         $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
244                         $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
245                 }
246
247                 if ($auth) {
248                         $sighead = 'Authorization: Signature ' . $headerval;
249                 } else {
250                         $sighead = 'Signature: ' . $headerval;
251                 }
252
253                 if ($head) {
254                         foreach ($head as $k => $v) {
255                                 if ($send_headers) {
256                                         // This is for ActivityPub implementation.
257                                         // Since the Activity Pub implementation isn't
258                                         // ready at the moment, we comment it out.
259                                         // header($k . ': ' . $v);
260                                 } else {
261                                         $return_headers[] = $k . ': ' . $v;
262                                 }
263                         }
264                 }
265
266                 if ($send_headers) {
267                         // This is for ActivityPub implementation.
268                         // Since the Activity Pub implementation isn't
269                         // ready at the moment, we comment it out.
270                         // header($sighead);
271                 } else {
272                         $return_headers[] = $sighead;
273                 }
274
275                 return $return_headers;
276         }
277
278         /**
279          * @brief
280          *
281          * @param string $request
282          * @param array  $head
283          * @param string $prvkey
284          * @param string $alg (optional) default 'sha256'
285          *
286          * @return array
287          */
288         private static function sign($request, $head, $prvkey, $alg = 'sha256')
289         {
290                 $ret = [];
291                 $headers = '';
292                 $fields  = '';
293
294                 if ($request) {
295                         $headers = '(request-target)' . ': ' . trim($request) . "\n";
296                         $fields = '(request-target)';
297                 }
298
299                 if ($head) {
300                         foreach ($head as $k => $v) {
301                                 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
302                                 if ($fields) {
303                                         $fields .= ' ';
304                                 }
305                                 $fields .= strtolower($k);
306                         }
307                         // strip the trailing linefeed
308                         $headers = rtrim($headers, "\n");
309                 }
310
311                 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
312
313                 $ret['headers']   = $fields;
314                 $ret['signature'] = $sig;
315
316                 return $ret;
317         }
318
319         /**
320          * @brief
321          *
322          * @param string $header
323          * @return array associate array with
324          *   - \e string \b keyID
325          *   - \e string \b algorithm
326          *   - \e array  \b headers
327          *   - \e string \b signature
328          */
329         public static function parseSigheader($header)
330         {
331                 $ret = [];
332                 $matches = [];
333
334                 // if the header is encrypted, decrypt with (default) site private key and continue
335                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
336                         $header = self::decryptSigheader($header);
337                 }
338
339                 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
340                         $ret['keyId'] = $matches[1];
341                 }
342
343                 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
344                         $ret['algorithm'] = $matches[1];
345                 }
346
347                 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
348                         $ret['headers'] = explode(' ', $matches[1]);
349                 }
350
351                 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
352                         $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
353                 }
354
355                 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
356                         $ret['headers'] = ['date'];
357                 }
358
359                 return $ret;
360         }
361
362         /**
363          * @brief
364          *
365          * @param string $header
366          * @param string $prvkey (optional), if not set use site private key
367          *
368          * @return array|string associative array, empty string if failue
369          *   - \e string \b iv
370          *   - \e string \b key
371          *   - \e string \b alg
372          *   - \e string \b data
373          */
374         private static function decryptSigheader($header, $prvkey = null)
375         {
376                 $iv = $key = $alg = $data = null;
377
378                 if (!$prvkey) {
379                         $prvkey = Config::get('system', 'prvkey');
380                 }
381
382                 $matches = [];
383
384                 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
385                         $iv = $matches[1];
386                 }
387
388                 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
389                         $key = $matches[1];
390                 }
391
392                 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
393                         $alg = $matches[1];
394                 }
395
396                 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
397                         $data = $matches[1];
398                 }
399
400                 if ($iv && $key && $alg && $data) {
401                         return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
402                 }
403
404                 return '';
405         }
406 }