#scriptname
/root/bin/allowHostsForSomeServices.pl

#!/usr/bin/perl
##########################################################
#
# set firewall rules, for specific ip addresses
#
# run via root cron:
# #update dns
# */5 6-21 * * * /root/bin/allowHostsForSomeServices.pl updateDNS >>/var/log/allowHostsForSomeServices.log
# 58 23 * * * /root/bin/allowHostsForSomeServices.pl >/dev/null
# 59 23 * * * gzip -f /var/log/allowHostsForSomeServices.log >/dev/null
#
#
##########################################################
use strict;
use Socket;

my $param = $ARGV[0];
my $mode=0; # 0 = default
# 1 = update only modus
my @host = ("computer2know.de","sys4com.de" );
my $ipt= '/sbin/iptables';


#get actual rules
my %actualIPHash={};
open(IN,"$ipt -L -n \|awk \{\'print \$4\'\} \|sort -u |");
while(<IN>){
my $line = $_;
chomp($line);
#print "$line.\n";
$actualIPHash{$line}=1;
}
close(IN);

if ($param eq "updateDNS"){
print "mode set to 1";
$mode=1;
}

if ($mode == 0){
print "Flush ipTables Rules\n";
system ("$ipt -F");
}

#check if addresses already exist
my $notexist=0;
if ($mode == 1){
foreach my $hostname (@host){
print "now checking hostname $hostname: ";
if (inet_aton($hostname)){
my $address = inet_ntoa(inet_aton($hostname));
print ("address of hostname ($hostname) is: $address\n");

if (exists $actualIPHash{$address}){
print "IP: $address already exists in FW rule.\n";
}else{
print "IP: $address does not exist in FW rule.\n";
$notexist++;
}
}else{
print "skipping hostname $hostname - since there is no ip for the name!\n";
}
}
}


my $i=0;
foreach my $hostname (@host){
if (! inet_aton($hostname)){
print "skipping hostname $hostname - since there is no ip for the name!\n";
next;
}

my $address = inet_ntoa(inet_aton($hostname));

if ($mode == 1){
if ($notexist > 0){
print "Allow checkmk from source IP $address ($hostname) - update only\n";
$i++; system ("$ipt -D INPUT $i; $ipt -I INPUT $i -p tcp --dport 6556 -s $address -j ACCEPT");
}
}else{
print "Allow checkmk from source IP $address ($hostname)\n";
system ("$ipt -A INPUT -p tcp --dport 6556 -s $address -j ACCEPT");
}
}

system("$ipt -L -n");
exit if $mode == 1;

#allow
#system ("$ipt -A INPUT -p tcp --dport 22 -j ACCEPT");

print "block all others\n";
# Deny all other DNS requests
system("$ipt -A INPUT -p tcp --dport 6556 -j LOG -m limit --limit 12/min --log-level 4 --log-prefix \'IP 6556 INPUT drop: \'");
system("$ipt -A INPUT -p tcp --dport 6556 -j DROP");

computer2know :: thank you for your visit :: have a nice day :: © 2024