Added author information.
[blocksshd_00z.git] / blocksshd
blob884b3bb422c69111d3a571255010a0b104cefc69
1 #!/usr/bin/perl -w
3 # This is BlockSSHD which protects computers from SSH brute force attacks by
4 # dynamically blocking IP addresses using iptables based on log entries.
5 # BlockSSHD is modified from BruteForceBlocker v1.2.3 by Daniel Gerzo
7 # Copyright (C) 2006, James Turnbull
8 # Support for pf and whois added by Anton - valqk@webreality.org - http://www.webreality.org
9 # Support for subnets in the whitelist added by Lester Hightower - hightowe@10east.com - http://www.10east.com/
10 # Support for repeated (but valid) syslog lines by Abel `00z' Camarillo <00z@the00z.org> - http://the00z.org
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful, but
18 # WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
20 # Public License for more details.
22 # You should have received a copy of the GNU General Public License along
23 # with this program; if not, write to the Free Software Foundation, Inc.,
24 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26 use strict;
27 use warnings;
29 use Sys::Syslog;
30 use Sys::Hostname;
31 use Tie::File;
32 use File::Tail;
33 use Net::DNS::Resolver;
34 use Net::Subnets;
35 use Getopt::Long;
37 use POSIX qw(setsid);
38 use vars qw($opt_d $opt_h $opt_v $opt_stop);
40 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin';
42 my $version = "1.3";
44 our $cfg;
46 # This is where the configuration file is located
47 require '/etc/blocksshd.conf';
49 my $work = {
50 ipv4 => '(?:\d{1,3}\.){3}\d{1,3}', # regexp to match ipv4 address
51 fqdn => '[\da-z\-.]+\.[a-z]{2,4}', # regexp to match fqdn
52 hostname => hostname, # get hostname
55 $cfg->{'whitelist_prepared'}=&loadwhitelist($cfg->{whitelist});
57 Getopt::Long::Configure('bundling');
58 GetOptions
59 ("start" => \$opt_d, "daemon" => \$opt_d, "d" => \$opt_d,
60 "h" => \$opt_h, "help" => \$opt_h,
61 "v" => \$opt_v, "version" => \$opt_v,
62 "stop" => \$opt_stop);
64 if ($opt_d) {
65 if (-e $cfg->{pid_file})
66 { die "BlockSSHD is already running!\n" }
68 # Fork daemon
69 chdir '/' || die "Can't change directory to /: $!";
70 umask 0;
71 open(STDIN, "+>/dev/null");
72 open(STDOUT, "+>&STDIN");
73 open(STDERR, "+>&STDIN");
74 defined(my $pid = fork) || die "Can't fork: $!";
75 exit if $pid;
76 setsid || die "Can't start a new session: $!";
78 # Record PID
79 open (PID,">$cfg->{pid_file}") || die ("Cannot open BlockSSHD PID file $cfg->{pid_file}!\n");
80 print PID "$$\n";
81 close PID;
84 if ($opt_stop) {
85 exithandler();
88 if ($opt_h) {
89 print_help();
90 exit;
93 if ($opt_v) {
94 print "BlockSSHD version $version\n";
95 exit;
98 openlog('blocksshd', 'pid', 'auth');
100 my $alarmed = 0; # ALRM state
101 my %count = (); # hash used to store total number of failed tries
102 my %timea = (); # hash used to store last time when IP was active
103 my %timeb = (); # hash used to store time when IP was blocked
104 my $res = Net::DNS::Resolver->new;
106 # Watch signals
108 $SIG{'ALRM'} = \&unblock;
109 $SIG{'INT'} = \&exithandler;
110 $SIG{'QUIT'} = \&exithandler;
111 $SIG{'KILL'} = \&exithandler;
112 $SIG{'TERM'} = \&exithandler;
114 # Notify of startup
116 syslog('notice', "Starting BlockSSHD");
118 # Create iptables chain
120 setup();
122 # Clear existing rules
124 flush();
126 # Restore previously blocked rules
128 if($cfg->{restore_blocked} == 1) {
129 restore_blocked();
132 # The core process
134 my $ref=tie *FH, "File::Tail", (name=>$cfg->{logfile},
135 maxinterval=>$cfg->{logcheck},
136 interval=> 10,
137 errmode=> "return");
139 if ( $cfg->{unblock} == 1) {
140 alarm( ($cfg->{unblock_timeout} /2) );
144 # Used because sometimes when the same message appears a lot of times syslog
145 # simply replace the line next to the first message with a :
147 # /var/log/messages:
149 # <month> <day> <hour> <host> sshd[<pid>] Failed password for <USER> from <ip>
150 # <month> <day> <hour> <host> last message repeated 2 times.
152 # this var stores a hash ref to the previous line that contain the line
153 # content, a array ref to the IPs to block and its badness.
154 my $prev_line;
156 while (<FH>)
158 if( $alarmed ) {
159 $alarmed = 0;
160 next;
163 # if the previous line was a bad line
164 if ($prev_line->{'bad'})
166 # `block' it again N times
167 if (my ($times) = /last message repeated ([[:digit:]]+) times/i)
169 map { block($_) } @{$prev_line->{'ip'}} while ($times--);
171 next;
174 # `bad' lines definition:
175 if (
176 /.*Failed (password) .* from ($work->{ipv4}|$work->{fqdn}) port [0-9]+/i ||
177 /.*(Invalid|Illegal) user .* from ($work->{ipv4}|$work->{fqdn})$/i ||
178 /.*Failed .* for (invalid|illegal) user * from ($work->{ipv4}|$work->{fqdn}) port [0-9]+ .*/i ||
179 /.*Failed .* for (invalid|illegal) user .* from ($work->{ipv4}|$work->{fqdn})/i ||
180 /.*(Postponed) .* for .* from ($work->{ipv4}|$work->{fqdn}) port [0-9]+ .*/i ||
181 /.*Did not receive (identification) string from ($work->{ipv4}|$work->{fqdn})$/i ||
182 /.*Bad protocol version (identification) .* from ($work->{ipv4}|$work->{fqdn})$/i ||
183 /.* login attempt for (nonexistent) user from ($work->{ipv4}|$work->{fqdn})$/i ||
184 /.* bad (password) attempt for '.*' from ($work->{ipv4}|$work->{fqdn}):[0-9]+/i ||
185 /.*unknown (user) .* from ($work->{ipv4}|$work->{fqdn}).*/i ||
186 /.*User .* (from) ($work->{ipv4}|$work->{fqdn}) not allowed because.*/i ||
187 /.*USER.*no such (user) found from ($work->{ipv4}|$work->{fqdn}).*/i
190 if($1 || $2)
192 my $IP=$1 unless $2;
193 $IP=$2 if $2;
194 if ( $IP =~ /$work->{fqdn}/i)
196 foreach my $type (qw(AAAA A))
198 my $query = $res->search($IP, $type);
199 if ($query)
201 my @ips;
202 foreach my $rr ($query->answer)
204 block($rr->address);
205 push @ips, $rr->address;
207 $prev_line = {content => $_ , ip => \@ips, bad => 1};
210 } else {
211 block($IP);
212 $prev_line = {content => $_ , ip => [$IP], bad => 1};
215 } else {
216 $prev_line = {content => $_ , ip => undef, bad => 0};
220 closelog();
222 sub block {
223 # Confirm iptables table is created
224 setup();
226 my ($IP) = shift or die "Missing IP address!\n";
228 # check to see if IP address already blocked
230 if($cfg->{os} eq 'linux') {
231 my ($exists) = system("$cfg->{iptables} -n -L $cfg->{chain} | grep -q '$IP'");
232 if ($exists == 0) {
233 return;
236 elsif($cfg->{os} eq 'bsd') {
237 my ($exists) = system("$cfg->{pfctl} -t $cfg->{chain} -T show| grep -q '$IP'");
238 if ($exists == 0) {
239 return;
243 # Reset IP count if timeout exceeded
244 if ($timea{$IP} && ($timea{$IP} < time - $cfg->{timeout})) {
245 syslog('notice', "Resetting $IP count, since it wasn't active for more than $cfg->{timeout} seconds");
246 delete $count{$IP};
248 $timea{$IP} = time;
250 # increase the total number of failed attempts
251 $count{$IP}++;
253 if ($count{$IP} < $cfg->{max_attempts}+1) {
254 syslog('notice', "$IP was logged with a total count of $count{$IP} failed attempts");
256 if ($count{$IP} >= $cfg->{max_attempts}+1) {
257 syslog('notice', "IP $IP reached the maximum number of failed attempts!");
258 system_block($IP);
262 sub system_block {
263 my $IP=shift or die("Can't find IP to block.\n");
264 if (ref($cfg->{'whitelist_prepared'}->check(\$IP)) ne 'SCALAR') {
265 if($cfg->{os} eq 'linux') {
266 syslog('notice', "Blocking $IP in iptables table $cfg->{chain}.");
267 system("$cfg->{iptables} -I $cfg->{chain} -p tcp --dport 22 -s $IP -j DROP") == 0 || syslog('notice', "Couldn't add $IP to firewall");
269 if($cfg->{os} eq 'bsd') {
270 syslog('notice', "Blocking $IP in pf table $cfg->{chain}.");
271 system("$cfg->{pfctl} -t $cfg->{chain} -T add $IP") == 0 || syslog('notice', "Couldn't add $IP to firewall");
273 $timeb{$IP} = time;
274 # send mail if it is configured
275 if ($cfg->{send_email} eq '1') {
276 notify($IP);
278 if ($cfg->{restore_blocked} eq '1') {
279 log_ip($IP);
284 sub setup {
285 # Check and setup iptables table if missing
286 if($cfg->{os} eq 'linux') {
287 system("$cfg->{iptables} -L $cfg->{chain} | grep -qs '$cfg->{chain}'") == 0 ||
288 system("$cfg->{iptables} -N $cfg->{chain}");
290 # Create IP log file if restore block function is on
291 if($cfg->{restore_blocked} == 1) {
292 if( !-e $cfg->{log_ips} ) {
293 open CLOG,">$cfg->{log_ips}" || syslog('notice',"Can't create $cfg->{log_ips}\n");
294 close(CLOG);
299 sub flush {
300 # Flush any existing firewall rules
301 syslog('notice', "Flushing existing rules in $cfg->{chain}.");
302 if($cfg->{os} eq 'linux') {
303 system("$cfg->{iptables} -F $cfg->{chain}") == 0 || syslog('notice', "Unable to flush existing firewalls rules from $cfg->{chain}");
304 } elsif($cfg->{os} eq 'bsd') {
305 system("$cfg->{pfctl} -t $cfg->{chain} -T flush") == 0 || syslog('notice', "Unable to flush existing firewalls rules from $cfg->{chain}");
306 } else {
307 syslog('notice',"No operating system specified in blocksshd.conf configuration file.");
309 # If blocking restore is turned off then clear contents of block
310 # file
311 if($cfg->{restore_blocked} == 0) {
312 if( -e $cfg->{log_ips} && !-z $cfg->{log_ips} ) {
313 unlink($cfg->{log_ips});
318 sub unblock {
319 # unblock old IPs based on timeout
320 $alarmed = 1;
322 if($cfg->{os} eq 'linux') {
323 open IPT, "$cfg->{iptables} -n -L $cfg->{chain} |";
325 while(<IPT>) {
326 chomp;
327 next if ($_ !~ /^DROP/);
328 my ($target, $prot, $opt, $source, $dest, $prot2, $dport) = split(' ', $_);
329 while ( my ($block_ip, $block_time) = each(%timeb) ) {
330 if (($block_ip == $source) && ($block_time < time - $cfg->{unblock_timeout})) {
331 syslog('notice', "Unblocking IP address $block_ip.");
332 system("$cfg->{iptables} -D $cfg->{chain} -p tcp --dport 22 -s $block_ip -j DROP ") == 0 || syslog('notice', "Couldn't unblock $block_ip from firewall.");
333 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
334 unlog_ip($block_ip);
336 delete $timeb{$block_ip};
337 delete $timea{$block_ip};
338 delete $count{$block_ip};
343 close IPT;
345 } elsif($cfg->{os} eq 'bsd') {
346 open IPT, "$cfg->{pfctl} -t $cfg->{chain} -T show|" || syslog('error',"Can't open $cfg->{pfctl} for reading.");
348 while(<IPT>) {
349 s/^\s+//;
350 my $source=$_;
351 while ( my ($block_ip, $block_time) = each(%timeb) ) {
352 if (($block_ip == $source) && ($block_time < time - $cfg->{unblock_timeout})) {
353 syslog('notice', "Unblocking IP address $block_ip.");
354 system("$cfg->{pfctl} -t $cfg->{chain} -T delete $block_ip") == 0 || syslog('notice', "Couldn't unblock $block_ip from firewall.");
355 if( $cfg->{restore_blocked} == 1) {
356 unlog_ip($block_ip);
358 delete $timeb{$block_ip};
359 delete $timea{$block_ip};
360 delete $count{$block_ip};
365 close IPT;
367 } else {
368 die("No operating system specified in blocksshd.conf configuration file.");
371 alarm( ($cfg->{unblock_timeout}/2) );
374 sub loadwhitelist {
375 my $rwhiteList = shift @_; # $cfg->{whitelist}
376 my $sn = Net::Subnets->new;
378 if (ref($rwhiteList) eq 'ARRAY') {
379 my @subnets = map { chomp $_; &trim($_); } @{$rwhiteList};
380 @subnets = grep(!/^#|^$/, @subnets);
381 my $p_sn='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}$';
382 my @bad_subnets = grep(!/$p_sn/, @subnets);
384 if (scalar(@bad_subnets) > 0) {
385 die "The whilelist holds invalid subnet entries: " .
386 join(', ', @bad_subnets) . "\n";
389 @subnets = grep(/$p_sn/, @subnets);
390 $sn->subnets( \@subnets );
393 return $sn;
396 sub trim {
397 my $str=shift @_;
398 $str =~ s/^[\s\r\n]+//;
399 $str =~ s/[\s\r\n]+$//;
400 return $str;
403 sub log_ip {
404 my $IP = shift or syslog('notice',"Can't get ip to log!\n");
405 my $inlist=0;
406 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
407 open LOG,"<$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
408 while(<LOG>) {
409 chomp;
410 if($_ eq $IP) {
411 $inlist=1;
412 last;
415 close LOG;
417 if($inlist == 0) {
418 open LOG,">>$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
419 print LOG "$IP\n";
420 close LOG;
424 sub unlog_ip {
425 my $block_ip = shift or die("Can't get IP to unlog!\n");
426 my @file;
428 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
430 tie @file, 'Tie::File', $cfg->{log_ips};
431 @file=grep { $_ ne $block_ip } @file;
432 untie @file;
434 syslog('notice',"Removed unblocked IP address ($block_ip) from log file $cfg->{log_ips}");
438 sub restore_blocked {
439 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
440 open RLOG,"<$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
441 while(<RLOG>) {
442 chomp;
443 if(/$work->{ipv4}|$work->{fqdn}/i) {
444 syslog('notice',"Blocking IP $_ - previously blocked and saved in $cfg->{log_ips}");
445 system_block($_);
447 else {
448 syslog('notice',"Invalid IP address ($_) found in $cfg->{log_ips}");
451 close (RLOG);
455 sub notify {
456 # send notification emails
457 my ($IP) = shift or die "Missing IP address!\n";
459 syslog('notice', "Sending notification email to $cfg->{email}");
460 my $whois = '';
461 if($cfg->{email_whois_lookup} == 1) {
462 $whois = `$cfg->{whois} $IP|$cfg->{sed} -e 's/\"/\\"/g'`;
464 system("echo \"$work->{hostname}: BlockSSHD blocking $IP\n\n $whois\" | $cfg->{mail} -s 'BlockSSHD blocking notification' $cfg->{email}");
467 sub exithandler {
468 if (-e $cfg->{pid_file})
470 my $pid=`/bin/cat $cfg->{pid_file}`;
471 system("/bin/kill -9 $pid");
472 unlink($cfg->{pid_file});
473 die "BlockSSHD exiting\n";
474 } else {
475 die "BlockSSHD is not running!\n";
479 sub print_help {
480 print "BlockSSHD command line options\n";
481 print "-d | --daemon | --start Start BlockSSHD in daemon mode\n";
482 print "--stop Stop BlockSSHD\n";
483 print "-h | --help Print this help text\n";
484 print "-v | --version Display version\n";