#!/usr/bin/perl

use warnings;
use strict;

use Getopt::Long;
use IPC::Open3;
use DateTime;
use Data::Dumper;
use Socket qw(inet_aton);
my @cidrwarn; # {cidr: string, ip: ip2int(), width: int, who string}

my %opts;
GetOptions(\%opts, "perm", "rbl", "ip=s@", "help", "force!");
usage("You must specify an IP address.") unless $opts{ip};
for (@{$opts{ip}}) {
  usage("Invalid IP: $_") unless /^\d+\.\d+\.\d+\.\d+$/;
}
die "Can't make --force --perm blocks. Pick one or the other!" if $opts{force} && $opts{perm};
die "Can't make --rbl --perm blocks. Pick one or the other!" if $opts{rbl} && $opts{perm};

load_cidr($_) for "Cloudflare", "CodeGuard", "Pingdom", "SingularCDN", "SiteLock", "VaultPress", "Monitoring";
load_cidr("Nginx+", $_) for "/etc/nginx/conf.d/proxyips", "/opt/eig_linux/etc/proxyips";
push @cidrwarn,
  map { {cidr => $_, ip => unpack("N", inet_aton($_)), width => 32, who => "local"} }
  qx(ifconfig) =~ /(?:inet addr:|inet )([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/g;

unless ($opts{force}) {
  my @good;
  for my $ip (@{$opts{ip}}) {
    if (my @cidr = cidrcheck($ip)) {
      warn "Won't block ".join("/",@cidr)." ip $ip without --force\n";
    } else {
      push @good, $ip;
    }
  }
  die "No valid IP addresses to block" unless @good;
  if (@good != @{$opts{ip}}) { # lengths differ
    warn "Blocking remaining valid IPs: ".join(', ', @good)."\n";
    @{$opts{ip}} = @good;
  }
}

add_to_ipset(@{$opts{ip}}) or die "Failed to add @{$opts{ip}} to ipset.";
if ( $opts{perm} ) {
  add_to_ipdrop(@{$opts{ip}}) or die "Added to ipset, but failed to add to ipdrop_local!";
}

my $date = DateTime->now();
$date->set_time_zone( 'America/Chicago' );
my $user = $ENV{'RUSER'} || 'unknown';
my $line = '[' . $date->mdy . ':' . $date->hms . '] ' . $user;
$line .= "PERMANENTLY" if ( $opts{perm} );
open my $fh, '>>', '/var/log/firewall-modification.log' or die "Failed to open log file.";
for (@{$opts{ip}}) {
  print $fh "$line blocked $_\n";
}
close $fh;

sub add_to_ipset {
  my @ips = @_;
  my $ipset = 'ipdrop-temp';
  $ipset = 'ipdrop' if ($opts{perm});
  $ipset = 'ipdrop-rbl' if ($opts{rbl});

  my ($chld_in, $chld_out, $chld_err);
  use Symbol 'gensym'; $chld_err = gensym;
  my $pid = open3($chld_in, $chld_out, $chld_err, '/usr/sbin/ipset', 'restore');
  print {$chld_in} "add $ipset $_ -exist\n" for @ips;
  close $chld_in;
  my @out = <$chld_out>;
  my @err = <$chld_err>;
  close $chld_out;
  close $chld_err;
  waitpid ( $pid, 0 );
  my $stat = $? >> 8;
  return undef unless ( $stat == 0 );
  return 1;
}

sub add_to_ipdrop {
  my %adds = map { $_, 1 } @_;
  open my $fh, '<', '/etc/firewall/conf/ipdrop_global';
  my @ips = <$fh>;
  close $fh;
  chomp @ips;
  for (grep { exists $adds{$_} } @ips) {
    warn "$_ already exists in ipdrop_global\n";
    delete $adds{$_};
  }
  unless (keys %adds) {
    warn "No IPs not already in ipdrop_global\n";
    exit 2;
  }

  @ips = ();
  open $fh, '<', '/etc/firewall/conf/ipdrop_local';
  @ips = <$fh>;
  close $fh;
  chomp @ips;

  # as long as we're going to rewrite ipdrop_local, we may as well clear dupes
  my %temp = map { $_ => 1 } @ips;
  @ips = keys %temp;

  for (grep { exists $adds{$_} } @ips) {
    warn "$_ already exists in ipdrop_local\n";
    delete $adds{$_};
  }
  unless (keys %adds) {
    warn "No IPs not already in ipdrop_global or ipdrop_local\n";
    exit 2;
  }
  push @ips, keys %adds;
  open $fh, '>', '/etc/firewall/conf/ipdrop_local.new';
  print $fh "$_\n" for @ips;
  close $fh;
  rename '/etc/firewall/conf/ipdrop_local.new', '/etc/firewall/conf/ipdrop_local';
}

sub usage {
  my ($msg) = @_;
  print "$msg\n\n" if defined $msg;
  print "blockip - blocks an IP from connecting to the server\n";
  print "\t--ip   - IP address to block\n";
  print "\t--perm - Block IP address permanently\n";
  print "\t--rbl  - Reserved for RBL-managed blcoks\n\n";
  print "Default is to block the IP address for 2 hours.\n";
  print "Adding --perm will permanently block the IP address and add it to ipdrop_local.\n";
  exit 1;
}

sub load_cidr {
  my ($who, $file) = @_;
  $file = "/etc/firewall/conf/".lc($who) unless defined $file;
  if ( open my $f, "<", $file ) {
    while ( defined(my $line = <$f>) ) {
      next unless $line =~ m!^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})(?:/(\d+))?$!;
      my ($ip, $width) = ($1, $2);
      $width = 32 unless defined $width;
      push @cidrwarn, {
        cidr => $width == 32 ? $ip : "$ip/width",
        ip => unpack("N", inet_aton($ip)),
        width => $width,
        who => $who
      };
    }
  }
}

sub cidrcheck {
  my ($ip) = @_;
  my @who;
  $ip = unpack("N", inet_aton($ip));

  for my $cidr (@cidrwarn) {
    my $mask = $ip & (-1 << (32 - $cidr->{width}));
    next unless $mask == $cidr->{ip};
    push @who, $cidr->{who};
  }
  return sort @who;
}
