e35a8a10c96e5f2b069a3b8ad58d88b7d4b02cdf
[mirror/dsa-nagios.git] / dsa-nagios-checks / weak-ssh-keys-check
1 #!/usr/bin/perl
2
3 # This cheak is based on code from the Debian/OpenSSL Weak Key Detector
4 # written by Florian Weimer <fw@deneb.enyo.de>. 
5 # The code has been modified and enhanced by Alexander Wirt 
6 # <formorer@debian.org> to use it as a nagios check. 
7 #
8 # Copyright (c) 2008, Florian Weimer <fw@deneb.enyo.de> for the original 
9 # Debian/OpenSSL Weak Key Detector 
10 # (http://security.debian.org/project/extra/dowkd/dowkd.pl.gz)
11 #
12 # Copyright (c) 2008, Alexander Wirt <formorer@debian.org> for check_weakkeys
13 #
14 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
15 #
16 # Permission to use, copy, modify, and/or distribute this software for any
17 # purpose with or without fee is hereby granted, provided that the above
18 # copyright notice and this permission notice appear in all copies.
19 #
20 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 #
28
29 =pod
30
31 =head1 NAME
32
33 B<check_weakkeys> - checks system for weak ssh keys 
34
35 =cut
36
37 =head1 SYNOPSIS
38
39 B<check_weakkeys> [options]
40
41 =cut
42
43 =head1 DESCRIPTION
44
45 B<check_weakkeys> checks for all users if there id_rsa, id_dsa or
46 authorized_key files if they contain weak ssh keys created by a Debian with a
47 broken libssl (see DSA-1571 for more informations). Optionally <check_weakkeys>
48 can spit out a warning of there are any DSA keys left in key or authorized_key
49 files. To work it needs a database of precomputed hashes of known weak keys.
50 This file is expected as an bdb database with the hash (like
51 03:a2:f0:46:7f:13:9f:5f:96:71:a9:b8:a0:1c:01:05) as key. See <gen_fprdb> for
52 such a database generator.  <check_weakkeys> outputs his data to STDOUT or to a
53 file. It meaned to be picked up by an nagios check like B<dsa-check-statusfile>
54 from Peter Palfrader. 
55
56 =cut
57
58 =head1 OPTIONS
59
60 =over 4
61
62 =item B<-h, --help>
63
64 Prints out a brief help
65
66 =item B<-s, --statusfile> "statusfile"
67
68 Use 'F<statusfile>' instead of 'F<STDOUT>'. 
69
70 =item B<-f, --fprdb> "database" (default: /var/lib/dsa/ssh-weak-keys.db)
71
72 Use 'F<database>' instead of 'F</var/lib/dsa/ssh-weak-keys.db>'
73 as fingerprint database. 
74
75 =item B<-n, --dsa_nowarn> 
76
77 Don't warn for DSA keys
78
79 =back 
80
81 =cut
82
83 use strict;
84 use warnings;
85
86 use File::Temp;
87 use BerkeleyDB;
88 use Pod::Usage;
89 use Getopt::Long;
90 use IPC::Open3;
91
92 my $fprdb_fname = "/var/lib/dsa/ssh-weak-keys.db" ;
93 my ($outfile, $help);
94 my $dsa_nowarn = 0;
95
96 GetOptions(     'help|h' => \$help, #Help function
97                 'statusfile|s=s' => \$outfile, 
98                 'fprdb|f=s' => \$fprdb_fname,
99                 'n|dsa_nowarn' => \$dsa_nowarn,  
100 );
101
102 pod2usage(1) if $help;
103
104 my $fh; 
105 if ($outfile) {
106         open ($fh, '>', $outfile) 
107                 or die "Could not open statusfile '$outfile' for writing: $!";
108 } else {
109         $fh = *STDOUT; 
110 }
111
112 my %fpr_hash;
113 tie %fpr_hash, 'BerkeleyDB::Btree',
114         -Filename   => $fprdb_fname,
115         -Flags      => DB_RDONLY
116                 or die "Cannot open fingerprint db $fprdb_fname: $! $BerkeleyDB::Error\n";
117
118
119 my ($weak_keys,$checked_keys) = 0;
120 my $dsa_keys = 0;
121 my $weird_keyfiles = 0;
122 my $text = '';
123 my %key_sizes;
124
125
126
127 #&from_user_all;
128 &from_debianorg_places;
129 &from_ssh_host(qw(localhost));
130
131 my $status="OK";
132 if ($weak_keys) {
133         $status = "CRITICAL";
134 } elsif ($dsa_keys && ! $dsa_nowarn  ||  $weird_keyfiles) {
135         $status = "WARNING";
136 }
137
138 print $fh "$status\n";
139 print $fh "Checked $checked_keys keys - $weak_keys weak - $dsa_keys dsa keys\n";
140 print $fh "Sizes: ";
141 foreach my $size (sort(keys(%key_sizes))) {
142         print $fh "$size:$key_sizes{$size} ";
143 }
144
145 print $fh "\n";
146 print $fh "$text" if $text;
147
148
149
150 sub safe_backtick (@) {
151     my @args = @_;
152
153     my ($wtr, $fh, $err);
154
155     open3($wtr,$fh,$err, @args)
156         or die "error: failed to spawn $args[0]: $!\n";
157     my @result;
158     if (wantarray) {
159         @result = <$fh>;
160     } else {
161         local $/;
162         @result = scalar(<$fh>);
163     }
164     close $fh;
165     $? == 0 or return undef;
166     if (wantarray) {
167         return @result;
168     } else {
169         return $result[0];
170     }
171 }
172
173 sub ssh_fprint_file ($) {
174     my $name = shift;
175     my $data = safe_backtick qw/ssh-keygen -l -f/, $name;
176     defined $data or return ();
177     my @data = $data =~ /^(\d+) ([0-9a-f]{2}(?::[0-9a-f]{2}){15})/;
178     return @data if @data == 2;
179     return ();
180 }
181
182 sub ssh_fprint_check ($$$) {
183     my ($name, $length, $hash) = @_;
184     if (exists $key_sizes{$length}) {
185             $key_sizes{$length}++;
186     } else {
187             $key_sizes{$length}=1;
188     }
189     $checked_keys++;
190     if (exists $fpr_hash{$hash}) {
191         $weak_keys++;
192         $text .= "$name weak ($hash)\n";
193     }
194 }
195
196
197 sub from_ssh_key_file ($) {
198     my $name = shift;
199     if (open (my $FH, '<', $name)) {
200         my $key = <$FH>; 
201         if (! defined $key) {
202                 $weird_keyfiles++;
203                 $text .= "cannot read $name properly - empty?\n";
204         } elsif ($key =~ m/ssh-dss/) {
205                 $dsa_keys++;
206                 $text .= "$name is a DSA key\n";
207         }
208     } else {
209         $text .= "Could not open $name: $!";
210     }
211     my ($length, $hash) = ssh_fprint_file $name;
212     if ($length && $hash) {
213         ssh_fprint_check "$name:1", $length, $hash;
214     } else {
215         $text .= "$name:1: warning: failed to parse SSH key file\n";
216     }
217 }
218
219 sub clear_tmp ($) {
220     my $tmp = shift;
221     seek $tmp, 0, 0 or die "seek: $!";
222     truncate $tmp, 0 or die "truncate: $!";
223 }
224
225 sub from_ssh_auth_file ($) {
226     my $name = shift;
227     my $auth;
228     unless (open $auth, '<', $name) {
229         warn "$name:0: error: open failed: $!\n";
230         return;
231     }
232     my $tmp = new File::Temp;
233     while (my $line = <$auth>) {
234         chomp $line;
235         my $lineno = $.;
236         clear_tmp $tmp;
237         next if $line =~ m/^$/; # ignore empty lines
238         next if $line =~ m/^#/; # ignore comments
239         if ($line =~ m/ssh-dss/) {
240                 $dsa_keys++;
241                 $text .= "$name:$lineno is a DSA key\n";
242         }
243         print $tmp "$line\n" or die "print: $!";
244         $tmp->flush;
245         my ($length, $hash) = ssh_fprint_file "$tmp";
246         if ($length && $hash) {
247             ssh_fprint_check "$name:$lineno", $length, $hash;
248         } else {
249             $text .= "$name:$lineno: warning: unparsable line\n";
250         }
251     }
252 }
253
254 sub from_ssh_host (@) {
255     my @names = @_;
256     my @lines;
257     push @lines, safe_backtick qw|ssh-keyscan -t rsa|, @names;
258     push @lines, safe_backtick qw|ssh-keyscan -t dsa|, @names;
259
260     my $tmp = new File::Temp;
261     for my $line (@lines) {
262         next if $line =~ /^#/;
263         next if $line =~ /^no hostkey alg/;
264         my ($host, $data) = $line =~ /^(\S+) (.*)$/;
265         clear_tmp $tmp;
266         print $tmp "$data\n" or die "print: $!";
267         $tmp->flush;
268         my ($length, $hash) = ssh_fprint_file "$tmp";
269         if ($length && $hash) {
270             ssh_fprint_check "$host", $length, $hash;
271         } else {
272             $text .= "$host: warning: unparsable line\n";
273         }
274     }
275 }
276
277 sub from_user ($) {
278     my $user = shift;
279     my ($name,$passwd,$uid,$gid,
280         $quota,$comment,$gcos,$dir,$shell,$expire) = getpwnam($user);
281     my $file = "$dir/.ssh/authorized_keys";
282     from_ssh_auth_file $file if -r $file;
283     $file = "$dir/.ssh/authorized_keys2";
284     from_ssh_auth_file $file if -r $file;
285     $file = "$dir/.ssh/id_rsa.pub";
286     from_ssh_key_file $file if -r $file;
287     $file = "$dir/.ssh/id_dsa.pub";
288     from_ssh_key_file $file if -r $file;
289 }
290
291 sub from_user_all () {
292     setpwent;
293     while (my $name = getpwent) {
294         from_user $name;
295     }
296     endpwent;
297 }
298
299
300 sub from_debianorg_places () {
301     open(F, "/etc/ssh/sshd_config") or die ("Cannot open /etc/ssh/sshd_config: $!\n");
302     my @lines = <F>;
303     close(F);
304
305     my @ak = grep { /^AuthorizedKeysFile\s/i } @lines;
306     my @ak2 = grep { /^AuthorizedKeysFile2\s/i } @lines;
307
308     if (scalar @ak != 1) {
309         print $fh "UNKNOWN\n";
310         print $fh "There is more than one AuthorizedKeysFile definition in sshd_config\n";
311         exit
312     }
313     if (scalar @ak2 != 1) {
314         print $fh "UNKNOWN\n";
315         print $fh "There is more than one AuthorizedKeysFile2 definition in sshd_config\n";
316         exit
317     }
318     unless ($ak[0] =~ m#^((?i)AuthorizedKeysFile)\s+/etc/ssh/userkeys/%u$# ) {
319         print $fh "UNKNOWN\n";
320         print $fh "The AuthorizedKeysFile definition has an unexpected value.  Should be /etc/ssh/userkeys/%u\n";
321         exit
322     }
323     unless ($ak2[0] =~ m#^((?i)AuthorizedKeysFile2)\s+/var/lib/misc/userkeys/%u$# ) {
324         print $fh "UNKNOWN\n";
325         print $fh "The AuthorizedKeysFile2 definition has an unexpected value.  Should be /var/lib/misc/userkeys/%u\n";
326         exit
327     }
328
329     for my $d (qw{/etc/ssh/userkeys /var/lib/misc/userkeys}) {
330         next unless (-d $d);
331         opendir(D, $d) or die "Cannot opendir $d: $!\n";
332         for my $file (grep { ! -d $d.'/'.$_ } readdir(D)) {
333             next if ($file eq 'README-DSA-BUILDD');
334             my $f = $d.'/'.$file;
335             from_ssh_key_file $f if -r $f;
336         };
337     };
338 }
339
340