Ubuntu 1404,iptables,阻止除特定 IP 之外的所有内容

Ubuntu 1404,iptables,阻止除特定 IP 之外的所有内容

我试图屏蔽服务器上除某些特定 IP 范围之外的所有内容。不应有来自 Web 或 ssh 或其他任何内容的访问。

我已经搜索了不同的主题并找到了一个听起来不错的解决方案:

iptables -P INPUT DROP
iptables -A INPUT -s IP/24 -j ACCEPT

实际上,drop 工作正常,但只要我执行命令,就会断开连接。我通过 ssh 客户端连接。我还尝试创建一个 bash 脚本。但 drop 之后,它也把我丢了,而且似乎脚本没有完成。

我该怎么做才能达到我的目标?

答案1

正如 ananthan 已经指出的那样,您应该首先反转设置策略和例外的顺序。如果您先设置策略,您的服务器就无法知道您大概设置例外,从而将您锁定。如果您先设置例外,则在设置策略时,例外已生效并豁免您的流量。

其次,如果您想要 IP 范围10.10.0.0- 10.10.255.255,则需要更宽的网络掩码。请尝试10.10.0.0/16。您可能还会发现关于 IPv4 子网划分的典型问题才有用。

最后,感谢您如此慷慨地回答这个问题(有足够特权看到已删除答案的读者会知道我的意思);如果 ananthan 稍后出现并写一个答案,我很乐意撤回我的答案以支持他/她。

答案2

您应该首先允许本地主机连接,然后允许您的 IP 地址或网络。

例如:如果您的 IP 地址是 192.168.1.20,您只能允许您的 IP 地址或整个网络。

# Allow connection from localhost
iptables -A INPUT -s 127.0.0.1/32 -j ACCEPT

# Allow my IP address.
iptables -A INPUT -s 192.168.1.20/32 -j ACCEPT

# ... or allow my entire network
iptables -A INPUT -s 192.168.1.1/24 -j ACCEPT

# Filter invalid packets
iptables -A INPUT -m state --state INVALID -j DROP

# Drop some custom ports
iptables -A INPUT -p tcp -m tcp --dport 22 -j DROP
iptables -A INPUT -p tcp -m tcp --dport 3306 -j DROP

# ... or allow some custom ports
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

# Allow related and established connection
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# And drop all
iptables -A INPUT -s 0.0.0.0 -j DROP

这只是一些示例,并非完美的解决方案。你可以使用 iptables 做更多的事情。

另一方面,你可以检查 Ubuntu14.04 防火墙请参阅手册页。

相关内容