Rev 4 | 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 | |||
27 | $cont = file_get_contents($file); |
||
28 | $original = $cont; |
||
29 | |||
30 | if (strpos($cont, '<?php') === false) { |
||
31 | echo "Not a PHP file: $file\n"; |
||
32 | continue; |
||
33 | } |
||
34 | |||
35 | $naked = preg_replace('@<\?php /\* <ViaThinkSoftSignature>(.+)</ViaThinkSoftSignature> \*/ \?>\n@ismU', '', $cont); |
||
36 | |||
37 | $hash = hash("sha256", $naked.basename($file)); |
||
38 | |||
39 | $pkeyid = @openssl_pkey_get_private('file://'.__DIR__.'/private.pem'); |
||
40 | openssl_sign($hash, $signature, $pkeyid, OPENSSL_ALGO_SHA256); |
||
41 | openssl_free_key($pkeyid); |
||
42 | |||
43 | if (!$signature) { |
||
44 | echo "ERROR: $file\n"; |
||
45 | continue; |
||
46 | } |
||
47 | |||
4 | daniel-mar | 48 | $sign_line = '<?php /* <ViaThinkSoftSignature>'."\n".split_equal_length(base64_encode($signature),65).'</ViaThinkSoftSignature> */ ?>'; |
49 | |||
50 | // 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 | 51 | if (substr($cont,0,2) === '#!') { |
52 | // Preserve shebang |
||
53 | $shebang_pos = strpos($naked, "\n"); |
||
54 | $shebang = substr($naked, 0, $shebang_pos); |
||
55 | $rest = substr($naked, $shebang_pos+1); |
||
56 | $cont = $shebang."\n".$sign_line."\n".$rest; |
||
57 | } else { |
||
58 | $cont = $sign_line."\n".$naked; |
||
59 | } |
||
60 | |||
61 | if ($cont != $original) { |
||
62 | echo "Signed: $file\n"; |
||
63 | file_put_contents($file, $cont); |
||
64 | } else { |
||
65 | echo "Already signed: $file\n"; |
||
66 | } |
||
67 | } |
||
68 | |||
4 | daniel-mar | 69 | # --- |
70 | |||
71 | function split_equal_length($data, $width=65) { |
||
72 | $out = ''; |
||
73 | for ($i=0; $i<strlen($data); $i+=$width) { |
||
74 | $out .= substr($data, $i, $width)."\n"; |
||
75 | } |
||
76 | return $out; |
||
77 | } |
||
78 |