Added features:
[blocksshd_00z.git] / blocksshd
blobdfa6c9371963165eddb03b07484547b47daa2981
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/
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 # Public License for more details.
21 # You should have received a copy of the GNU General Public License along
22 # with this program; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 use strict;
26 use warnings;
28 use Sys::Syslog;
29 use Sys::Hostname;
30 use Tie::File;
31 use File::Tail;
32 use Net::DNS::Resolver;
33 use Net::Subnets;
34 use Getopt::Long;
36 use POSIX qw(setsid);
37 use vars qw($opt_d $opt_h $opt_v $opt_stop);
39 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin';
41 my $version = "1.3";
43 our $cfg;
45 # This is where the configuration file is located
46 require '/etc/blocksshd.conf';
48 my $work = {
49 ipv4 => '(?:\d{1,3}\.){3}\d{1,3}', # regexp to match ipv4 address
50 fqdn => '[\da-z\-.]+\.[a-z]{2,4}', # regexp to match fqdn
51 hostname => hostname, # get hostname
54 $cfg->{'whitelist_prepared'}=&loadwhitelist($cfg->{whitelist});
56 Getopt::Long::Configure('bundling');
57 GetOptions
58 ("start" => \$opt_d, "daemon" => \$opt_d, "d" => \$opt_d,
59 "h" => \$opt_h, "help" => \$opt_h,
60 "v" => \$opt_v, "version" => \$opt_v,
61 "stop" => \$opt_stop);
63 if ($opt_d) {
64 if (-e $cfg->{pid_file})
65 { die "BlockSSHD is already running!\n" }
67 # Fork daemon
68 chdir '/' || die "Can't change directory to /: $!";
69 umask 0;
70 open(STDIN, "+>/dev/null");
71 open(STDOUT, "+>&STDIN");
72 open(STDERR, "+>&STDIN");
73 defined(my $pid = fork) || die "Can't fork: $!";
74 exit if $pid;
75 setsid || die "Can't start a new session: $!";
77 # Record PID
78 open (PID,">$cfg->{pid_file}") || die ("Cannot open BlockSSHD PID file $cfg->{pid_file}!\n");
79 print PID "$$\n";
80 close PID;
83 if ($opt_stop) {
84 exithandler();
87 if ($opt_h) {
88 print_help();
89 exit;
92 if ($opt_v) {
93 print "BlockSSHD version $version\n";
94 exit;
97 openlog('blocksshd', 'pid', 'auth');
99 my $alarmed = 0; # ALRM state
100 my %count = (); # hash used to store total number of failed tries
101 my %timea = (); # hash used to store last time when IP was active
102 my %timeb = (); # hash used to store time when IP was blocked
103 my $res = Net::DNS::Resolver->new;
105 # Watch signals
107 $SIG{'ALRM'} = \&unblock;
108 $SIG{'INT'} = \&exithandler;
109 $SIG{'QUIT'} = \&exithandler;
110 $SIG{'KILL'} = \&exithandler;
111 $SIG{'TERM'} = \&exithandler;
113 # Notify of startup
115 syslog('notice', "Starting BlockSSHD");
117 # Create iptables chain
119 setup();
121 # Clear existing rules
123 flush();
125 # Restore previously blocked rules
127 if($cfg->{restore_blocked} == 1) {
128 restore_blocked();
131 # The core process
133 my $ref=tie *FH, "File::Tail", (name=>$cfg->{logfile},
134 maxinterval=>$cfg->{logcheck},
135 interval=> 10,
136 errmode=> "return");
138 if ( $cfg->{unblock} == 1) {
139 alarm( ($cfg->{unblock_timeout} /2) );
143 # Used because sometimes when the same message appears a lot of times syslog
144 # simply replace the line next to the first message with a :
146 # /var/log/messages:
148 # <month> <day> <hour> <host> sshd[<pid>] Failed password for <USER> from <ip>
149 # <month> <day> <hour> <host> last message repeated 2 times.
151 # this var stores a hash ref to the previous line that contain the line
152 # content, a array ref to the IPs to block and its badness.
153 my $prev_line;
155 while (<FH>)
157 if( $alarmed ) {
158 $alarmed = 0;
159 next;
162 # if the previous line was a bad line
163 if ($prev_line->{'bad'})
165 # `block' it again N times
166 if (my ($times) = /last message repeated ([[:digit:]]+) times/i)
168 map { block($_) } @{$prev_line->{'ip'}} while ($times--);
170 next;
173 # `bad' lines definition:
174 if (
175 /.*Failed (password) .* from ($work->{ipv4}|$work->{fqdn}) port [0-9]+/i ||
176 /.*(Invalid|Illegal) user .* from ($work->{ipv4}|$work->{fqdn})$/i ||
177 /.*Failed .* for (invalid|illegal) user * from ($work->{ipv4}|$work->{fqdn}) port [0-9]+ .*/i ||
178 /.*Failed .* for (invalid|illegal) user .* from ($work->{ipv4}|$work->{fqdn})/i ||
179 /.*(Postponed) .* for .* from ($work->{ipv4}|$work->{fqdn}) port [0-9]+ .*/i ||
180 /.*Did not receive (identification) string from ($work->{ipv4}|$work->{fqdn})$/i ||
181 /.*Bad protocol version (identification) .* from ($work->{ipv4}|$work->{fqdn})$/i ||
182 /.* login attempt for (nonexistent) user from ($work->{ipv4}|$work->{fqdn})$/i ||
183 /.* bad (password) attempt for '.*' from ($work->{ipv4}|$work->{fqdn}):[0-9]+/i ||
184 /.*unknown (user) .* from ($work->{ipv4}|$work->{fqdn}).*/i ||
185 /.*User .* (from) ($work->{ipv4}|$work->{fqdn}) not allowed because.*/i ||
186 /.*USER.*no such (user) found from ($work->{ipv4}|$work->{fqdn}).*/i
189 if($1 || $2)
191 my $IP=$1 unless $2;
192 $IP=$2 if $2;
193 if ( $IP =~ /$work->{fqdn}/i)
195 foreach my $type (qw(AAAA A))
197 my $query = $res->search($IP, $type);
198 if ($query)
200 my @ips;
201 foreach my $rr ($query->answer)
203 block($rr->address);
204 push @ips, $rr->address;
206 $prev_line = {content => $_ , ip => \@ips, bad => 1};
209 } else {
210 block($IP);
211 $prev_line = {content => $_ , ip => [$IP], bad => 1};
214 } else {
215 $prev_line = {content => $_ , ip => undef, bad => 0};
219 closelog();
221 sub block {
222 # Confirm iptables table is created
223 setup();
225 my ($IP) = shift or die "Missing IP address!\n";
227 # check to see if IP address already blocked
229 if($cfg->{os} eq 'linux') {
230 my ($exists) = system("$cfg->{iptables} -n -L $cfg->{chain} | grep -q '$IP'");
231 if ($exists == 0) {
232 return;
235 elsif($cfg->{os} eq 'bsd') {
236 my ($exists) = system("$cfg->{pfctl} -t $cfg->{chain} -T show| grep -q '$IP'");
237 if ($exists == 0) {
238 return;
242 # Reset IP count if timeout exceeded
243 if ($timea{$IP} && ($timea{$IP} < time - $cfg->{timeout})) {
244 syslog('notice', "Resetting $IP count, since it wasn't active for more than $cfg->{timeout} seconds");
245 delete $count{$IP};
247 $timea{$IP} = time;
249 # increase the total number of failed attempts
250 $count{$IP}++;
252 if ($count{$IP} < $cfg->{max_attempts}+1) {
253 syslog('notice', "$IP was logged with a total count of $count{$IP} failed attempts");
255 if ($count{$IP} >= $cfg->{max_attempts}+1) {
256 syslog('notice', "IP $IP reached the maximum number of failed attempts!");
257 system_block($IP);
261 sub system_block {
262 my $IP=shift or die("Can't find IP to block.\n");
263 if (ref($cfg->{'whitelist_prepared'}->check(\$IP)) ne 'SCALAR') {
264 if($cfg->{os} eq 'linux') {
265 syslog('notice', "Blocking $IP in iptables table $cfg->{chain}.");
266 system("$cfg->{iptables} -I $cfg->{chain} -p tcp --dport 22 -s $IP -j DROP") == 0 || syslog('notice', "Couldn't add $IP to firewall");
268 if($cfg->{os} eq 'bsd') {
269 syslog('notice', "Blocking $IP in pf table $cfg->{chain}.");
270 system("$cfg->{pfctl} -t $cfg->{chain} -T add $IP") == 0 || syslog('notice', "Couldn't add $IP to firewall");
272 $timeb{$IP} = time;
273 # send mail if it is configured
274 if ($cfg->{send_email} eq '1') {
275 notify($IP);
277 if ($cfg->{restore_blocked} eq '1') {
278 log_ip($IP);
283 sub setup {
284 # Check and setup iptables table if missing
285 if($cfg->{os} eq 'linux') {
286 system("$cfg->{iptables} -L $cfg->{chain} | grep -qs '$cfg->{chain}'") == 0 ||
287 system("$cfg->{iptables} -N $cfg->{chain}");
289 # Create IP log file if restore block function is on
290 if($cfg->{restore_blocked} == 1) {
291 if( !-e $cfg->{log_ips} ) {
292 open CLOG,">$cfg->{log_ips}" || syslog('notice',"Can't create $cfg->{log_ips}\n");
293 close(CLOG);
298 sub flush {
299 # Flush any existing firewall rules
300 syslog('notice', "Flushing existing rules in $cfg->{chain}.");
301 if($cfg->{os} eq 'linux') {
302 system("$cfg->{iptables} -F $cfg->{chain}") == 0 || syslog('notice', "Unable to flush existing firewalls rules from $cfg->{chain}");
303 } elsif($cfg->{os} eq 'bsd') {
304 system("$cfg->{pfctl} -t $cfg->{chain} -T flush") == 0 || syslog('notice', "Unable to flush existing firewalls rules from $cfg->{chain}");
305 } else {
306 syslog('notice',"No operating system specified in blocksshd.conf configuration file.");
308 # If blocking restore is turned off then clear contents of block
309 # file
310 if($cfg->{restore_blocked} == 0) {
311 if( -e $cfg->{log_ips} && !-z $cfg->{log_ips} ) {
312 unlink($cfg->{log_ips});
317 sub unblock {
318 # unblock old IPs based on timeout
319 $alarmed = 1;
321 if($cfg->{os} eq 'linux') {
322 open IPT, "$cfg->{iptables} -n -L $cfg->{chain} |";
324 while(<IPT>) {
325 chomp;
326 next if ($_ !~ /^DROP/);
327 my ($target, $prot, $opt, $source, $dest, $prot2, $dport) = split(' ', $_);
328 while ( my ($block_ip, $block_time) = each(%timeb) ) {
329 if (($block_ip == $source) && ($block_time < time - $cfg->{unblock_timeout})) {
330 syslog('notice', "Unblocking IP address $block_ip.");
331 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.");
332 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
333 unlog_ip($block_ip);
335 delete $timeb{$block_ip};
336 delete $timea{$block_ip};
337 delete $count{$block_ip};
342 close IPT;
344 } elsif($cfg->{os} eq 'bsd') {
345 open IPT, "$cfg->{pfctl} -t $cfg->{chain} -T show|" || syslog('error',"Can't open $cfg->{pfctl} for reading.");
347 while(<IPT>) {
348 s/^\s+//;
349 my $source=$_;
350 while ( my ($block_ip, $block_time) = each(%timeb) ) {
351 if (($block_ip == $source) && ($block_time < time - $cfg->{unblock_timeout})) {
352 syslog('notice', "Unblocking IP address $block_ip.");
353 system("$cfg->{pfctl} -t $cfg->{chain} -T delete $block_ip") == 0 || syslog('notice', "Couldn't unblock $block_ip from firewall.");
354 if( $cfg->{restore_blocked} == 1) {
355 unlog_ip($block_ip);
357 delete $timeb{$block_ip};
358 delete $timea{$block_ip};
359 delete $count{$block_ip};
364 close IPT;
366 } else {
367 die("No operating system specified in blocksshd.conf configuration file.");
370 alarm( ($cfg->{unblock_timeout}/2) );
373 sub loadwhitelist {
374 my $rwhiteList = shift @_; # $cfg->{whitelist}
375 my $sn = Net::Subnets->new;
377 if (ref($rwhiteList) eq 'ARRAY') {
378 my @subnets = map { chomp $_; &trim($_); } @{$rwhiteList};
379 @subnets = grep(!/^#|^$/, @subnets);
380 my $p_sn='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}$';
381 my @bad_subnets = grep(!/$p_sn/, @subnets);
383 if (scalar(@bad_subnets) > 0) {
384 die "The whilelist holds invalid subnet entries: " .
385 join(', ', @bad_subnets) . "\n";
388 @subnets = grep(/$p_sn/, @subnets);
389 $sn->subnets( \@subnets );
392 return $sn;
395 sub trim {
396 my $str=shift @_;
397 $str =~ s/^[\s\r\n]+//;
398 $str =~ s/[\s\r\n]+$//;
399 return $str;
402 sub log_ip {
403 my $IP = shift or syslog('notice',"Can't get ip to log!\n");
404 my $inlist=0;
405 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
406 open LOG,"<$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
407 while(<LOG>) {
408 chomp;
409 if($_ eq $IP) {
410 $inlist=1;
411 last;
414 close LOG;
416 if($inlist == 0) {
417 open LOG,">>$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
418 print LOG "$IP\n";
419 close LOG;
423 sub unlog_ip {
424 my $block_ip = shift or die("Can't get IP to unlog!\n");
425 my @file;
427 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
429 tie @file, 'Tie::File', $cfg->{log_ips};
430 @file=grep { $_ ne $block_ip } @file;
431 untie @file;
433 syslog('notice',"Removed unblocked IP address ($block_ip) from log file $cfg->{log_ips}");
437 sub restore_blocked {
438 if( -e $cfg->{log_ips} && ((-s $cfg->{log_ips}) > 0)) {
439 open RLOG,"<$cfg->{log_ips}" || syslog('notice',"Can't open $cfg->{log_ips}\n");
440 while(<RLOG>) {
441 chomp;
442 if(/$work->{ipv4}|$work->{fqdn}/i) {
443 syslog('notice',"Blocking IP $_ - previously blocked and saved in $cfg->{log_ips}");
444 system_block($_);
446 else {
447 syslog('notice',"Invalid IP address ($_) found in $cfg->{log_ips}");
450 close (RLOG);
454 sub notify {
455 # send notification emails
456 my ($IP) = shift or die "Missing IP address!\n";
458 syslog('notice', "Sending notification email to $cfg->{email}");
459 my $whois = '';
460 if($cfg->{email_whois_lookup} == 1) {
461 $whois = `$cfg->{whois} $IP|$cfg->{sed} -e 's/\"/\\"/g'`;
463 system("echo \"$work->{hostname}: BlockSSHD blocking $IP\n\n $whois\" | $cfg->{mail} -s 'BlockSSHD blocking notification' $cfg->{email}");
466 sub exithandler {
467 if (-e $cfg->{pid_file})
469 my $pid=`/bin/cat $cfg->{pid_file}`;
470 system("/bin/kill -9 $pid");
471 unlink($cfg->{pid_file});
472 die "BlockSSHD exiting\n";
473 } else {
474 die "BlockSSHD is not running!\n";
478 sub print_help {
479 print "BlockSSHD command line options\n";
480 print "-d | --daemon | --start Start BlockSSHD in daemon mode\n";
481 print "--stop Stop BlockSSHD\n";
482 print "-h | --help Print this help text\n";
483 print "-v | --version Display version\n";