aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Web/HTTPSig.php
blob: 792556a10d8b78f3a25776a54578ebc20ac5ff5d (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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
<?php

namespace Zotlabs\Web;

use Zotlabs\Lib\ActivityStreams;
use Zotlabs\Lib\Webfinger;
use Zotlabs\Web\HTTPHeaders;
use Zotlabs\Lib\Libzot;

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

class HTTPSig {

	/**
	 * @brief RFC5843
	 *
	 * @see https://tools.ietf.org/html/rfc5843
	 *
	 * @param string $body The value to create the digest for
	 * @param string $alg hash algorithm (one of 'sha256','sha512')
	 * @return string The generated digest header string for $body
	 */

	static function generate_digest_header($body,$alg = 'sha256') {

		$digest = base64_encode(hash($alg, $body, true));
		switch($alg) {
			case 'sha512':
				return 'SHA-512=' . $digest;
			case 'sha256':
			default:
				return 'SHA-256=' . $digest;
				break;
		}
	}

	static function find_headers($data,&$body) {

		// decide if $data arrived via controller submission or curl

		if(is_array($data) && $data['header']) {
			if(! $data['success'])
				return [];

			$h = new 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);

		return $headers;
	}


	// See draft-cavage-http-signatures-10

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

		$body      = $data;
		$headers   = null;

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


		$headers = self::find_headers($data,$body);

		if(! $headers)
			return $result;

		$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.', LOGGER_DEBUG);
			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($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(! array_key_exists('keyId',$sig_block))
			return $result;

		$result['signer'] = $sig_block['keyId'];

		$key = self::get_key($key,$keytype,$result['signer']);

		if(! ($key && $key['public_key'])) {
			return $result;
		}

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

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

		if(! $x) {

			// try again, ignoring the local actor (xchan) cache and refetching the key
			// from its source

			$fkey = self::get_key($key,$keytype,$result['signer'],true);

			if ($fkey && $fkey['public_key']) {
				$y = rsa_verify($signed_data,$sig_block['signature'],$fkey['public_key'],$algorithm);
				logger('verified: (cache reload) ' . $x, LOGGER_DEBUG);
			}

			if (! $y) {
				logger('verify failed for ' . $result['signer'] . ' alg=' . $algorithm . (($fkey['public_key']) ? '' : ' no key'));
				$sig_block['signature'] = base64_encode($sig_block['signature']);
				logger('affected sigblock: ' . print_r($sig_block,true));
				logger('headers: ' . print_r($headers,true));
				logger('server: ' . print_r($_SERVER,true));
				return $result;
			}

		}

		$result['portable_id'] = $key['portable_id'];
		$result['header_valid'] = true;

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

			if(base64_encode(hash($hashalg,$body,true)) === $digest[1]) {
				$result['content_valid'] = true;
			}

			logger('Content_Valid: ' . (($result['content_valid']) ? 'true' : 'false'));
			if (! $result['content_valid']) {
				logger('invalid content signature: data ' . print_r($data,true));
				logger('invalid content signature: headers ' . print_r($headers,true));
				logger('invalid content signature: body ' . print_r($body,true));
			}
		}

		return $result;
	}

	static function get_key($key,$keytype,$id) {

		if(is_array($key))
			btlogger('key is array: ' . print_r($key,true));

		if($key) {
			if(function_exists($key)) {
				return $key($id);
			}
			return [ 'public_key' => $key ];
		}

		if($keytype === 'zot6') {
			$key = self::get_zotfinger_key($id,$force);
			if($key) {
				return $key;
			}
		}

		if(strpos($id,'#') === false) {
			$key = self::get_webfinger_key($id);
		}

		if(! $key) {
			$key = self::get_activitystreams_key($id);
		}

		return $key;

	}


	function convertKey($key) {

		if(strstr($key,'RSA ')) { 
			return rsatopem($key);
		}
		elseif(substr($key,0,5) === 'data:') {
			return convert_salmon_key($key);
		}
		else {
			return $key;
		}

	}


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

	function get_activitystreams_key($id) {

		// remove fragment

		$url = ((strpos($id,'#')) ? substr($id,0,strpos($id,'#')) : $id);

		$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' and hubloc_network in ('zot6', 'activitypub')",
			dbesc(str_replace('acct:','',$url)),
			dbesc($url)
		);

		$x = Libzot::zot_record_preferred($x);

		if($x && $x['xchan_pubkey']) {
			return [ 'portable_id' => $x['xchan_hash'], 'public_key' => $x['xchan_pubkey'] , 'hubloc' => $x ];
		}

		$r = ActivityStreams::fetch($id);

		if($r) {
			if(array_key_exists('publicKey',$r) && array_key_exists('publicKeyPem',$r['publicKey']) && array_key_exists('id',$r['publicKey'])) {
				if($r['publicKey']['id'] === $id || $r['id'] === $id) {
					$portable_id = ((array_key_exists('owner',$r['publicKey'])) ? $r['publicKey']['owner'] : EMPTY_STR);
					return [ 'public_key' => self::convertKey($r['publicKey']['publicKeyPem']), 'portable_id' => $portable_id, 'hubloc' => [] ];
				}
			}
		}
		return false;
	}


	function get_webfinger_key($id) {

		$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s'",
			dbesc(str_replace('acct:','',$id)),
			dbesc($id)
		);

		$x = Libzot::zot_record_preferred($x);

		if($x && $x['xchan_pubkey']) {
			return [ 'portable_id' => $x['xchan_hash'], 'public_key' => $x['xchan_pubkey'] , 'hubloc' => $x ];
		}

		$wf = Webfinger::exec($id);
		$key = [ 'portable_id' => '', 'public_key' => '', 'hubloc' => [] ];

		if($wf) {
		 	if(array_key_exists('properties',$wf) && array_key_exists('https://w3id.org/security/v1#publicKeyPem',$wf['properties'])) {
				$key['public_key'] = self::convertKey($wf['properties']['https://w3id.org/security/v1#publicKeyPem']);
			}
			if(array_key_exists('links', $wf) && is_array($wf['links'])) {
				foreach($wf['links'] as $l) {
					if(! (is_array($l) && array_key_exists('rel',$l))) {
						continue;
					}
					if($l['rel'] === 'magic-public-key' && array_key_exists('href',$l) && $key['public_key'] === EMPTY_STR) {
						$key['public_key'] = self::convertKey($l['href']);
					}
				}
			}
		}

		return (($key['public_key']) ? $key : false);
	}

	function get_zotfinger_key($id) {

		$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' and hubloc_network = 'zot6'",
			dbesc(str_replace('acct:','',$id)),
			dbesc($id)
		);

		if($x && $x[0]['xchan_pubkey']) {
			return [ 'portable_id' => $x[0]['xchan_hash'], 'public_key' => $x[0]['xchan_pubkey'] , 'hubloc' => $x[0] ];
		}

		$wf = Webfinger::exec($id);
		$key = [ 'portable_id' => '', 'public_key' => '', 'hubloc' => [] ];

		if($wf) {
		 	if(array_key_exists('properties',$wf) && array_key_exists('https://w3id.org/security/v1#publicKeyPem',$wf['properties'])) {
				$key['public_key'] = self::convertKey($wf['properties']['https://w3id.org/security/v1#publicKeyPem']);
			}
			if(array_key_exists('links', $wf) && is_array($wf['links'])) {
				foreach($wf['links'] as $l) {
					if(! (is_array($l) && array_key_exists('rel',$l))) {
						continue;
					}
					if($l['rel'] === 'http://purl.org/zot/protocol/6.0' && array_key_exists('href',$l) && $l['href'] !== EMPTY_STR) {

						// The third argument to Zotfinger::exec() tells it not to verify signatures
						// Since we're inside a function that is fetching keys with which to verify signatures,
						// this is necessary to prevent infinite loops.

						$z = \Zotlabs\Lib\Zotfinger::exec($l['href'],null,false);
						if($z) {
							$i = Libzot::import_xchan($z['data']);
							if($i['success']) {
								$key['portable_id'] = $i['hash'];

								$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_id_url = '%s' and hubloc_network = 'zot6'",
									dbesc($l['href'])
								);
								if($x) {
									$key['hubloc'] = $x[0];
								}
							}
						}
					}
					if($l['rel'] === 'magic-public-key' && array_key_exists('href',$l) && $key['public_key'] === EMPTY_STR) {
						$key['public_key'] = self::convertKey($l['href']);
					}
				}
			}
		}

		return (($key['public_key']) ? $key : false);
	}


	/**
	 * @brief
	 *
	 * @param array $head
	 * @param string $prvkey
	 * @param string $keyid (optional, default '')
	 * @param boolean $auth (optional, default false)
	 * @param string $alg (optional, default 'sha256')
	 * @param array $encryption [ 'key', 'algorithm' ] or false
	 * @return array
	 */
	static function create_sig($head, $prvkey, $keyid = EMPTY_STR, $auth = false, $alg = 'sha256', $encryption = false ) {

		$return_headers = [];

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

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

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

		if($encryption) {
			$x = crypto_encapsulate($headerval,$encryption['key'],$encryption['algorithm']);
			if(is_array($x)) {
				$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) {
				// strip the request-target virtual header from the output headers
				if($k === '(request-target)') {
					continue;
				}
				$return_headers[] = $k . ': ' . $v;
			}
		}
		$return_headers[] = $sighead;

		return $return_headers;
	}

	/**
	 * @brief set headers
	 *
	 * @param array $headers
	 * @return void
	 */


	static function set_headers($headers) {
		if($headers && is_array($headers)) {
			foreach($headers as $h) {
				header($h);
			}
		} 
	}


	/**
	 * @brief
	 *
	 * @param array  $head
	 * @param string $prvkey
	 * @param string $alg (optional) default 'sha256'
	 * @return array
	 */

	static function sign($head, $prvkey, $alg = 'sha256') {

		$ret = [];

		$headers = '';
		$fields  = '';

		logger('signing: ' . print_r($head,true), LOGGER_DATA);

		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) {

		$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 '';
	}

}