aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Web/HTTPSig.php
blob: fe0b9428ff0d26a7cfaaed221bbf82618bf55ae7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
<?php

namespace Zotlabs\Web;

/**
 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
 *
 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
 */
class HTTPSig {

	/**
	 * @brief RFC5843
	 *
	 * @see https://tools.ietf.org/html/rfc5843
	 *
	 * @param string $body The value to create the digest for
	 * @param boolean $set (optional, default true)
	 *   If set send a Digest HTTP header
	 * @return string The generated digest of $body
	 */
	static function generate_digest($body, $set = true) {
		$digest = base64_encode(hash('sha256', $body, true));

		if($set) {
			header('Digest: SHA-256=' . $digest);
		}
		return $digest;
	}

	// See draft-cavage-http-signatures-08

	static function verify($data,$key = '') {

		$body      = $data;
		$headers   = null;
		$spoofable = false;

		$result = [
			'signer'         => '',
			'header_signed'  => false,
			'header_valid'   => false,
			'content_signed' => false,
			'content_valid'  => false
		];

		// decide if $data arrived via controller submission or curl
		if(is_array($data) && $data['header']) {
			if(! $data['success'])
				return $result;

			$h = new \Zotlabs\Web\HTTPHeaders($data['header']);
			$headers = $h->fetcharr();
			$body = $data['body'];
			$headers['(request-target)'] = $data['request_target'];
		}

		else {
			$headers = [];
			$headers['(request-target)'] =
				strtolower($_SERVER['REQUEST_METHOD']) . ' ' .
				$_SERVER['REQUEST_URI'];
			$headers['content-type'] = $_SERVER['CONTENT_TYPE'];
			$headers['content-length'] = $_SERVER['CONTENT_LENGTH'];

			foreach($_SERVER as $k => $v) {
				if(strpos($k,'HTTP_') === 0) {
					$field = str_replace('_','-',strtolower(substr($k,5)));
					$headers[$field] = $v;
				}
			}
		}

		// logger('SERVER: ' . print_r($_SERVER,true), LOGGER_ALL);

		// logger('headers: ' . print_r($headers,true), LOGGER_ALL);

		$sig_block = null;

		if(array_key_exists('signature',$headers)) {
			$sig_block = self::parse_sigheader($headers['signature']);
		}
		elseif(array_key_exists('authorization',$headers)) {
			$sig_block = self::parse_sigheader($headers['authorization']);
		}

		if(! $sig_block) {
			logger('no signature provided.');
			return $result;
		}

		// Warning: This log statement includes binary data
		// logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);

		$result['header_signed'] = true;

		$signed_headers = $sig_block['headers'];
		if(! $signed_headers)
			$signed_headers = [ 'date' ];

		$signed_data = '';
		foreach($signed_headers as $h) {
			if(array_key_exists($h,$headers)) {
				$signed_data .= $h . ': ' . $headers[$h] . "\n";
			}
			if(strpos($h,'.')) {
				$spoofable = true;
			}
			if($h === 'date') {
				$d = new \DateTime($headers[$h]);
				$d->setTimeZone(new \DateTimeZone('UTC'));
				$dplus = datetime_convert('UTC','UTC','now + 1 day');
				$dminus = datetime_convert('UTC','UTC','now - 1 day');
				$c = $d->format('Y-m-d H:i:s');
				if($c > $dplus || $c < $dminus) {
					logger('bad time: ' . $c);
					return $result;
				}
			}
		}
		$signed_data = rtrim($signed_data,"\n");

		$algorithm = null;
		if($sig_block['algorithm'] === 'rsa-sha256') {
			$algorithm = 'sha256';
		}
		if($sig_block['algorithm'] === 'rsa-sha512') {
			$algorithm = 'sha512';
		}

		if($key && function_exists($key)) {
			$result['signer'] = $sig_block['keyId'];
			$key = $key($sig_block['keyId']);
		}

		if(! $key) {
			$result['signer'] = $sig_block['keyId'];
			$key = self::get_activitypub_key($sig_block['keyId']);
		}

		if(! $key)
			return $result;

		$x = rsa_verify($signed_data,$sig_block['signature'],$key,$algorithm);

		logger('verified: ' . $x, LOGGER_DEBUG);

		if(! $x)
			return $result;

		if(! $spoofable)
			$result['header_valid'] = true;

		if(in_array('digest',$signed_headers)) {
			$result['content_signed'] = true;
			$digest = explode('=', $headers['digest']);
			if($digest[0] === 'SHA-256')
				$hashalg = 'sha256';
			if($digest[0] === 'SHA-512')
				$hashalg = 'sha512';

			// The explode operation will have stripped the '=' padding, so compare against unpadded base64
			if(rtrim(base64_encode(hash($hashalg,$body,true)),'=') === $digest[1]) {
				$result['content_valid'] = true;
			}
		}


		if(in_array('x-zot-digest',$signed_headers)) {
			$result['content_signed'] = true;
			$digest = explode('=', $headers['x-zot-digest']);
			if($digest[0] === 'SHA-256')
				$hashalg = 'sha256';
			if($digest[0] === 'SHA-512')
				$hashalg = 'sha512';

			// The explode operation will have stripped the '=' padding, so compare against unpadded base64
			if(rtrim(base64_encode(hash($hashalg,$_POST['data'],true)),'=') === $digest[1]) {
				$result['content_valid'] = true;
			}
		}

		logger('Content_Valid: ' . (($result['content_valid']) ? 'true' : 'false'));

		return $result;
	}

