Subversion Repositories vnag

Rev

Rev 33 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 daniel-mar 1
#!/usr/bin/php
2
<?php
3
 
33 daniel-mar 4
/*
5
 * VNag - Nagios Framework for PHP
6
 * Developed by Daniel Marschall, ViaThinkSoft <www.viathinksoft.com>
7
 * Licensed under the terms of the Apache 2.0 license
8
 *
9
 * Revision 2018-11-06
10
 */
11
 
2 daniel-mar 12
// Generate keypair with:
13
//	openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:8192
14
//	openssl rsa -pubout -in private.pem -out public.pem
15
 
16
if ($argc < 2) {
17
	die("Syntax: $argv[0] file1 [file2 ...]\n");
18
}
19
 
20
if (!file_exists(__DIR__.'/private.pem')) {
21
	echo "Key private.pem not found\n";
22
}
23
 
24
for ($i=1; $i<$argc; $i++) {
25
	$file = $argv[$i];
26
 
59 daniel-mar 27
	if (is_dir($file)) continue;
2 daniel-mar 28
	$cont = file_get_contents($file);
29
	$original = $cont;
30
 
31
	if (strpos($cont, '<?php') === false) {
32
		echo "Not a PHP file: $file\n";
33
		continue;
34
	}
35
 
36
	$naked = preg_replace('@<\?php /\* <ViaThinkSoftSignature>(.+)</ViaThinkSoftSignature> \*/ \?>\n@ismU', '', $cont);
37
 
38
	$hash = hash("sha256", $naked.basename($file));
39
 
40
	$pkeyid = @openssl_pkey_get_private('file://'.__DIR__.'/private.pem');
41
	openssl_sign($hash, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
42
	openssl_free_key($pkeyid);
43
 
44
	if (!$signature) {
45
		echo "ERROR: $file\n";
46
		continue;
47
	}
48
 
4 daniel-mar 49
	$sign_line = '<?php /* <ViaThinkSoftSignature>'."\n".split_equal_length(base64_encode($signature),65).'</ViaThinkSoftSignature> */ ?>';
50
 
51
	// We have to put the signature at the beginning, because we don't know if the end of the file lacks a PHP closing tag
2 daniel-mar 52
	if (substr($cont,0,2) === '#!') {
53
		// Preserve shebang
54
		$shebang_pos = strpos($naked, "\n");
55
		$shebang = substr($naked, 0, $shebang_pos);
56
		$rest = substr($naked, $shebang_pos+1);
57
		$cont = $shebang."\n".$sign_line."\n".$rest;
58
	} else {
59
		$cont = $sign_line."\n".$naked;
60
	}
61
 
62
	if ($cont != $original) {
63
		echo "Signed: $file\n";
64
		file_put_contents($file, $cont);
65
	} else {
66
		echo "Already signed: $file\n";
67
	}
68
}
69
 
4 daniel-mar 70
# ---
71
 
72
function split_equal_length($data, $width=65) {
73
	$out = '';
74
	for ($i=0; $i<strlen($data); $i+=$width) {
75
		$out .= substr($data, $i, $width)."\n";
76
	}
77
	return $out;
78
}
79