2015-04-07 116 views
1

我正在使用以下脚本通过从whitelist.txt文件中过滤IP来应用iptablesbash脚本执行多个iptables链

如果我在列表中有多个IP,我iptables正显示出多条链:

#!/bin/bash 

# allowed ip file location 
WHITELIST=/usr/src/firewall/whitelist.txt 
# 
## Specify where IP Tables is located 
# 

IPTABLES=/sbin/iptables 
IPTABLES_SAVE=/sbin/iptables-save 

# 
## Save current iptables running configuration in case we want to revert back 
## To restore using our example we would run "/sbin/iptables-restore < /usr/src/iptables.last" 
# 
$IPTABLES_SAVE > /usr/src/iptables.last 
# 
## Clear current rules 
# 
##If current INPUT policy is set to DROP we will be locked out once we flush the rules 
## so we must first ensure it is set to ACCEPT. 
# 
$IPTABLES -P INPUT ACCEPT 
echo 'Setting default INPUT policy to ACCEPT' 

$IPTABLES -F 
echo 'Clearing Tables F' 
$IPTABLES -X 
echo 'Clearing Tables X' 
$IPTABLES -Z 
echo 'Clearing Tables Z' 

#Always allow localhost. 
echo 'Allowing Localhost' 
$IPTABLES -A INPUT -s 127.0.0.1 -j ACCEPT 

# 
## Whitelist 
# 

for x in `grep -v ^# $WHITELIST | awk '{print $1}'`; do 
echo "Permitting $x..." 
# $IPTABLES -A INPUT -s $x -j ACCEPT 
$IPTABLES -A INPUT -p tcp --dport 22 -j ACCEPT 
$IPTABLES -A INPUT -p tcp -m tcp -s "$x" --dport 80 -j ACCEPT 
$IPTABLES -A INPUT -p udp -m udp -s "$x" --dport 5060 -j ACCEPT 
done 

# block all other traffice 

$IPTABLES -A INPUT -p all -j DROP 
# 
## Save the rules so they are persistent on reboot. 
# 
/etc/init.d/iptables save 

而且我的iptables -L -n输出显示为

firewall]# iptables -L -n 
Chain INPUT (policy ACCEPT) 
target  prot opt source    destination 
ACCEPT  all -- 127.0.0.1   0.0.0.0/0 
ACCEPT  tcp -- 0.0.0.0/0   0.0.0.0/0   tcp dpt:22 
ACCEPT  tcp -- 192.168.1.125  0.0.0.0/0   tcp dpt:80 
ACCEPT  udp -- 192.168.1.125  0.0.0.0/0   udp dpt:5060 
ACCEPT  tcp -- 0.0.0.0/0   0.0.0.0/0   tcp dpt:22 
ACCEPT  tcp -- 192.168.1.1   0.0.0.0/0   tcp dpt:80 
ACCEPT  udp -- 192.168.1.1   0.0.0.0/0   udp dpt:5060 
DROP  all -- 0.0.0.0/0   0.0.0.0/0 

Chain FORWARD (policy DROP) 
target  prot opt source    destination 

Chain OUTPUT (policy ACCEPT) 
target  prot opt source    destination 

如何避免重复,该脚本怎么了......

+0

如何'whitelist.txt'看? –

+0

也许你应该在for-each-source-address循环之外放置非源地址限定的'$ IPTABLES -A INPUT -p tcp --dport 22 -j ACCEPT'行? – twalberg

+0

感谢进入无源地址以外的作品完美..... – striker

回答

0

让我猜你的whitelist.txt包含两个IP:192.168.1.125和192.168.1.1 ?!

然后,设置每个IP三个规则,一个SSH,一个用于HTTP,一个用于SIP,只有你不能指定SSH --source/-s,所以自然对任何IP白名单中,该规则将是相同的任何以前的。

TL; DR:将一个-s "$x"添加到SSH规则,你应该没问题。

特别提示:如果您想使整个私有C类子网,您可以使用语法-s 192.168.1.0/24 :-)

干杯,