Hi everybody,
here is a script i found that keeps most Chinese and Russian hackers off my system.
To find more information about this script visit http://ipinfodb.com
With this script you have the possibility to block a list of whole countrys.
You could also specify ports that should still be accessible.
To get it up an runnig do the following:
touch /usr/bin/blockcountry.sh
chmod 755 /usr/bin/blockcountry.sh
copy this into the new file:
Now all you have to do is run the script.
To automatically execute it weekly you cou add the following script to /etc/cron.weekly folder:
cheers
Axel
here is a script i found that keeps most Chinese and Russian hackers off my system.
To find more information about this script visit http://ipinfodb.com
With this script you have the possibility to block a list of whole countrys.
You could also specify ports that should still be accessible.
To get it up an runnig do the following:
touch /usr/bin/blockcountry.sh
chmod 755 /usr/bin/blockcountry.sh
copy this into the new file:
#!/bin/bash
### IpInfoDB iptables countries block bash script###
### Slightly modified script from http://www.cyberciti.biz
### Countries code available : http://ipinfodb.com/country.txt ###
### Block all traffic from RUSSIA (RU) and CHINA (CN). Use ISO code ##
ISO="RU CN"
### Set PATH ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep
ZONEROOT="/root/iptables/"
IPTCBRESTORE="/root/iptables/iptables.cb"
### Network config ###
####change this to reflect your servers wan interface ###
IPTCBDEVICE=eth0
### Uncomment this to add exceptions from the blocking i.e. allow blocked countrys access to specific ports ###
#ALLOWPORTS=80,443
#ALLOWSUBNET=192.168.0.0/255.255.0.0
### No editing below ###
CBLIST="countrydrop"
MAXZONEAGE=6
DLROOT="http://ipinfodb.com/country_query_test.php?country="
cleanOldRules(){
$IPT -L $CBLIST > /dev/null 2>&1
if [ $? = 0 ] ; then
$IPT -D INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST
$IPT -D OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST
$IPT -D FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST
fi
$IPT -F $CBLIST
$IPT -X $CBLIST
for i in `$IPT -L -n | grep Chain | cut -f 2 -d ' ' | grep '\-$CBLIST'`
do
$IPT -F ${i}
$IPT -X ${i}
done
}
updateZoneFiles() {
ZONEARCH=${ZONEROOT}/arch
mkdir -p ${ZONEARCH}
find ${ZONEROOT} -maxdepth 1 -mindepth 1 -ctime +${MAXZONEAGE} -exec mv {} ${ZONEARCH} \;
for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone
if [ -f $tDB ] ; then
printf "Zone file %s is new enough - no update required.\n" $tDB
else
# get fresh zone file if it is newer than MAXZONEAGE days
$WGET -O $tDB $DLROOT$c
fi
done
oldzones=`find ${ZONEROOT} -mindepth 1 -maxdepth 1 -type f -exec basename {} \; | cut -f 1 -d '.'`
# Archive old zones no longer blocked
for z in $oldzones ; do
archme=${c}
for c in $ISO ; do
if [ $c = $z ] ; then archme="X"; fi
done
if [ $archme = $z ] ; then
mv ${archme} ${ZONEARCH}
else
printf "Working from previous zone file for %s\n" ${z}
fi
done
}
createIPTLoadFile() {
printf "# Generated by %s on" $0 > ${IPTCBRESTORE}
printf "%s " `date` >> ${IPTCBRESTORE}
printf "\n*filter\n" >> ${IPTCBRESTORE}
# Create CBLIST chain
printf ":$CBLIST - [0:0]\n" >> ${IPTCBRESTORE}
printf "%s INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST\n" "-I" > ${IPTCBRESTORE}.tmp
printf "%s OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST\n" "-I" >> ${IPTCBRESTORE}.tmp
printf "%s FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST\n" "-I" >> ${IPTCBRESTORE}.tmp
if [ "Z${ALLOWPORTS}" = "Z" ] ; then
printf "Blocking all traffic from country - no ports allowed\n"
else
printf "%s $CBLIST -p tcp -m multiport --dports ${ALLOWPORTS} -j RETURN\n" "-I">> ${IPTCBRESTORE}.tmp
fi
if [ "Z${ALLOWSUBNET}" = "Z" ] ; then
printf "Blocking all traffic from country - no subnets excluded\n"
else
printf "%s $CBLIST -s ${ALLOWSUBNET} -j RETURN\n" "-I">> ${IPTCBRESTORE}.tmp
fi
for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone
# country specific log message
SPAMDROPMSG="iptables: ${c}-Country-Drop: "
# Create drop chain for identified packets
CBLISTDROP=${c}-${CBLIST}-DROP
printf ":${CBLISTDROP} - [0:0]\n" >> ${IPTCBRESTORE}
printf "%s ${CBLISTDROP} -j LOG --log-prefix \"$SPAMDROPMSG\"\n" "-A" >> ${IPTCBRESTORE}.tmp
printf "%s ${CBLISTDROP} -j DROP\n" "-A" >> ${IPTCBRESTORE}.tmp
# Load IP ranges into chains correlating to first octet
BADIPS=$(egrep -v "^#|^$" $tDB)
for ipblock in $BADIPS
do
topip=`echo $ipblock | cut -f 1 -d '.'`
chainExists=`grep -c :${topip}-${CBLIST} ${IPTCBRESTORE}`
if [ $chainExists = 0 ] ; then
printf "Creating chain for octet %s\n" ${topip}
printf ":$topip-$CBLIST - [0:0]\n" >> ${IPTCBRESTORE}
sip=${topip}.0.0.0/8
printf "%s $CBLIST -s ${sip} -j $topip-$CBLIST\n" "-A" >> ${IPTCBRESTORE}.tmp
fi
printf " Adding rule for %s to chain for octet %s\n" ${ipblock} ${topip}
printf "%s $topip-$CBLIST -s $ipblock -j ${CBLISTDROP}\n" "-A" >> ${IPTCBRESTORE}.tmp
done
done
cat ${IPTCBRESTORE}.tmp >> ${IPTCBRESTORE} && rm -f ${IPTCBRESTORE}.tmp
printf "COMMIT\n# Completed on " >> ${IPTCBRESTORE}
printf "%s " `date` >> ${IPTCBRESTORE}
printf "\n" >> ${IPTCBRESTORE}
}
directLoadTables() {
# Create CBLIST chain
$IPT -N $CBLIST
$IPT -I INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST
$IPT -I OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST
$IPT -I FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST
if [ "Z${ALLOWPORTS}" = "Z" ] ; then
printf "Blocking all traffic from country - no ports allowed\n"
else
$IPT -I $CBLIST -p tcp -m multiport --dports ${ALLOWPORTS} -j RETURN
fi
if [ "Z${ALLOWSUBNET}" = "Z" ] ; then
printf "Blocking all traffic from country - no subnets allowed\n"
else
$IPT -I $CBLIST -s ${ALLOWSUBNET} -j RETURN
fi
for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone
# country specific log message
SPAMDROPMSG="$c Country Drop"
# Create drop chain for identified packets
CBLISTDROP=${c}-${CBLIST}-DROP
$IPT -N ${CBLISTDROP}
$IPT -A ${CBLISTDROP} -j LOG --log-prefix "$SPAMDROPMSG"
$IPT -A ${CBLISTDROP} -j DROP
# Load IP ranges into chains correlating to first octet
BADIPS=$(egrep -v "^#|^$" $tDB)
for ipblock in $BADIPS
do
topip=`echo $ipblock | cut -f 1 -d '.'`
$IPT -L $topip-$CBLIST > /dev/null 2>&1
if [ $? = 1 ] ; then
printf "Creating chain for octet %s\n" ${topip}
$IPT -N $topip-$CBLIST
sip=${topip}.0.0.0/8
$IPT -A $CBLIST -s ${sip} -j $topip-$CBLIST
fi
printf " Adding rule for %s to chain for octet %s\n" ${ipblock} ${topip}
$IPT -A $topip-$CBLIST -s $ipblock -j ${CBLISTDROP}
done
done
}
loadTables() {
createIPTLoadFile
${IPT}-restore -n ${IPTCBRESTORE}
#directLoadTables
printf "Country block instituted for: %s\n" "$ISO"
}
# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT
# clean old rules
cleanOldRules
# update zone files as needed
updateZoneFiles
# create a new iptables list
loadTables
exit 0
Now all you have to do is run the script.
To automatically execute it weekly you cou add the following script to /etc/cron.weekly folder:
#!/bin/bash
blockcountry.sh
exit 0
cheers
Axel
In Firewall
Share this post:
Responses (132)
-
Accepted Answer
I've now put it into a proper Howto in the Knowledgebase
@John, it looks like my script has moved on a bit from when I posted. MAXELEM is now parameterised. This is a trivial change and you don't need it. I've also set it to e-mail me if the update fails.
Also writing it up has shown a stupidity in my firewall rules. You can remove:
from the firewall rules. This should have been replaced by:-m state --state NEW
And not supplemented with it.-m conntrack --ctstate NEW
-
Accepted Answer
My firewall rules appear to be quite simple:
I am not blocking any outbound traffic and I am not sure if you even need the "! --sport 25" but I am not confident of how SMTP works.if [ "`lsmod | grep ip_set`" = "" ]; then
modprobe ip_set
fi
# Block non-RIPE and other country addresses
ipset create country-list nethash --hashsize 3456 -exist
iptables -N COUNTRY_BLOCK > /dev/null 2>&1
#comment out the next line if you do not want any firewall logging
iptables -A COUNTRY_BLOCK -j LOG --log-level INFO --log-prefix "COUNTRY_BLOCK: "
iptables -A COUNTRY_BLOCK -j DROP
iptables -I INPUT -i eth0 -m set --match-set country-list src -p tcp -m multiport --dports 443,587,993 -m state --state NEW -j COUNTRY_BLOCK
Note that some of this blocking is an illusion of security. If you have not opened your firewall you don't need any blocks. This is why I am just blocking three ports. The rest are not open so not vulnerable (not quite true, but I have other stuff securing IPsec and OpenVPN requires certificates)
My current script (in /etc/cron.monthly) is:
Note the extra couple of lines at the end which adds "-exist" to all the ipset-save rules which stops errors if there are timing errors during boot up (sometimes cron.monthly can fire before the "ipset restore" is done from the rc.local file so when the restore happens the rules already exist).#!/bin/bash
# A list of the ISO country codes can be found at http://en.wikipedia.org/wiki/ISO_3166-1
# Use lower case for this script
ISO="ae al am az by il iq ir jo kg kw kz lb om qa ro ru sa sy tj tm tr ua uz ye"
cd /usr/tmp
rm -f *.zone
rm -f all-zones.tar.gz
# Download the file
if ! wget http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz -q ;
then
exit 1
fi
tar xzf all-zones.tar.gz --wildcards '*.zone' > /dev/null
# Check if ipset is loaded. If not, load it
if [ "`lsmod | grep ip_set`" = "" ]; then
modprobe ip_set
fi
# Destroy country-list-temp in case it exists and is populated
ipset destroy -q country-list-temp
# Make sure the new lists exist
ipset create country-list nethash --hashsize 65536 -exist
ipset create country-list-temp nethash --hashsize 65536 -exist
for COUNTRY in $ISO ; do
if [ -f $COUNTRY.zone ] ; then
# Load the country list
while read line
do
ipset -A -exist country-list-temp $line
done < $COUNTRY.zone
fi
done
# Make the temp list current
ipset swap country-list country-list-temp
# Destroy the new temp list
ipset destroy -q country-list-temp
rm -f *.zone
rm -f all-zones.tar.gz
ipset save country-list > /usr/src/ipset_country-list.save
sed -i 's/create/create -exist/g' /usr/src/ipset_country-list.save
sed -i 's/add/add -exist/g' /usr/src/ipset_country-list.save
In /etc/rc.d/rc.local I have:
Note that I modprobe everywhere as I've no idea which one will fire first!# Load in all previously saved ipset sets
if [ "`lsmod | grep ip_set`" = "" ]; then
modprobe ip_set
fi
ipset restore < /usr/src/ipset_country-list.save
If you feel really keen, you can try to consolidate the subnets with code something like:
Then throw the resulting country_list into the earlier script replacing:#!/bin/bash
ISO="ae al am az by il iq ir jo kg kw kz lb om qa ro ru sa sy tj tm tr ua uz ye"
# Assemble list of IP addresses and sort it in ascending order
rm -f country_list.temp
touch country_list.temp
for COUNTRY in $ISO ; do
if [ -f $COUNTRY.zone ] ; then
# Load the country list
cat $COUNTRY.zone >> country_list.temp
fi
done
sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n country_list.temp > country_list
rm -f country_list.temp
CHANGED=1
while [ $CHANGED = 1 ] ; do
IP1=
MASK1=
SUBNET1=
touch country_list.temp
CHANGED=0
while read SUBNET2 ; do
IP2=${SUBNET2%/*}
MASK2=${SUBNET2#*/}
NEWMASK=$[MASK2 - 1]
if [[ "$MASK1" = "$MASK2" ]] ; then
if [[ `ipcalc -n $IP1/$NEWMASK` = `ipcalc -n $IP2/$NEWMASK` ]] ; then
# if [[ `ipcalc -b $IP1/$NEWMASK` = `ipcalc -b $IP2/$NEWMASK` ]] ; then
SUBNET1=$IP1/$NEWMASK
IP2=
MASK2=
SUBNET2=
CHANGED=1
# fi
fi
fi
if [ -n "$SUBNET1" ] ; then
echo $SUBNET1 >> country_list.temp
fi
SUBNET1=$SUBNET2
IP1="$IP2"
MASK1="$MASK2"
done < country_list
if [ -n "$SUBNET1" ] ; then
echo $SUBNET1 >> country_list.temp
fi
rm -f country_list
mv country_list.temp country_list
done
with something like (untested):for COUNTRY in $ISO ; do
if [ -f $COUNTRY.zone ] ; then
# Load the country list
while read line
do
ipset -A -exist country-list-temp $line
done < $COUNTRY.zone
fi
done
while read line
do
ipset -A -exist country-list-temp $line
done < country_list
Note if you quote this post you should see all the indenting which the forum otherwise strips out.
Also note you need to install ipset:yum install ipset --enablerepo=clearos-core
-
Accepted Answer
-
Accepted Answer
Hi Axel.
Couple of questions for you.
I don't know much about coding. I got lost in your script above. So my apology for asking what might be a stupid question.
What happens to the existing block lists from the webconfig? Do they get overwritten?
Have you looked at http://www.ipdeny.com/ipblocks/ ? It looks like they have lists updated each day that might be a bit easier to download?
Is there a reason why you chose ipinfodb.com instead?
Thanks and regards! -
Accepted Answer
Hi Nuke.
The script will not modify webconfigs existing block list. It will create additional rules.
The reason i use this script is the ease of use.
The link you provided just provides a list of ip ranges which you somehow have to incorporate into COS / iptables for them to work.
My script provides the whole automated process.
What the script does:
The script will check if the blocklist is older than 6 days. If it is older or does not exist it will AUTOMATICALLY download the blocklist.
Then it will automatically add or update the blocking rules for all downloaded ip ranges to / in iptables.
So all you have to do is put the ISO codes for the country you want to block in the script and make your system call the script during boot and once a week.
By the way, this is a for blocking whole countrys and the ip ranges don't change very often.
That is the reason why a weekly update should be enough.
cheers
Axel -
Accepted Answer
-
Accepted Answer
-
Accepted Answer
-
Accepted Answer
Thank you Axel.
Where I was getting confused was about cron.weekly and what I read about cron and crontab. I thought that you meant to put this shell script into the cron file.
Something like:
0 2 * * sun /usr/bin/blockcountry.sh >> /dev/null 2>&1
i.e. run "blockcountry.sh" at 02:00 on Sunday, send output to black hole.
Is there a reason you chose to put a small script into cron.weekly instead of into the crontab?
Thanks again. -
Accepted Answer
Axel,
I'm getting an error message using the script.
Would you mind having a look at this and tell me what I've done wrong? I get this from the email.
/etc/cron.weekly/updateblockrules:
iptables: No chain/target/match by that name
iptables: No chain/target/match by that name
mv: cannot move `/root/iptables/arch' to a subdirectory of itself, `/root/iptables//arch/arch'
At the end it saysCountry block instituted for: RU CN
So I think it is working OK. -
Accepted Answer
Sweet. I'm going to try to find time this week to implement it in reverse (default policy block, switch the DROPs to ACCEPTs) so one can reject traffic from everywhere except the specified countries. This could cut down a lot on automated attacks where, say, you have a VPN gateway you may connect to from many different or unforseen IPs but you know at the very least they will always be in Canada. -
Accepted Answer
It was easier than it looked. I don't have enough free IPs to test 1-1 NAT but going by pings to the external side of a gateway mode ClearOS VM I'm pretty sure I got it right; two networks in Canada could reach it but neither of the two in the states I tried could. My headquarters subnet was not in the list of Canadian addresses so I would advise anyone who wants to play with this to add their public subnet/host to ALLOWSUBNET (single hosts have netmask 255.255.255.255) for good measure.
To install, dump this into your shell:
wget http://foxpa.ws/dist/geofence.sh
mv geofence.sh /usr/sbin
chmod +x /usr/sbin/geofence.sh
touch /etc/cron.weekly/geosync
chmod +x /etc/cron.weekly/geosync
nano /usr/sbin/geofence.sh
Change the variables to reflect your environment, save the script then nano /etc/cron.weekly/geosync and paste in:
#!/bin/bash
/usr/sbin/geofence.sh
exit 0 -
Accepted Answer
The script ran with errors today.Connecting to ipinfodb.com|67.212.74.82|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2010-09-26 04:24:17 ERROR 404: Not Found.
It looks like you will have to update the line:
### Old line ### DLROOT="http://ipinfodb.com/country_query_test.php?country="
to
DLROOT="http://ipinfodb.com/country_query.php?country="
-
Accepted Answer
A quick request for help in updating this script.
ipinfodb.com has changed the way to access the database.
Old line that worked until today:
DLROOT="http://ipinfodb.com/country_query.php?country="
According to the ipinfodb.com website the new code should be something like:
DLROOT="http://api.ipinfodb.com/v2/ip_query_country.php?key=<your_api_key>&ip=74.125.45.100"
I somehow have to get the "country=" part into this, I think, but I'm not sure.
Could someone give me some suggestions on how to update the script?
Thanks. -
Accepted Answer
replace it with:
DLROOT="http://api.ipinfodb.com/v2/ip_query_country.php?key=<your_api_key>&ip=74.125.45.100&country="
the script appends the countries extentions to the sting. -
Accepted Answer
-
Accepted Answer
Thanks, that worked great!
Sorry, spoke too soon.
I've got an error that I have to investigate:
iptables-restore v1.3.5: error creating chain '<CountryCode></CountryCode>-countrydrop':Invalid argument
Error occurred at line: 141
Try `iptables-restore -h' or 'iptables-restore --help' for more information.
-
Accepted Answer
Sorry Brian, I'm not sure what you mean by saying it expects two fields. The two digit code for the United States is "US". Isn't this what you are using?
I noticed that I've added a few comments and when I replaced the above line of code I commented it out. Both the old line and new line cause the same error.
Line 141, the code having the problem is:
$IPT -I OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST
Figuring out what the problem is beyond my limited coding experience. I'll have to do some learning. -
Accepted Answer
Hi Axel,
great script! Made an extra script to grep logfiles for blocks and summarize it in the mail. Everytime surprised about numbers of "foreign visitors".
But....
the scripts also blocks the "syn acks" for connections initiated from the host the script runs on.
In other words: if I block connections from Russia, I can't access hosts in the RU-zone either.
Can you point me in the right direction for changing your script to fix this? (Or update is for me..? ;-)
thanks,
rolf -
Accepted Answer
-
Accepted Answer
-
Accepted Answer
Does this still work? Also, will it prevent me from accessing sites hosted in blocked countries, or will it only impact incoming traffic?
I found this while looking up how to block an entire country using IPtables: http://www.cyberciti.biz/faq/block-entier-country-using-iptables/ Not sure how much use it'll be, but I'm putting this on my ClearOS todo list. -
Accepted Answer
Yes, still works, use it on my box.
Weekly updates, and daily report of results:
Gisteren, Sep 26 zijn er 49 connecties uit Rusland geblokt.
Gisteren, Sep 26 zijn er 0 connecties uit China geblokt.
Gisteren, Sep 26 zijn er 0 connecties uit Taiwan geblokt.
Gisteren, Sep 26 zijn er 16 connecties uit India geblokt.
Gisteren, Sep 26 zijn er 4 connecties uit Indonesie geblokt.
Gisteren, Sep 26 zijn er 0 connecties uit Oekraine geblokt.
And no, it doesn't prevent you from accessing sites in those countries. It only blocks traffic from these countries. -
Accepted Answer
-
Accepted Answer
Well, the report is quite simple.
I've made a script that reads /var/log/messages and turns it into a mail.
The script is run daily from cron, so every morning I get a report on how many evil kiddies have been blocked.
The script:
#! /bin/bash
########################################
# juli 2010
# rolf@
# /var/log/messages greppen op blokkades uit de as van het kwaad
# Zie http://www.google.com/postini/threat_network.html voor spamlanden
# en greppen op spam
########################################
gisteren=`date +'%b %d' -d yesterday`
Drop_RU=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep RU-Country-Drop |wc -l)
Drop_CN=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep CN-Country-Drop |wc -l)
Drop_TW=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep TW-Country-Drop |wc -l)
Drop_IN=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep IN-Country-Drop |wc -l)
Drop_ID=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep ID-Country-Drop |wc -l)
Drop_UA=$(grep -i "`date +'%b %e' -d yesterday`" /var/log/messages* |grep UA-Country-Drop |wc -l)
echo "Gisteren, $gisteren zijn er $Drop_RU connecties uit Rusland geblokt."
echo "Gisteren, $gisteren zijn er $Drop_CN connecties uit China geblokt."
echo "Gisteren, $gisteren zijn er $Drop_TW connecties uit Taiwan geblokt."
echo "Gisteren, $gisteren zijn er $Drop_IN connecties uit India geblokt."
echo "Gisteren, $gisteren zijn er $Drop_ID connecties uit Indonesie geblokt."
echo "Gisteren, $gisteren zijn er $Drop_UA connecties uit Oekraine geblokt."
~
Script is partly in Dutch, but I guess you'll understand what it reads.
For every country blocked (and to be reported) you add an extra line, but since this is (for me though) quite stable, that isn't a big deal. -
Accepted Answer
Brian wrote:
replace it with:
DLROOT="http://api.ipinfodb.com/v2/ip_query_country.php?key=<your_api_key>&ip=74.125.45.100&country="
the script appends the countries extentions to the sting.
I tried this in the original blockcountry.sh script, but it does not do what is required for the script - instead, the ip_query_country.php script checks what zone the ip=74.125.45.100 is in. If you don't include an ip=, the script checks what country your system IP is in - the IP your Internet traffic is sourced from when you run the query, in other words.
I got the original script to work with this query:
DLROOT="http://ipinfodb.com/country_query.php?country="
If you'd like to see this in action, go here in your favorite web browser http://ipinfodb.com/ip_country_block.php and pick a country from the list.
I have not tried the weekly update in cron yet, nor the neat mail script I see in here, that's next! -
Accepted Answer
after installing wget / screen onto my clearos system I edited the file with my API Key and changed ISO "xx xx xx xx xx xx" with all the countried I wish to block. I edited the /etc/cron.weekly/geofence file and and then ran the script /usr/sbin/geofence.sh
The screen came to life spitting out all sorts of stuff about adding iptables for the countries.
I then logged onto the clearos webgui but I was unable to see any of the imported stuff under the firewall settings.
I was wondering if I did something wrong or if anyone knew of a way I could see if infact the selected countries are blocked.
Thanks in advance. -
Accepted Answer
The firewall screens only show firewall rules added through them. You will not see any rules where you are adding them by a script. You can run the commands "iptables -L -n -v" and "iptables -t nat -L -n -v" to see them (and all the other rules) if you want.
Note that I would be wary of blocking OUTPUT or FORWARD messages to some countries. You may want to, for example, go to the Foxconn web site to see something about a motherboard, but a China block would block this. To me, the main thing is to block the INPUT chain because this is what is hit by unsolicited traffic. -
Accepted Answer
here is what I got for a script, if you would be as kind as to let me know if I am even doing this right.
I just want to block them from accessing or even trying to access my clearos system, if someone on my network wants to access them thats fine by me.
I replaced my API key with < API KEY GOES HERE > just incase someone was wondering lol
Thanks in advance.
-
Accepted Answer
I've no idea if you re doing it right, I'm afraid. You'll have to try and learn. I'd still not write any rules for the OUTPUT or FORWARD chain (but the rules with a -D are OK).
Also, not having read the script or thread fully, I'd also like to know how the script works with a firewall restart. I have a feeling you'd lose all your country blocks. I would look at splitting the script into two. The first bit of the script would be to do the downloading and the creation of the rules files. There would then be a seconf bit which executed the rules. The second file should be called from /etc/clearos/firewall.d/local so that any time the firewall is restarted, the block rules are added to the firewall. The first script as its last command should either call the second script, or better, fire off a "service firewall restart". -
Accepted Answer
I had no need to use the api key, in fact found that the process did not work as expected with that command. I have the script working fine with the dlroot command set like this:
DLROOT="http://ipinfodb.com/country_query.php?country="
Every time you restart the firewall from the gui, the rules created by the script are overwritten. I have created a script in /etc/cron.hourly to re-apply the block.
touch /etc/cron.hourly/updatecountryblock
chmod 755 /etc/cron.hourly/updatecountryblock
From there, I simply called the script I have in /usr/bin by editing /etc/cron.hourly/updatecountryblock and puttting the following in it:
#!/bin/bash
/usr/bin/blockcountry
exit 0
In order to verify that the rules are in place, assuming you've left the original script alone, you can grep for countrydrop:
iptables -n -v -L | grep countrydrop
If you've blocked any countries, you should see a fairly long list of block rules.
If you want to see how old your list of blocked countries is, the best way I've found is to list the contents of /root/iptables and check the dates on the files.
ls -al /root/iptables
I modified the script to update anything older than 3 days - I think the default was 5? I was having issues with new IP's being added to Russia and China more often than every 5 days, and attacks coming form the new IP's. Three days seemed to make this work better.
One thing I did not know when creating the script in cron.hourly was that it would not run if the script had an extention - I originally used updatecountryblock.sh, and while I could run it manually, it would not run hourly. I suspect this is a n00b mistake on my part, but I figured if I ran into it, someone else might too. Might as well mention it.
There is probably a better way to do what I've done, and if anyone has any ideas, I'm open to hearing them. Every now and then the script in /etc/cron.hourly runs, but the rules don't get updated, and the next time the firewall restarts the country blocking stops. I have to either run the script manually when that happens, or go through and delete the country files in /root/iptables and run he script manually to get things going again. Fair warning -
Accepted Answer
I gave you the better way! The script needs splitting in two. One to create the rules and one to apply them. The one to apply them needs to be called from /etc/clearos/firewall.d/local so it is called every time the firewall restarts. The one to create them does not need to run so often (weekly?). If you run your script hourly will the download server complain at you updating so often?
If you work out how, I think you just want to run the "loadTables" function the script from /etc/clearos/firewall.d/local. -
Accepted Answer
-
Accepted Answer
Nick Howitt wrote:
The one to apply them needs to be called from /etc/clearos/firewall.d/local so it is called every time the firewall restarts.
Thanks Nick. Very good idea. I've been running this weekly but never checked if the firewall dies in between and if it loads those country blocks. Looks like I have some bash script learning to do....
As I'm still on COS 5.2, the correct file to be updating is /etc/rc.d/rc.firewall.local ?
Thanks again for all your help and suggestions! -
Accepted Answer
-
Accepted Answer
I've just given this script a bash and it works well.
Only thing i too, am not getting around, is the firewall restarts removing all the rules.
I've tried putting a cron job inside the hourly folder, but this doesnt work either.
Any ideas how to make it reload the rules after the system does what ever it does that
keeps removing the rules?
i've never delt with a script as advanced as the one here, so i wouldnt know what the hell to do
adding anything other than iptable rules to /etc/clearos/firewall.d/local
Unless there is some way to make it execute the script?
#!/bin/bash
/root/block-countrys.sh
exit 0
? -
Accepted Answer
Hmmmm, the source of information for this script ( http://ipinfodb.com ) seems to have discontinued their service...
Does anyone has a alternative solution?
I see a sharp increase in relay-attempts, earlier they were blocked by this script before they reached the mailserver... -
Accepted Answer
That's too bad.
Looks like you have to use [url]http://www.ip2location.com/free/visitor-blocker][/url] instead. 1 country per visit. Yeck.
These things don't change very quickly so you should be able to use your existing lists for some time.
Maybe someone can spend a minutes to investigate. I think there is another site that offers these lists??
Please login to post a reply
You will need to be logged in to be able to post a reply. Login using the form on the right or register an account if you are new here.
Register Here »