Last active
July 8, 2022 01:05
-
-
Save techouse/fa47326f466e1cd1d982abce1a0c3b69 to your computer and use it in GitHub Desktop.
Ban whole countries with iptables and Perl. I wrote this script cause modern software like ipset doesn't work and/or exist on older machines running CentOS/RHEL 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use LWP::Simple; | |
use File::Basename; | |
use IO::File; | |
my $debug = 0; | |
my $restore = defined $ARGV[0] && $ARGV[0] eq '--restore' ? 1 : 0; # optional --restore command line argument | |
my $config_file = dirname(__FILE__) . '/iptables_configuration.txt'; | |
my $base_url = 'http://www.ipdeny.com/ipblocks/data/countries'; | |
my @countries = qw/af br in kp mx my pk ro ru tr ua ve vn/; # list the countries you want to ban here | |
if ($restore && -e $config_file) { | |
print "RESTORING CONFIGURATION\n"; | |
system("/sbin/iptables-restore < $config_file"); | |
} | |
for my $country (@countries) { | |
my $banned_cmd = q#-L -n | /bin/awk '$1=="DROP" && $4!="0.0.0.0/0" { print $4 }' | /bin/sort | /usr/bin/uniq#; | |
my @banned_ips = split "\n", `/sbin/iptables $banned_cmd`; | |
my %banned; | |
my $check_banned_ips = 0; | |
if (scalar @banned_ips > 0) { | |
$check_banned_ips = 1; | |
$banned{$_} = 1 for @banned_ips; | |
} | |
printf "BANNING %s\n", uc $country; | |
my $banned_counter = 0; | |
$country = lc $country; | |
my @ips = split "\n", get("${base_url}/${country}.zone"); | |
if (scalar @ips != 0) { | |
for my $ip (@ips) { | |
next if length $ip <= 0 || ($check_banned_ips && $banned{$ip}); | |
print "/sbin/iptables -A INPUT -s $ip -j DROP\n" if $debug; | |
my $result = system("/sbin/iptables -A INPUT -s $ip -j DROP > /dev/null"); | |
if ($result != 0) { | |
print "X: ($result) iptables -A INPUT -s $ip -j DROP\n"; | |
} else { | |
printf "\tbanned:\t%s\n", $ip if $debug; | |
$banned_counter++; | |
} | |
} | |
if ($banned_counter) { | |
printf "APPLYING %d RULES FOR %s\n", $banned_counter, uc $country; | |
system("/sbin/service iptables save"); | |
} | |
} | |
} | |
if (my $config = IO::File->new($config_file, 'w')) { | |
print "SAVING CONFIGURATION"; | |
print $config `/sbin/iptables-save`; | |
$config->close; | |
} | |
print "DONE!\n"; | |
exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment