summaryrefslogtreecommitdiffstats
path: root/ddwrt/ipblock.sh
blob: 1bd2198615b70249fe54340efa2e984c1a5fd356 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/sh


### USAGE
#
# Append below to 'Commands' as save to 'Save Firewall' and place this script to /opt/ipblock/ipblock.sh
#
#iptables -N countrydropin
#iptables -N countrydropout
#iptables -I INPUT 2 -i vlan2 -j countrydropin
#iptables -I FORWARD 2 -i vlan2 -j countrydropin
#iptables -I FORWARD 3 -o vlan2 -j countrydropout
#sh /opt/ipblock/ipblock.sh & 

#set -x

### Block all traffic from listed. Use ISO code ###
ISO="cn-aggregated"
CLOCAL="custom"

### Set PATH ###
IPT=/usr/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep
LOCKFILE=/tmp/ipblock.lock

### No editing below ###
inSPAMLIST="countrydropin"
outSPAMLIST="countrydropout"
ZONEROOT="/opt/ipblock/zones"
DLROOT="http://www.ipdeny.com/ipblocks/data/aggregated"
iBL="${ZONEROOT}/ipblockin.rules"
oBL="${ZONEROOT}/ipblockout.rules"

if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "Lock file exist.. exiting"
    exit
fi

# make sure the lockfile is removed when we exit and then claim it
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}

cleanOldRules(){
  $IPT -F countrydropin
  $IPT -F countrydropout
}

# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT

# clean old rules
cleanOldRules
rm -f $iBL
rm -f $oBL

echo '*filter' > $iBL
echo '*filter' > $oBL

for c in $ISO
do
        # local zone file
        tDB=$ZONEROOT/$c.zone

        # get fresh zone file
        $WGET -T 30 -O $tDB $DLROOT/$c.zone

        awk -v inSPAMLIST=$inSPAMLIST '{print "-A "inSPAMLIST" -s "$1" -j DROP"}' $tDB >> $iBL
        awk -v outSPAMLIST=$outSPAMLIST '{print "-A "outSPAMLIST" -d "$1" -j REJECT"}' $tDB >> $oBL
done

for c in $CLOCAL
do
        # local custom zone file
        if [ -e $ZONEROOT/$c.zone ]; then
            tDB=$ZONEROOT/$c.zone

            awk -v inSPAMLIST=$inSPAMLIST '{print "-A "inSPAMLIST" -s "$1" -j DROP"}' $tDB >> $iBL
            awk -v outSPAMLIST=$outSPAMLIST '{print "-A "outSPAMLIST" -d "$1" -j REJECT"}' $tDB >> $oBL
        fi
done

echo 'COMMIT' >> $iBL
echo 'COMMIT' >> $oBL

iptables-restore -n < $iBL
iptables-restore -n < $oBL

rm -f ${LOCKFILE}