#!/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", "ip=s", "help", "force!" );
unless (  $opts{ip} && ( $opts{ip} =~ /\d+\.\d+\.\d+\.\d+/ ) ) {
  print "You must specify an ip address.\n\n";
  usage();
  exit;
}
die "Can't make --force --perm blocks. Pick one or the other!" if $opts{force} && $opts{perm};

load_cidr($_) for "Cloudflare", "CodeGuard", "Pingdom", "SingularCDN", "SiteLock", "VaultPress";
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}) {
  if(my @cidr = cidrcheck($opts{ip})) {
    die "Won't block ".join("/",@cidr)." ip without --force";
  }
}

add_to_ipset($opts{ip}, $opts{perm}) 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} );
$line .= "blocked $opts{ip}\n";

open my $fh, '>>', '/var/log/firewall-modification.log' or die "Failed to open log file.";
print $fh $line;
close $fh;

sub add_to_ipset {
  my $ip = shift;
  my $perm = shift || undef;
  my $ipset = 'ipdrop-temp';
  $ipset = 'ipdrop' if ( $perm );

  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', '-exist', 'add', $ipset, $ip);
  my @out = <$chld_out>;
  my @err = <$chld_err>;
  close $chld_in;
  close $chld_out;
  close $chld_err;
  waitpid ( $pid, 0 );
  my $stat = $? >> 8;
  return undef unless ( $stat == 0 );
  return 1;
}

sub add_to_ipdrop {
  my $ip = shift;
  open my $fh, '<', '/etc/firewall/conf/ipdrop_global';
  my @ips = <$fh>;
  close $fh;
  chomp @ips;
  if ( grep { /^$ip$/ } @ips ) {
    print "$ip already exists 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;

  if ( grep { /^$ip$/ } @ips ) {
    print "$ip already exists in ipdrop_local\n";
    exit 2;
  }

  push @ips, $ip;
  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 {
  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\n";
  print "Default is to block the IP address for 2 hours. Adding --perm will permanently block the IP address and add it to ipdrop_local.\n";
}

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;
}
