Advertisement
Guest User

Asiablock

a guest
Apr 6th, 2011
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 15.00 KB | None | 0 0
  1. root@Asustek:~# cat /opt/etc/init.d/S95asiablock
  2. #!/bin/sh
  3. ##############################################################################
  4. ## S95countryblock
  5. ## Written by: JP van Melis
  6. ## Intended platform: DD-WRT Linux router
  7. #
  8. # This script downloads a blacklist from the Internet which will be used by iptables
  9.  
  10. # If available it will use "aggregate" to combine subnets
  11.  
  12. # http://www.mail-archive.com/nanog@nanog.org/msg14737.html
  13. # ftp://ftp.isc.org/isc/aggregate/aggregate-1.6.tar.gz
  14.  
  15. #
  16. # Make sure Optware programs come first as they support all the options I need
  17. export PATH=/opt/usr/sbin:/opt/sbin:/opt/bin:/bin:/usr/bin:/sbin:/usr/sbin:/jffs/sbin:/jffs/bin:/jffs/usr/sbin:/jffs/usr/bin:/mmc/sbin:/mmc/bin:/mmc/usr/sbin:/mmc/usr/bin
  18.  
  19. # Constants
  20.  
  21. # cn = China
  22. # af = Afghanistan
  23. # au = Australia
  24. # pk = pakistan
  25. # ph = philippines
  26. # in = india
  27. # my = malaysia
  28. # ua = ukrain
  29. # ng = nigeria
  30. # sg = singapore
  31. # th = Thailand
  32. # kh = cambodia
  33. # li = Liechtenstein
  34. # These countries will be blocked specifically
  35. ISO_spam="af cn ng in th sg pk my kh li vn kr ph"
  36. ISO_ham="us"
  37.  
  38. # You can limit the amount of logentries per minute
  39. LOGONCE=1
  40.  
  41. KEYWORD=asia
  42. NAME=asiablock
  43.  
  44. URLBASE="http://www.ipdeny.com/ipblocks/data/countries"
  45. AGE=10
  46.  
  47. CONFDIR=/tmp/etc/config
  48. WORKDIR=/tmp
  49. SAVEDIR=/tmp
  50. [ -d /opt/etc ] && SAVEDIR=/opt/etc
  51.  
  52. scriptname=${0##*/}
  53.  
  54. SPAMips=${WORKDIR}/spamips.${KEYWORD}
  55. HAMips=${WORKDIR}/hamips.${KEYWORD}
  56. COUNTRYfile=${WORKDIR}/country.${KEYWORD}
  57. COUNTRYtemp=${WORKDIR}/.country.${KEYWORD}
  58.  
  59. HAMinclude=${SAVEDIR}/${KEYWORD}.ham
  60. SPAMinclude=${SAVEDIR}/${KEYWORD}.spam
  61.  
  62. SPAMCHAIN=SPAM${KEYWORD}
  63. SPAMfile=iptables.${KEYWORD}
  64. SPAMfilepath=${SAVEDIR}/${SPAMfile}
  65. SPAMrules=${SAVEDIR}/${SPAMfile}.rules
  66. SYMLINK=${CONFDIR}/${KEYWORD}.prewall
  67. SPAMACTION=DROP
  68. # SPAMACTION=REJECT
  69. SPAMLOGSTOP=${SPAMACTION}${KEYWORD}
  70.  
  71. AGE_SPAMfilepath=0
  72.  
  73. [ -f ${SPAMfilepath} ] && AGE_SPAMfilepath=`date +%s -r ${SPAMfilepath}`
  74.  
  75. if [ -z "`which ipcalc`" ] ; then
  76.   echo "Script needs 'ipcalc', abort" >&2
  77.   exit 1
  78. fi
  79.  
  80. if [ -z "$1" ] ; then
  81.     case `echo "$0" | sed 's:^.*/\(.*\):\1:g'` in
  82.         S??*) rc="start" ;;
  83.         K??*) rc="stop" ;;
  84.         *) rc="usage" ;;
  85.     esac
  86. else
  87.     rc="$1"
  88. fi
  89.  
  90. createblocknet ()
  91. {
  92. optlog "${scriptname}" "Create static network to block"
  93. # You can put comments after the subnet as a reminder
  94. # If you put a comment before, this specific subnet will not be included
  95. echo -n "43.0.0.0/8  # Japan
  96. 58.0.0.0/7 # A lot of 'decent' countries, as well...
  97. 60.0.0.0/7
  98. 110.0.0.0/7
  99. 112.0.0.0/6
  100. 116.0.0.0/6
  101. 120.0.0.0/6
  102. 124.0.0.0/7
  103. 126.0.0.0/8
  104. # 169.0.0.0/8 # too much US.. not added
  105. 180.0.0.0/8
  106. 202.0.0.0/8
  107. 203.0.0.0/8 # A lot of 'down under'
  108. 210.0.0.0/7
  109. 218.0.0.0/7
  110. 220.0.0.0/7
  111. 222.0.0.0/8 # Japan" | egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+' >${WORKDIR}/${KEYWORD}net
  112. optlog "${scriptname}" "network consists of `cat ${WORKDIR}/${KEYWORD}net | wc -l` subnets"
  113. }
  114.  
  115. createclassA_list ()
  116. {
  117. optlog "${scriptname}" "Break down big network into Class A subnets"
  118. echo -n "" >${WORKDIR}/classA.${KEYWORD}
  119. while read asialine ; do
  120.   brcast=`ipcalc -nb "${asialine}" | grep -i Broadcast | tr -cd '[0-9].' | awk -F\. '{print $1}'`
  121.   network=`echo ${asialine} | awk -F\. '{print $1}'`
  122.   while [ ${network} -le ${brcast} ] ; do
  123.     echo "^${network}\\." >>${WORKDIR}/classA.${KEYWORD}
  124.     let network+=1
  125.   done
  126. done<${WORKDIR}/${KEYWORD}net
  127. }
  128.  
  129. createblocklist ()
  130. {
  131. # remove file if the last line doesn't contain a bracket
  132. if [ -f ${SPAMfilepath} ] ; then
  133.   if ! tail -n1 ${SPAMfilepath} | grep -q "^#" ; then
  134.     optlog "${scriptname}" "I will remove ${SPAMfile} because the current one is invalid"
  135.     rm -f ${SPAMfilepath} 2>/dev/null
  136.   else
  137.     # remove file if it is older than this script
  138.     [ ${AGE_SPAMfilepath} -lt `date +%s -r ${0}` ] && rm -f ${SPAMfilepath} 2>/dev/null
  139.     # remove file if it is older than 20 days
  140.     find ${SAVEDIR} -mtime +${AGE} -type f -name ${SPAMfile} -exec rm {} \;
  141.     [ -f ${SPAMfilepath} ] || optlog "${scriptname}" "Removed ${SPAMfilepath} because it was older than ${AGE} days or the file $0"
  142.   fi
  143. fi
  144.  
  145. sanitize ()
  146. {
  147. sanfile="${1}"
  148. if [ -f ${sanfile} ] ; then
  149.   # Sanitize HAMinclude, but not more than necessary
  150.   if [ ${AGE_SPAMfilepath} -lt `date +%s -r ${sanfile}` ] ; then
  151.     fdate="`date -r ${sanfile}`"
  152.     rm -f ${SPAMfilepath} 2>/dev/null
  153.     sed -i -e "s/^[1-9][0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$/&\/32/" ${sanfile}
  154.     if [ ! -z "`which aggregate`" ] && [ `cat ${sanfile} | wc -l` -gt 1 ] ; then
  155.       egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+' ${sanfile} >/tmp/netsonly
  156.       cat /tmp/netsonly | aggregate >/tmp/sanfile
  157.       # I can just replace the file with the aggregated list, but then I would need
  158.       # to lookup all the whois data again. These lookups are limited from a given IP
  159.       if [ `cat /tmp/sanfile | wc -l` -ne `cat ${sanfile} | wc -l` ] ; then
  160.          # Collect all the lines that are in aggregated list
  161.          grep -f /tmp/sanfile ${sanfile} >/tmp/sanfile2
  162.          # Add the ones that were not there
  163.          grep -v -f /tmp/netsonly /tmp/sanfile >>/tmp/sanfile2
  164.          mv /tmp/sanfile2 ${sanfile}
  165.       fi
  166.       [ -f /tmp/sanfile ] && rm -f /tmp/sanfile 2>/dev/null
  167.     fi
  168.     if [ -n "`which whois`" ]  ; then
  169.       changed=0
  170.       cp ${sanfile} /tmp/sanfile
  171.       while read line ; do
  172.         # only entries with merely CIDR will be replaced
  173.  
  174.         if echo "$line" | egrep -q '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$' ; then
  175.           let changed+=1
  176.           IP=`echo "$line" | egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}'`
  177.           IPpadded="`echo "${line}" | awk '{ printf("%-18s\n", $0)}' | sed 's/\//\\\\\//'`"
  178.           orgname="`whois ${IP} 2>/dev/null | grep -i -e 'orgname:' -e 'netname:' -e 'descr:' | head -n1 | awk -F: '{print $2}' | sed -e 's/\&/\\\\&/' | sed 's/^[ \t]*//;s/[ \t]*$//'`"
  179.           [ -z "${orgname}" ] || optlog "${scriptname}" "found ${orgname} at ${IP}"
  180.           sed -i -e "s/${IP}.*/${IPpadded}\t# ${orgname}/" ${sanfile}
  181.         fi
  182.       done </tmp/sanfile
  183.       if [ ${changed} -gt 0 ] ; then
  184.         optlog "${scriptname}" "changed ${changed} entries in ${sanfile}"
  185.         sort -t'/' -k2 -n ${sanfile} -o /tmp/sanfile
  186.         mv /tmp/sanfile ${sanfile}
  187.       fi
  188.       rm -f /tmp/sanfile 2>/dev/null
  189.     fi
  190.     touch -d "${fdate}" ${sanfile}
  191.   fi
  192. else
  193.   echo -n "" >${sanfile}
  194. fi
  195. }
  196.  
  197. sanitize ${HAMinclude}
  198. sanitize ${SPAMinclude}
  199.  
  200. if [ -f ${SPAMfilepath} ] ; then
  201.   optlog "${scriptname}" "Using existing file: ${SPAMfilepath}"
  202. else
  203.  
  204.   createblocknet
  205.   createclassA_list
  206.  
  207.   # Create chain in 2 files
  208.   echo -e "# bof" >${SPAMfilepath}
  209.   echo -e "iptables -N ${SPAMCHAIN}" >>${SPAMfilepath}
  210.   echo -e "iptables -N ${KEYWORD}" >>${SPAMfilepath}
  211.   echo -e "iptables -N ${SPAMLOGSTOP}" >>${SPAMfilepath}
  212.   echo -e "iptables -F ${SPAMCHAIN}" >>${SPAMfilepath}
  213.   echo -e "iptables -F ${KEYWORD}" >>${SPAMfilepath}
  214.   echo -e "iptables -F ${SPAMLOGSTOP}" >>${SPAMfilepath}
  215.   if [ ${LOGONCE} -eq 0 ] ; then
  216.     echo -e "iptables -A ${SPAMLOGSTOP} -j LOG --log-prefix \"[${KEYWORD} ${SPAMACTION}] : \" --log-tcp-options --log-ip-options" >>${SPAMfilepath}
  217.     echo -e "iptables -A ${SPAMLOGSTOP} -j ${SPAMACTION}" >>${SPAMfilepath}
  218.   else
  219.     echo -e "iptables -A ${SPAMLOGSTOP} -m recent ! --rcheck --seconds 1200 --name ${SPAMLOGSTOP} --rsource -j LOG --log-prefix \"[${KEYWORD} ${SPAMACTION} (1st pkt)] : \" --log-tcp-options --log-ip-options" >>${SPAMfilepath}
  220.     echo -e "iptables -A ${SPAMLOGSTOP} -m recent --set --name ${SPAMLOGSTOP} --rsource -j ${SPAMACTION}" >>${SPAMfilepath}
  221.   fi
  222.  
  223.   echo -e "iptables-restore -n <${SPAMrules}" >>${SPAMfilepath}
  224.   echo -e "*filter" >${SPAMrules}
  225.  
  226.   if [ ! -s ${WORKDIR}/${KEYWORD}net ] ; then
  227.     optlog "${scriptname}" "No HAM needed because there's no general SPAMlist"
  228.   else
  229.  
  230.     echo -n "" >${HAMips}
  231.     # Whitelist these countries if they are within Asia's subnet
  232.     for c in ${ISO_ham} ; do
  233.       cURL=${URLBASE}/${c}.zone
  234.       n=1
  235.       while true ; do
  236.         optlog "${scriptname}" "Downloading ${cURL} to ${COUNTRYfile}"
  237.         wget -q -O ${COUNTRYfile} ${cURL}
  238.         [ -f ${COUNTRYfile} ] && grep -q "/" ${COUNTRYfile} && break
  239.         [ $n -gt 5 ] && break
  240.         let n+=1
  241.         sleep 30
  242.       done
  243.       if [ -f ${COUNTRYfile} ] ; then
  244.         # subnet will be extracted
  245.         egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+' ${COUNTRYfile} >${COUNTRYtemp}
  246.         down_nets=`cat ${COUNTRYtemp} | wc -l`
  247.         optlog "${scriptname}" "Downloaded ${down_nets} subnets from country \"${c}\""
  248.         grep -f ${WORKDIR}/classA.${KEYWORD} ${COUNTRYtemp} >${COUNTRYfile}
  249.         in_classA=`cat ${COUNTRYfile} | wc -l`
  250.         optlog "${scriptname}" "${in_classA} subnets are in spamnet"
  251.         if [ ! -z "`which aggregate`" ] && [ ${in_classA} -gt 1 ] ; then
  252.           aggregate <${COUNTRYfile} >${COUNTRYtemp}
  253.           mv ${COUNTRYtemp} ${COUNTRYfile}
  254.           agg_nets=`cat ${COUNTRYfile} | wc -l`
  255.           optlog "${scriptname}" "\"aggregate\" brought this down to ${agg_nets} subnets"
  256.         fi
  257.         cat ${COUNTRYfile} >>${HAMips}
  258.       else
  259.         optlog "${scriptname}" "Failed to download ${cURL}"
  260.       fi
  261.     done
  262.     [ -f ${HAMinclude} ] && cat ${HAMinclude} >>${HAMips}
  263.     exceptions=`cat ${HAMips} | wc -l`
  264.     optlog "${scriptname}" "A total of ${exceptions} exceptions to the general blocklist are found"
  265.     if [ ! -z "`which aggregate`" ] && [ ${exceptions} -gt 1 ] ; then
  266.       aggregate <${HAMips} >${WORKDIR}/aggregate
  267.       mv ${WORKDIR}/aggregate ${HAMips}
  268.     fi
  269.     optlog "${scriptname}" "Create Hamlist"
  270.     sed -e "s/.*/-A ${KEYWORD} -s & -j RETURN/" ${HAMips} >>${SPAMrules}
  271.   fi
  272.   optlog "${scriptname}" "Hamlist created"
  273.   echo "-A ${KEYWORD} -j ${SPAMCHAIN}" >>${SPAMrules}
  274.   echo "-A ${KEYWORD} -j RETURN" >>${SPAMrules}
  275.  
  276.   rm ${SPAMips} 2>/dev/null
  277.   # Block these countries!!
  278.   for c in ${ISO_spam} ; do
  279.     cURL=${URLBASE}/${c}.zone
  280.     n=1
  281.     while true ; do
  282.       optlog "${scriptname}" "Downloading ${cURL} to ${COUNTRYfile}"
  283.       wget -q -O ${COUNTRYfile} ${cURL}
  284.       [ -f ${COUNTRYfile} ] && grep -q "/" ${COUNTRYfile} && break
  285.       [ $n -gt 5 ] && break
  286.       let n+=1
  287.       sleep 30
  288.     done
  289.     if [ ! -f ${COUNTRYfile} ] ; then
  290.       optlog "${scriptname}" "Error downloading ${cURL}"
  291.     else
  292.       # subnet will be extracted
  293.       egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+' ${COUNTRYfile} >${COUNTRYtemp}
  294.  
  295.       down_nets=`cat ${COUNTRYtemp} | wc -l`
  296.       optlog "${scriptname}" "Downloaded ${down_nets} subnets from country \"${c}\""
  297.       if [ -z "`which aggregate`" ] ; then
  298.         mv ${COUNTRYtemp} ${COUNTRYfile}
  299.       else
  300.         aggregate <${COUNTRYtemp} >${COUNTRYfile}
  301.         rm ${COUNTRYtemp} 2>/dev/null
  302.         agg_nets=`cat ${COUNTRYfile} | wc -l`
  303.         optlog "${scriptname}" "\"aggregate\" brought this down to ${agg_nets} subnets"
  304.       fi
  305.  
  306.       nRULES=`cat ${COUNTRYfile} 2>/dev/null | wc -l`
  307.       nCURips=`cat ${SPAMips} 2>/dev/null | wc -l`
  308.       optlog "${scriptname}" "Checking ${nRULES} rules for country \"${c}\""
  309.       grep -vf ${WORKDIR}/classA.${KEYWORD} ${COUNTRYfile} >>${SPAMips}
  310.       optlog "${scriptname}" "$(( `cat ${SPAMips} | wc -l` - ${nCURips})) rules added for country ${c}"
  311.     fi
  312.   done
  313.   optlog "${scriptname}" "Removing file \"${COUNTRYfile}\""
  314.   rm ${COUNTRYfile}
  315.  
  316.   cat ${WORKDIR}/${KEYWORD}net >>${SPAMips}
  317.   [ -f ${SPAMinclude} ] && cat ${SPAMinclude} >>${SPAMips}
  318.   blocks=`cat ${SPAMips} | wc -l`
  319.   optlog "${scriptname}" "A total of ${blocks} blocks are found"
  320.   if [ -z "`which aggregate`" ] ; then
  321.     optlog "${scriptname}" "\"aggregate\" is missing :-("
  322.   else
  323.     aggregate<${SPAMips} >${WORKDIR}/aggregate 2>/dev/null
  324.     # aggregate returns a 'Floating point exception' when the result should be 0.0.0.0/0
  325.     if [ $? -gt 128 ] ; then
  326.       echo '0.0.0.0/0' >${SPAMips}
  327.     else
  328.       sort -t'/' -k2 -n ${WORKDIR}/aggregate -o ${SPAMips}
  329.     fi
  330.     blocks=`cat ${SPAMips} | wc -l`
  331.     optlog "${scriptname}" "\"aggregate\" brought it down to ${blocks} blocks"
  332.   fi
  333.   sed -e "s/.*/-A ${SPAMCHAIN} -s & -j ${SPAMLOGSTOP}/" ${SPAMips} >>${SPAMrules}
  334.   echo "-A ${SPAMCHAIN} -j RETURN" >>${SPAMrules}
  335.   echo "COMMIT" >>${SPAMrules}
  336.  
  337.   echo "# eof" >>${SPAMfilepath}
  338.  
  339.   # if the whole Internet is blocked in the SPAMchain then that chain is not necessart anymore
  340.   if grep -q '0.0.0.0/0' ${SPAMips} ; then
  341.     sed -i -e "s/-A ${KEYWORD} -j SPAM${KEYWORD}/-A ${KEYWORD} -j ${SPAMLOGSTOP}/" ${SPAMrules}
  342.   fi
  343.  
  344.   rm ${SPAMips}
  345.   rm ${WORKDIR}/aggregate
  346. fi
  347. }
  348.  
  349. # Start/Stop/Status samba
  350. case "$rc" in
  351.     start)
  352.       mkdir -p ${CONFDIR} 2>/dev/null
  353.       createblocklist
  354.       if [ -f "${SPAMfilepath}" ] ; then
  355.  
  356.         chmod +x "${SPAMfilepath}"
  357.         rm -f ${SYMLINK}
  358.         # echo -e "iptables-restore -n <${SPAMfilepath}" >${SYMLINK}
  359.         # chmod +x ${SYMLINK}
  360.         ln -s ${SPAMfilepath} ${SYMLINK}
  361.  
  362.         optlog "${scriptname}" "Restart firewall"
  363.         lines=`cat ${SPAMrules} | wc -l`
  364.         secs=`date +%s`
  365.         stopservice firewall
  366.         iptables -F
  367.         rm /tmp/.ipt
  368.         startservice firewall
  369.         secs=$((`date +%s` - ${secs}))
  370.         optlog "${scriptname}" "It took ${secs} seconds to load ${lines} rules into iptables"
  371.       else
  372.         optlog "${scriptname}" "Failed to create ${SPAMfile}"
  373.         exit 1
  374.       fi
  375.       ;;
  376.     stop)
  377.       if [ -h ${SYMLINK} ] ; then
  378.         # replace symlink with a file with a chain which just says RETURN
  379.         mkdir -p ${CONFDIR} 2>/dev/null
  380.         rm -f ${SYMLINK}
  381.         echo -e "iptables -N ${SPAMCHAIN}" >${SYMLINK}
  382.         echo -e "iptables -F ${SPAMCHAIN}" >>${SYMLINK}
  383.         echo -e "iptables -N ${KEYWORD}" >>${SYMLINK}
  384.         echo -e "iptables -F ${KEYWORD}" >>${SYMLINK}
  385.         echo -e "iptables -A ${KEYWORD} -j RETURN"  >>${SYMLINK}
  386.  
  387.         chmod +x ${SYMLINK}
  388.  
  389.         optlog "${scriptname}" "Restart firewall"
  390.         rm /tmp/.ipt
  391.         startservice firewall
  392.       fi
  393.       ;;
  394.     status)
  395.       HAMNUM=$((`iptables -nL ${KEYWORD} 2>/dev/null | wc -l` - 4))
  396.       if [ -e ${SYMLINK} ] ; then
  397.         if [ -h ${SYMLINK} ] ; then
  398.            SPAMNUM=$((`iptables -nL SPAM${KEYWORD} | wc -l` - 3))
  399.            if iptables -nL SPAMworld | tail -n4 | grep -q "${SPAMLOGSTOP}" ; then
  400.              echo "${NAME} is blocking the world but whitelisting ${HAMNUM} subnets"
  401.            else
  402.              echo "${NAME} is blocking ${SPAMNUM} subnets whilst whitelisting ${HAMNUM}"
  403.            fi
  404.         else
  405.           echo "${NAME} is not blocking now"
  406.         fi
  407.         FORWARDref=`iptables -nL FORWARD | grep -c "${KEYWORD} "`
  408.         INPUTref=`iptables -nL INPUT | grep -c "${KEYWORD} "`
  409.         echo "It is referred to ${FORWARDref} time(s) in the chain FORWARD and ${INPUTref} times in the chain INPUT"
  410.       else
  411.         if [ ${HAMNUM} -le 4 ] ; then
  412.           echo "$NAME is not active"
  413.         else
  414.           echo "Although ${NAME} is disabled, the chain ${KEYWORD} has $((${HAMNUM} + 2)) entries"
  415.         fi
  416.       fi
  417.       ;;
  418. esac
  419.  
  420. root@Asustek:~#
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement