Guest User

block_countries_iptables.sh

a guest
Jul 5th, 2013
361
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2. ### Block all traffic from AFGHANISTAN (af) and CHINA (CN). Use ISO code ###
  3. ISO="af cn th kr"
  4.  
  5. ### Set PATH ###
  6. IPT=/sbin/iptables
  7. IPT_SAVE=/sbin/service
  8. IPT_SAVE_ARGS="iptables save"
  9. WGET=/usr/bin/wget
  10. EGREP=/bin/egrep
  11.  
  12. ### No editing below ###
  13. #SPAMLIST="countrydrop"
  14. ZONEROOT="/root/iptables"
  15. DLROOT="http://www.ipdeny.com/ipblocks/data/countries"
  16.  
  17. ### run ./block_countries_iptables.sh flush ###
  18. if [ $1 == "flush" ]
  19.     then
  20.     for c in $ISO
  21.     do
  22.         $IPT -D INPUT -j $c
  23.         $IPT -D OUTPUT -j $c
  24.         $IPT -D FORWARD -j $c
  25.         $IPT -F $c
  26.         $IPT -X $c
  27.         rm $ZONEROOT/$c.zone
  28.     done
  29.     $IPT_SAVE $IPT_SAVE_ARGS
  30.     echo "ALL COUNTRIES REMOVED"
  31.     exit 0 
  32. fi 
  33. ### END ###
  34.  
  35. cleanOldRules(){
  36. $IPT -D INPUT -j $1
  37. $IPT -D OUTPUT -j $1
  38. $IPT -D FORWARD -j $1
  39. $IPT -F $1
  40. $IPT -X $1
  41. rm $ZONEROOT/$1.zone
  42. }
  43.  
  44. # create a dir
  45. [ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT
  46.  
  47. for c in $ISO
  48. do
  49.     # clean old rules
  50.     [ -f $ZONEROOT/$c.zone ] && cleanOldRules $c
  51.    
  52.     # create a new iptables list
  53.     $IPT -N $c
  54.  
  55.     # local zone file
  56.     tDB=$ZONEROOT/$c.zone
  57.  
  58.     # get fresh zone file
  59.     $WGET -O $tDB $DLROOT/$c.zone
  60.  
  61.     # country specific log message
  62.     SPAMDROPMSG="$c Country Drop: "
  63.  
  64.     # get
  65.     BADIPS=$(egrep -v "^#|^$" $tDB)
  66.     for ipblock in $BADIPS
  67.     do
  68.        $IPT -A $c -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
  69.        $IPT -A $c -s $ipblock -j DROP
  70.     done
  71.    
  72.     # exit chain
  73.     $IPT -A $c -j RETURN
  74.    
  75.     # Drop everything
  76.     $IPT -I INPUT -j $c
  77.     $IPT -I OUTPUT -j $c
  78.     $IPT -I FORWARD -j $c
  79. done
  80.  
  81. # call your other iptable script
  82. $IPT_SAVE $IPT_SAVE_ARGS
  83.  
  84. exit 0
RAW Paste Data