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