#!/usr/bin/perl -w

BEGIN {

    require '/usr/sec/lib/SecBinLog.pm';
    SecBinLog::sb_log(); # Writes an entry to /var/log/legacy/sec-bin.log
}

# Program: devilbanner
# Purpose: Block offensive IPs temporarily
# $Id: userbox_devilbanner.erb,v 1.4 2017/05/22 16:17:28 apayne Exp $

use strict;
use Getopt::Long;
use Fcntl qw( O_RDWR O_CREAT LOCK_EX);
use Sys::Syslog qw(:standard :macros);
use Net::IP qw( ip_is_ipv4 );
use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip );

my $banfile = "/var/cpanel/devilips";
my $expireafter = 7200;
my $release = undef;
my $releaseall = undef;
my $quiet = undef;
my $single = undef;
my $stdin = undef;
my $help = undef;
my $iptables = "/sbin/iptables";
my $iproute2 = "/sbin/ip";
my $conntrack = "/usr/sbin/conntrack";

GetOptions
  "banfile=s" => \$banfile,
  "expire=i" => \$expireafter,
  "release=s" => \$release,
  "release-all" => \$releaseall,
  "singleip" => \$single,
  "stdin" => \$stdin,
  "quiet" => \$quiet,
  "help" => \$help,
  or &help();
&help() if $help;

sub help {
  print "\n$0 [--quiet] [--banfile $banfile ] [ --expire $expireafter ] [--release IP ] [ --release-all ] [--singleip] { --stdin | IPs ... }\n\n";
  exit;
}

# Fire up the logger
openlog('devilbanner', 'cons,pid', 'notice');

if ($release) {
  $release =~ s/\.\d+$/\.0/ unless $single;
  unban($release);
} elsif ($releaseall) {
  my $banned = loadbanned();
  stripbanned();
} else {
  if ($stdin) {
    output("Reading IPs from STDIN.  Hit CTRL-C to abort:");
    while (<STDIN>) {
      chomp;
      my ($banip) = split;
      push @ARGV, $banip;
    }
  }
  if (@ARGV) {
    my $banned = loadbanned();
    foreach my $banip (@ARGV) {
      my $realbanip = $banip;
      $banip =~ s/\.\d+$/\.0/ unless $single;
      if ($banned->{$banip}) {
        output("$banip was already banned.");
      } else {
        $banned->{$banip} = time;
        ban($banip, $realbanip);
      }
    }
    stripbanned();
  } else {
    &help();
  }
}

closelog();

sub loadbanned {
  sysopen (DB, $banfile, O_RDWR | O_CREAT ) or die "$banfile: open: $!\n";
  flock(DB, LOCK_EX) or die "$banfile: flock: $!\n";
  my %banned = ();
  while (<DB>) {
    my ($time,$banip) = split;
    $banned{$banip} = $time;
  }
  return \%banned;
}

sub ban {
  my $ip = shift;
  my $realip = shift;
  unless (ip_is_ipv4($ip)) {
    output("IP [$ip] TOO UGLY TO BAN?");
    return;
  }
  my @localips = `$iproute2 -4 addr show | awk '/inet/ {gsub(/\\/.*/,"",\$2); if (\$2 != "127.0.0.1") print \$2}'`;
  chomp @localips;
  my $dgate = `ip route | awk '/default/ {match(\$0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr(\$0,RSTART,RLENGTH); print ip}'`;
  chomp $dgate;
  unless (ip_is_ipv4($dgate)) {
    output("Could not find default gateway");
    return;
  }
  my $friendly_ip_regex = &gen_friendly_regex();
  if (match_ip($ip, $friendly_ip_regex)) {
    output("IP [$ip] TOO FRIENDLY TO BLOCK!");
    return;
  } elsif (grep(/$ip/, @localips)){
    output("IP [$ip] is local");
    return;
  } elsif ( $ip =~ m/^$dgate$/){
    output("IP [$ip] is default gateway");
    return;
  } elsif ($realip) {
    my ($sip) = $realip =~ /(\d+\.\d+\.\d+\.)/;
    if ($sip and (grep(/$sip/, @localips) or $sip =~ m/^$dgate/)){
      output("IP [$realip] shares a subnet with a local IP. Can only ban with --singleip");
      return;
    }
  }
  print DB time(), " $ip\n";
  my $prefix = ($ip =~ /\.0$/) ? 24 : 32;
  #my @cmd = ($iptables => -I => INPUT => "--src" => "$ip/$prefix" => -j => "DROP");
  my @cmd = ($iproute2 => route => add => blackhole => "$ip/$prefix");
  output("RUNNING: ", join(" ", @cmd));
  system @cmd;
  @cmd = ( $conntrack, "-D", "-s", "$realip");
  output("RUNNING: ", join(" ", @cmd));
  system @cmd;
}

