Forums

×

Warning

JUser: :_load: Unable to load user with ID: 18417
ahorli
ahorli
Offline
Resolved
0 votes
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:
#!/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
Wednesday, April 28 2010, 03:02 PM
Share this post:
Responses (132)
  • Accepted Answer

    Saturday, February 21 2015, 04:43 PM - #Permalink
    Resolved
    0 votes
    Nick, you are very eagle-eyed today and thanks for pointing out.

    The pain of copy and pasting from a small SSH window...

    The code should be:

    !/bin/bash

    # Use lower case for this script

    ISO="bh br cn in"

    # Remove old compressed and uncompressed zone files that was downloaded
    cd /mnt/ipsets
    rm -f all-zones.tar.gz
    rm -f *.zone

    # Download the file
    if ! wget http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz -q;
    then
    exit 1
    fi

    # Check if the file was downloaded successfully and then take the relevant actions
    if [ -f "all-zones.tar.gz" ]
    then
    # Extract the country codes from teh compressed file
    tar xzf all-zones.tar.gz > /dev/null

    # Make sure the ip_set module is loaded
    if [ "`lsmod | grep ip_set`" = "" ]; then
    modprobe ip_set
    fi

    # Destroy non-ripe-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

    # Load the country list
    for COUNTRY in $ISO
    do
    if [ -f "$COUNTRY.zone" ]
    then
    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

    # Remove the compressed file
    rm -f all-zones.tar.gz
    rm -f *.zone

    # Save the IPSet data to file
    ipset save country-list > ipset-state-data
    fi
    Like
    1
    The reply is currently minimized Show
  • Accepted Answer

    Sunday, February 22 2015, 09:58 PM - #Permalink
    Resolved
    0 votes
    Attention anyone using my script from the previous page


    There is a serious error in the script which I have now corrected. Untarring the file caused the permissions on /tmp to be overwritten. The fix is to change the line:
    tar xzf all-zones.tar.gz  > /dev/null
    to
    tar xzf all-zones.tar.gz --wildcards '*.zone' > /dev/null
    There may also be a command line switch which fixes the problem but I have not found it yet.

    To fix the problem caused, change the permissions on /tmp to 1777:
    chmod 1777 /tmp

    Many apologies.

    @James, your script is OK as you are unpacking to your own directory rather than a system directory.
    Like
    1
    The reply is currently minimized Show
  • Accepted Answer

    Monday, January 06 2020, 11:55 AM - #Permalink
    Resolved
    2 votes
    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:
    -m state --state NEW
    from the firewall rules. This should have been replaced by:
    -m conntrack --ctstate NEW
    And not supplemented with it.
    Like
    1
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Thursday, April 29 2010, 11:08 PM - #Permalink
    Resolved
    0 votes
    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!
    The reply is currently minimized Show
  • Accepted Answer

    ahorli
    ahorli
    Offline
    Friday, April 30 2010, 08:18 AM - #Permalink
    Resolved
    0 votes
    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
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Wednesday, May 05 2010, 03:59 PM - #Permalink
    Resolved
    0 votes
    Thank you for the explanation, Axel.

    I will try to implement this on my server over the next few days.
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Tuesday, May 11 2010, 08:24 PM - #Permalink
    Resolved
    0 votes
    Axel,

    Ran the script and had a few things to change. It looks like my copy buffer didn't like lines longer than 80 characters. Once I fixed the incorrect line endings, everything worked great.

    Now I have to figure out how to add the cron job.

    Thanks and Cheers!
    The reply is currently minimized Show
  • Accepted Answer

    ahorli
    ahorli
    Offline
    Tuesday, May 11 2010, 09:24 PM - #Permalink
    Resolved
    0 votes
    Hi

    glad it works for you.
    Like i said in my first post create a file in /etc/cron.weekly and make it executable.
    Now put this code
    Code:
    #!/bin/bash
    blockcountry.sh
    exit 0

    into the file and execute #service crond restart.
    Now you are set.

    cheers
    Axel
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Wednesday, May 12 2010, 09:14 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Wednesday, May 19 2010, 03:16 AM - #Permalink
    Resolved
    0 votes
    Thats a Nice Script Axel! Thanks for the contrib....
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Sunday, June 06 2010, 10:26 PM - #Permalink
    Resolved
    0 votes
    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 says
    Country block instituted for: RU CN
    So I think it is working OK.
    The reply is currently minimized Show
  • Accepted Answer

    kfox
    kfox
    Offline
    Monday, June 07 2010, 01:08 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    kfox
    kfox
    Offline
    Monday, June 07 2010, 02:47 PM - #Permalink
    Resolved
    0 votes
    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
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Sunday, September 26 2010, 10:00 PM - #Permalink
    Resolved
    0 votes
    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=" 
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Sunday, November 14 2010, 04:59 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Brian
    Brian
    Offline
    Friday, November 26 2010, 09:00 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Brian
    Brian
    Offline
    Friday, November 26 2010, 09:03 PM - #Permalink
    Resolved
    0 votes
    But i forgot to post that the main script has errors as it thinks United States is 2 fields because of the space.
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Friday, November 26 2010, 09:10 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Friday, November 26 2010, 09:33 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Thursday, November 24 2011, 08:04 PM - #Permalink
    Resolved
    0 votes
    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
    The reply is currently minimized Show
  • Accepted Answer

    Wednesday, February 15 2012, 10:53 PM - #Permalink
    Resolved
    0 votes
    ### Network config ###
    ####change this to reflect your servers wan interface ###
    IPTCBDEVICE=eth0


    Would this work on dual wan?

    ### Network config ###
    ####change this to reflect your servers wan interface ###
    IPTCBDEVICE=eth0
    IPTCBDEVICE=eth2
    The reply is currently minimized Show
  • Accepted Answer

    Saturday, May 26 2012, 10:51 AM - #Permalink
    Resolved
    0 votes
    Hi.
    I got this one:

    iptables-restore v1.3.5: host/network `Too.0.0.0' not found
    Error occurred at line: 14
    The reply is currently minimized Show
  • Accepted Answer

    Wolvenmoon
    Wolvenmoon
    Offline
    Thursday, September 27 2012, 01:56 AM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Thursday, September 27 2012, 06:17 AM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Thursday, September 27 2012, 12:46 PM - #Permalink
    Resolved
    0 votes
    Yes, I continue to use it on my COS5.2 box. I think it works well. I update monthly.

    Rolf, how do you get a report? I would appreciate learning how you got that to work.

    Regards,
    Nuke
    The reply is currently minimized Show
  • Accepted Answer

    Thursday, September 27 2012, 07:01 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Stephen
    Stephen
    Offline
    Friday, November 09 2012, 01:45 PM - #Permalink
    Resolved
    0 votes
    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!
    The reply is currently minimized Show
  • Accepted Answer

    Graham
    Graham
    Offline
    Sunday, February 03 2013, 01:07 PM - #Permalink
    Resolved
    0 votes
    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. http://www.clearfoundation.com/media/kunena/attachments/legacy/images/Capture1.JPG
    The reply is currently minimized Show
  • Accepted Answer

    Sunday, February 03 2013, 02:18 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Graham
    Graham
    Offline
    Sunday, February 03 2013, 02:42 PM - #Permalink
    Resolved
    0 votes
    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.

    http://www.clearfoundation.com/media/kunena/attachments/legacy/images/cap.png
    Attachments:
    The reply is currently minimized Show
  • Accepted Answer

    Monday, February 04 2013, 12:24 PM - #Permalink
    Resolved
    0 votes
    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".
    The reply is currently minimized Show
  • Accepted Answer

    Stephen
    Stephen
    Offline
    Monday, February 04 2013, 03:37 PM - #Permalink
    Resolved
    0 votes
    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 :)
    The reply is currently minimized Show
  • Accepted Answer

    Monday, February 04 2013, 07:02 PM - #Permalink
    Resolved
    0 votes
    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.
    The reply is currently minimized Show
  • Accepted Answer

    Stephen
    Stephen
    Offline
    Monday, February 04 2013, 07:10 PM - #Permalink
    Resolved
    0 votes
    Ah, I see, I missed your reply. I'll see if I can do just that.

    So far, the site has not complained about me getting the list hourly, but I would prefer to run the update daily for the IP changes, and apply the rules every time the firewalls tarts. I'll see what I can do.
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Thursday, February 07 2013, 02:00 AM - #Permalink
    Resolved
    0 votes
    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!
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Thursday, February 07 2013, 02:01 AM - #Permalink
    Resolved
    0 votes
    Oooophs sorry. Somehow I double posted.
    The reply is currently minimized Show
  • Accepted Answer

    Thursday, February 07 2013, 12:18 PM - #Permalink
    Resolved
    0 votes
    Double? It looks like triple to me! ;)

    Anyway, yes it is /etc/rc.d/rc.firewall.local in 5.2.
    The reply is currently minimized Show
  • Accepted Answer

    t1ck3ts
    t1ck3ts
    Offline
    Tuesday, August 20 2013, 01:55 PM - #Permalink
    Resolved
    0 votes
    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

    ?
    The reply is currently minimized Show
  • Accepted Answer

    Friday, October 11 2013, 03:57 PM - #Permalink
    Resolved
    0 votes
    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...
    The reply is currently minimized Show
  • Accepted Answer

    nuke
    nuke
    Offline
    Friday, October 11 2013, 06:56 PM - #Permalink
    Resolved
    0 votes
    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??
    The reply is currently minimized Show
Your Reply