	/**
	 * @brief
	 *
	 * @param string $id
	 * @return boolean|string
	 *   false if no pub key found, otherwise return the pub key
	 */
	function get_activitypub_key($id) {

		if(strpos($id,'acct:') === 0) {
			$x = q("select xchan_pubkey from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' limit 1",
				dbesc(str_replace('acct:','',$id))
			);
		}
		else {
			$x = q("select xchan_pubkey from xchan where xchan_hash = '%s' and xchan_network = 'activitypub' ",
				dbesc($id)
			);
		}

		if($x && $x[0]['xchan_pubkey']) {
			return ($x[0]['xchan_pubkey']);
		}

		if(function_exists('as_fetch'))
			$r = as_fetch($id);

		if($r) {
			$j = json_decode($r,true);

			if(array_key_exists('publicKey',$j) && array_key_exists('publicKeyPem',$j['publicKey'])) {
				if((array_key_exists('id',$j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id)
					return false;

				return($j['publicKey']['publicKeyPem']);
			}
		}

		return false;
	}

	/**
	 * @brief
	 *
	 * @param string $request
	 * @param array $head
	 * @param string $prvkey
	 * @param string $keyid (optional, default 'Key')
	 * @param boolean $send_headers (optional, default false)
	 *   If set send a HTTP header
	 * @param boolean $auth (optional, default false)
	 * @param string $alg (optional, default 'sha256')
	 * @param string $crypt_key (optional, default null)
	 * @param string $crypt_algo (optional, default 'aes256ctr')
	 * @return array
	 */
	static function create_sig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false,
			$alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr') {

		$return_headers = [];

		if($alg === 'sha256') {
			$algorithm = 'rsa-sha256';
		}
		if($alg === 'sha512') {
			$algorithm = 'rsa-sha512';
		}

		$x = self::sign($request,$head,$prvkey,$alg);

		$headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
			. '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';

		if($crypt_key) {
			$x = crypto_encapsulate($headerval,$crypt_key,$crypt_algo);
			$headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
		}

		if($auth) {
			$sighead = 'Authorization: Signature ' . $headerval;
		}
		else {
			$sighead = 'Signature: ' . $headerval;
		}

		if($head) {
			foreach($head as $k => $v) {
				if($send_headers) {
					header($k . ': ' . $v);
				}
				else {
					$return_headers[] = $k . ': ' . $v;
				}
			}
		}
		if($send_headers) {
			header($sighead);
		}
		else {
			$return_headers[] = $sighead;
		}

		return $return_headers;
	}

	/**
	 * @brief
	 *
	 * @param string $request
	 * @param array  $head
	 * @param string $prvkey
	 * @param string $alg (optional) default 'sha256'
	 * @return array
	 */
	static function sign($request, $head, $prvkey, $alg = 'sha256') {

		$ret = [];

		$headers = '';
		$fields  = '';
		if($request) {
			$headers = '(request-target)' . ': ' . trim($request) . "\n";
			$fields = '(request-target)';
		}

		if($head) {
			foreach($head as $k => $v) {
				$headers .= strtolower($k) . ': ' . trim($v) . "\n";
				if($fields)
					$fields .= ' ';

				$fields .= strtolower($k);
			}
			// strip the trailing linefeed
			$headers = rtrim($headers,"\n");
		}

		$sig = base64_encode(rsa_sign($headers,$prvkey,$alg));

		$ret['headers']   = $fields;
		$ret['signature'] = $sig;

		return $ret;
	}

	/**
	 * @brief
	 *
	 * @param string $header
	 * @return array associate array with
	 *   - \e string \b keyID
	 *   - \e string \b algorithm
	 *   - \e array  \b headers
	 *   - \e string \b signature
	 */
	static function parse_sigheader($header) {

		if(is_array($header)) {
			btlogger('is_array: ' . print_r($header,true));
		}

		$ret = [];
		$matches = [];

		// if the header is encrypted, decrypt with (default) site private key and continue

		if(preg_match('/iv="(.*?)"/ism',$header,$matches))
			$header = self::decrypt_sigheader($header);

		if(preg_match('/keyId="(.*?)"/ism',$header,$matches))
			$ret['keyId'] = $matches[1];
		if(preg_match('/algorithm="(.*?)"/ism',$header,$matches))
			$ret['algorithm'] = $matches[1];
		if(preg_match('/headers="(.*?)"/ism',$header,$matches))
			$ret['headers'] = explode(' ', $matches[1]);
		if(preg_match('/signature="(.*?)"/ism',$header,$matches))
			$ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));

		if(($ret['signature']) && ($ret['algorithm']) && (! $ret['headers']))
			$ret['headers'] = [ 'date' ];

 		return $ret;
	}


	/**
	 * @brief
	 *
	 * @param string $header
	 * @param string $prvkey (optional), if not set use site private key
	 * @return array|string associative array, empty string if failue
	 *   - \e string \b iv
	 *   - \e string \b key
	 *   - \e string \b alg
	 *   - \e string \b data
	 */
	static function decrypt_sigheader($header, $prvkey = null) {

		$iv = $key = $alg = $data = null;

		if(! $prvkey) {
			$prvkey = get_config('system', 'prvkey');
		}

		$matches = [];

		if(preg_match('/iv="(.*?)"/ism',$header,$matches))
			$iv = $matches[1];
		if(preg_match('/key="(.*?)"/ism',$header,$matches))
			$key = $matches[1];
		if(preg_match('/alg="(.*?)"/ism',$header,$matches))
			$alg = $matches[1];
		if(preg_match('/data="(.*?)"/ism',$header,$matches))
			$data = $matches[1];

		if($iv && $key && $alg && $data) {
			return crypto_unencapsulate([ 'encrypted' => true, 'iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data ] , $prvkey);
		}

		return '';
	}

}