sub unban {
  my $ip = shift;
  my $banned = loadbanned();
  if ($banned->{$ip}) {
    output("Releasing $ip ...");
    stripbanned($ip);
  } else {
    output("$ip was already not banned.");
  }
}


sub stripbanned {
  my $release = shift;
  my $wipe_before = time - $expireafter;
  seek (DB, 0, 0);
  my $CONTENT = "";
  while (<DB>) {
    my ($when, $ip) = split;
    if ($when > $wipe_before and
        (!$release or
         $release ne $ip)) {
      $CONTENT .= $_;
    } else {
      my $prefix = ($ip =~ /\.0$/) ? 24 : 32;
      #my @cmd = ($iptables => -D => INPUT => "--src" => "$ip/$prefix" => -j => "DROP");
      my @cmd = ($iproute2 => route => del => blackhole => "$ip/$prefix");
      output("RUNNING: ",join(" ",@cmd));
      system @cmd;
    }
  }
  seek (DB, 0, 0);
  print DB $CONTENT;
  truncate(DB, length $CONTENT);
  close(DB);
}

sub output {
  my @sure = @_ or die "You have to output something $!";
  my $text = join(' ', @sure);
  syslog(LOG_ERR, $text);
  print STDERR "$text\n" unless $quiet;
  return 1;
}

# net ipblock_list select cidr
sub gen_friendly_regex {
  my @net_ip_range = (
    '0.0.0.0/8',
    '127.0.0.0/8',
    '10.0.0.0/8',
    '103.21.58.0/23',
    '103.224.23.0/24',
    '108.167.128.0/22',
    '108.167.132.0/24',
    '108.167.133.0/26',
    '108.167.133.128/25',
    '108.167.134.0/23',
    '108.167.136.0/23',
    '108.167.138.0/23',
    '108.167.140.0/22',
    '108.167.144.0/20',
    '108.167.160.0/24',
    '108.167.161.0/24',
    '108.167.163.0/24',
    '108.167.164.0/22',
    '108.167.168.0/22',
    '108.167.172.0/22',
    '108.167.176.0/22',
    '108.167.180.0/22',
    '108.167.184.0/22',
    '108.167.188.0/22',
    '108.179.192.0/22',
    '108.179.196.0/22',
    '108.179.200.0/22',
    '108.179.204.0/23',
    '108.179.206.0/23',
    '108.179.208.0/20',
    '108.179.224.0/22',
    '108.179.228.0/22',
    '108.179.232.0/22',
    '108.179.236.0/22',
    '108.179.240.0/21',
    '108.179.248.0/22',
    '108.179.252.0/23',
    '108.179.254.0/24',
    '108.179.255.0/26',
    '108.179.255.128/26',
    '108.179.255.192/26',
    '108.179.255.64/26',
    '142.4.0.0/19',
    '162.144.0.0/16',
    '162.214.0.0/15',
    '162.240.0.0/15',
    '169.57.166.128/27',
    '169.57.166.232/29',
    '172.16.0.0/12',
    '173.254.0.0/17',
    '192.163.192.0/19',
    '192.163.224.0/19',
    '192.168.0.0/16',
    '192.185.0.0/16',
    '192.232.192.0/18',
    '192.254.128.0/17',
    '198.154.192.0/20',
    '198.154.208.0/20',
    '198.154.224.0/19',
    '198.1.64.0/18',
    '198.20.224.0/20',
    '198.20.240.0/21',
    '198.20.248.0/22',
    '198.20.252.0/22',
    '198.57.128.0/17',
    '199.58.196.0/22',
    '207.174.212.0/24',
    '216.12.194.43/32',
    '216.172.160.0/24',
    '216.172.161.0/24',
    '216.172.162.0/23',
    '216.172.164.0/22',
    '216.172.168.0/22',
    '216.172.172.0/23',
    '216.172.174.0/23',
    '216.172.176.0/22',
    '216.172.180.0/22',
    '216.172.184.0/21',
    '50.116.104.0/22',
    '50.116.108.0/22',
    '50.116.112.0/22',
    '50.116.116.0/22',
    '50.116.120.0/22',
    '50.116.124.0/22',
    '50.116.64.0/21',
    '50.116.72.0/22',
    '50.116.76.0/22',
    '50.116.80.0/20',
    '50.116.96.0/21',
    '50.87.0.0/16',
    '66.147.240.0/20',
    '67.20.64.0/18',
    '67.222.32.0/19',
    '69.195.64.0/18',
    '69.89.16.0/20',
    '70.40.192.0/19',
    '74.220.192.0/19',
    '96.125.160.0/20',
  );
  my $net_regex = create_iprange_regexp(@net_ip_range);
  return $net_regex;
}
