-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcheck_certexp.pl
executable file
·367 lines (306 loc) · 9.97 KB
/
check_certexp.pl
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
#!/usr/bin/env perl
# Check certificate expiry.
#
# Copyright (c) 2016 Michael Kraus <[email protected]>.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##############################################################################
#
# basic settings
#
##############################################################################
use warnings;
use strict;
use IO::Socket;
use Getopt::Long;
use Net::SSLeay;
use Date::Manip;
use MIME::Base64;
use vars qw($opt_H $opt_c $opt_w $opt_h $opt_i $opt_p $opt_t $opt_d $opt_v );
my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3);
sub expiry_date ($$$$);
sub get_cert_details ($);
sub make_regex ($);
sub verbose ();
sub die_crit ($);
sub die_warn ($);
sub die_ok ($);
sub die_unknown ($);
sub print_usage ();
sub print_help ();
my $suffix = '';
my $PROGNAME = 'check_certexp.pl';
my $CRIT = 28;
my $TIMEOUT = 15;
$SIG{ALRM} = sub { die_unknown("Timeout of $TIMEOUT seconds reached."); };
$ENV{PATH} = '';
$ENV{ENV} = '';
$ENV{TZ} = 'CET';
##############################################################################
#
# parse options
#
##############################################################################
Getopt::Long::Configure('bundling');
if (!GetOptions('h|help' => \$opt_h,
'H|hostname=s' => \$opt_H,
'c|critical=i' => \$opt_c,
'w|warning=i' => \$opt_w,
'p|proxy=s' => \$opt_p,
'i|issuer=s' => \$opt_i,
'd|debug' => \$opt_d,
'v|verbose+' => \$opt_v,
't|timeout=i' => \$opt_t,)) {
print "Error processing command line options\n";
print_usage();
exit $ERRORS{UNKNOWN};
}
# help
if ($opt_h) {
print_help();
exit $ERRORS{OK};
}
# debug
my $debug = 0;
if ($opt_d) {
$debug = 1;
}
# verbose
my $verbose = 0;
if ($opt_v) {
$verbose = $opt_v;
}
# host:port / proxy:port
unless ($opt_H) {
print "No target host specified\n";
print_usage();
exit $ERRORS{UNKNOWN};
}
my ($host, $port, $dhost, $dport, $url, $servername);
if ($opt_p) {
($host, $port) = split(/:/, $opt_p);
($dhost, $dport) = split(/:/, $opt_H);
$url = $dhost;
$servername = $dhost;
} else {
($host, $port) = split(/:/, $opt_H);
$dhost = 'no';
$url = $host;
$servername = $host;
}
unless ($port) { $port = 443; }
unless ($dport) { $dport = 443; }
# thresholds
my $critical = $opt_c ? $opt_c : $CRIT;
my $warning = $opt_w ? $opt_w : $critical;
if ($warning < $critical) {
print "WARNING threshold exceeds CRITICAL threshold\n";
print_usage();
exit $ERRORS{UNKNOWN};
}
# timeout
my $timeout = $opt_t ? $opt_t : $TIMEOUT;
alarm($timeout);
# issuers
my @issuers = split(/:/, $opt_i) if $opt_i;
##############################################################################
#
# main
#
##############################################################################
my $san = "";
# get certificate details
my ($notafter_days, $notafter, $notbefore_days, $notbefore, $subject, $issuer) = expiry_date($host, $port, $dhost, $dport);
# verify subject
print "DEBUG Verify $url with subject [ ",$subject," ]:\n" if $debug;
my $subject_cn = $subject;
$subject_cn=~ s/\/.*CN=([^\/]+).*/$1/;
print "DEBUG Subject CN (CN): ",$subject_cn,"\n" if $debug;
print "DEBUG SAN): ",$san,"\n" if $debug;
die_crit("$url does not match Subject CN '$subject_cn' or SAN '$san'") if not
grep {
$url =~ /$_/;
} map {
make_regex($_);
} map {
split(/\s+/, $_);
} ($subject_cn, $san);
# verify issuer
my $issuer_cn = $issuer;
$issuer_cn =~ s/\/.*CN=([^\/]+).*/$1/;
print "DEBUG Issuer (CN): ",$issuer_cn,"\n" if $debug;
if (@issuers) {
die_crit("Issuer CN '$issuer_cn' does not match: " . join(':', @issuers)) if not grep($issuer_cn eq $_, @issuers);
$suffix = " (Issuer: $issuer)";
}
# not yet valid
if ($notbefore_days > 0) {
die_crit("Certificate will be valid in $notbefore_days $suffix");
}
# is expired
if ($notafter_days < 0) {
$notafter_days =~ s/^-//;
die_crit("Certificate expired $notafter_days ago $suffix");
}
# verify against thresholds
die_crit("Certificate expires in $notafter_days days $suffix") if $notafter_days < $critical;
die_warn("Certificate expires in $notafter_days days $suffix") if $notafter_days < $warning;
die_ok("Certificate expires in $notafter_days days $suffix");
##############################################################################
#
# subs
#
##############################################################################
sub expiry_date ($$$$) {
my ($host, $port, $dhost, $dport) = @_;
my ($buffer, $iaddr, $paddr, $ctx, $ssl, $crt, $end, $str);
print "DEBUG Connect to host: ",$host,":",$port,"\n" if $debug;
# connect
$| = 1;
my $sock = new IO::Socket::INET (
PeerAddr => $host,
PeerPort => $port,
Proto => 'tcp',
) || die_unknown("Error connecting to $host: $!");
# connect with proxy
unless ( $dhost eq 'no' ) {
print "DEBUG Connect via proxy to destination: ",$dhost,":",$dport,"\n" if $debug;
# send a "CONNECT" command to proxy
print $sock "CONNECT $dhost:$dport HTTP/1.0\r\n\r\n";
# get HTTP status code, bail out unless 2xx
my $recv_line = <$sock>;
my ($status) = (split(/\s+/,$recv_line))[1];
die_unknown("Received a bad status code \"$status\" from proxy server.") if ( int($status/100) != 2 );
# skip through remaining part of HTTP header (until blank line)
1 until ( <$sock> =~ /^[\r\n]+$/ );
}
# initialize SSL
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms();
Net::SSLeay::randomize();
$ctx = Net::SSLeay::CTX_new();
my $mode = &Net::SSLeay::VERIFY_NONE;
Net::SSLeay::CTX_set_verify($ctx, $mode);
$ssl = Net::SSLeay::new($ctx);
Net::SSLeay::set_tlsext_host_name($ssl, $servername);
Net::SSLeay::set_fd($ssl, fileno($sock));
Net::SSLeay::connect($ssl);
# DO NOT DIE HERE IF CONNECTION FAILS - WE CAN GET SERVER CERTIFICATE EVEN WITHOUT SUCCESSFUL CONNECTION THEN
# get certificate
$crt = Net::SSLeay::get_peer_certificate($ssl)
|| die_unknown(Net::SSLeay::print_errs('Cannot get peer certificate') or 'Cannot get peer certificate');
# get dates
my $tmp;
my $notafter = Net::SSLeay::P_ASN1_UTCTIME_put2string(Net::SSLeay::X509_get_notAfter($crt));
print "DEBUG NotAfter: ",$notafter,"\n" if $debug;
$tmp = $notafter;
$tmp =~ s/ GMT//;
my $notafter_days = int((&UnixDate(&ParseDate($tmp), '%s') - time) / 86400);
print "DEBUG NotAfter (days): ",$notafter_days,"\n" if $debug;
my $notbefore = Net::SSLeay::P_ASN1_UTCTIME_put2string(Net::SSLeay::X509_get_notBefore($crt));
print "DEBUG NotBefore: ",$notbefore,"\n" if $debug;
$tmp = $notbefore;
$tmp =~ s/ GMT//;
my $notbefore_days = int((&UnixDate(&ParseDate($tmp), '%s') - time) / 86400);
print "DEBUG NotBefore (days): ",$notbefore_days,"\n" if $debug;
# get subject
my $subject = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($crt));
print "DEBUG Subject: ",$subject,"\n" if $debug;
# get issuer
my $issuer = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_issuer_name($crt));
print "DEBUG Issuer: ",$issuer,"\n" if $debug;
# get sans
my @altnames = Net::SSLeay::X509_get_subjectAltNames($crt);
if ( @altnames ) { while (@altnames) {
my $type = shift @altnames;
my $value = shift @altnames;
$value = join('.', unpack('C4', $value)) if ( $type == 7 ); # IP Address
$san.=$value.' ';
} }
print "DEBUG SANs ",$san,"\n" if $debug;
#
# cleanup
Net::SSLeay::free($ssl);
Net::SSLeay::CTX_free($ctx);
$sock->close();
return ("$notafter_days", "$notafter", "$notbefore_days", "$notbefore", "$subject", "$issuer");
}
sub make_regex ($) {
my $glob = shift;
$glob =~ s/\./\\./g;
$glob =~ s/^\*/.*/g;
return '^'.$glob.'$';
}
sub verbose () {
if ($verbose == 2) {
printf "Subject: %s\n",$subject if $subject;
printf "SANs %s\n",$san if $san;
printf "Issuer: %s\n",$issuer if $issuer;
printf "NotAfter: %s\n",$notafter if $notafter;
printf "NotBefore: %s\n",$notbefore if $notbefore;
}
if ($verbose == 1) {
printf "Subject CN: %s\n",$subject_cn if $subject_cn;
printf "SANs %s\n",$san if $san;
printf "Issuer CN: %s\n",$issuer_cn if $issuer_cn;
printf "NotAfter: %s\n",$notafter if $notafter;
printf "NotBefore: %s\n",$notbefore if $notbefore;
}
}
sub die_unknown ($) {
printf "UNKNOWN: %s\n", shift;
exit $ERRORS{UNKNOWN};
}
sub die_warn ($) {
printf "WARNING: %s\n", shift;
verbose() if $verbose;
exit $ERRORS{WARNING};
}
sub die_crit ($) {
printf "CRITICAL: %s\n", shift;
verbose() if $verbose;
exit $ERRORS{CRITICAL};
}
sub die_ok ($) {
printf "OK: %s\n", shift;
verbose() if $verbose;
exit $ERRORS{OK};
}
sub print_usage () {
print "Usage: $PROGNAME -H host [-p proxy] [-i issuer] [-w warn]\n" .
" [-c crit] [-t timeout] [-d] [-v]\n";
}
sub print_help () {
print "Check certificate expiry date.\n\n";
print_usage();
print <<EOF;
-H, --hostname=ADDRESS[:PORT]
Host name or IP address, port defaults to 443
-p, --proxy=ADDRESS[:PORT]
Proxy name or IP address, port defaults to 443
-i, --issuer=NAME:NAME
Certificate issuer name(s)
-w, --warning=INTEGER
WARNING if less than specified number of days until expiry (default: $CRIT)
-c, --critical=INTEGER
CRITICAL if less than specified number of days until expiry (default: $CRIT)
-t, --timeout=INTEGER
Seconds before connection times out (default: $TIMEOUT)
-d
Enable debug output
-v
Enable verbose output, use multiple for different views
EOF
}