使用 iptables 将允许的 IP(进/出)列入白名单

使用 iptables 将允许的 IP(进/出)列入白名单

我有几个 IP 范围,我希望我的服务器能够连接,用户也能够从这些 IP 范围进行连接。其他所有 IP 范围都应被阻止。

我该如何使用 iptables 来做到这一点?

我的操作系统是基于 Debian 的 Linux 发行版。

答案1

我建议你使用防火墙配置工具,例如纵火者,然后从那里开始。不过,这里有一些基础知识供您参考。

#Flush existing rules
iptables -F
# Allow existing connections to continue
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# Accept everything from the 192.168.1.x network
iptables -A INPUT -i eth0 -s 192.168.1.0/24 -j ACCEPT
# Allow connections from this host to 192.168.2.10
iptables -A OUTPUT -o eth0 -d 192.168.2.10 -j ACCEPT
# Set up default DROP rule for eth0
iptables -P INPUT DROP

答案2

iptables -I INPUT -s <allowed_ip> -j ACCEPT #(repeat this line as needed)
iptables -P INPUT DROP

这会将您的系统变成不允许的计算机使用的不存在的系统。

答案3

如果您想要允许任意范围而不是整个子网,您可以使用“iprange”iptables 模块:

iptables -P INPUT DROP

iptables -A INPUT -m iprange --src-range 192.168.1.30-50 -j ACCEPT

例如,将允许来自地址在 192.168.1.30 和 192.168.1.50 之间的所有机器的流量。

如果您想要允许传入和传出流量到同一范围的 IP,我建议您创建一个特定的链,允许该 IP 并将所有输入和输出目标定位到它:

--定义删除所有内容的默认策略:

iptables -P INPUT DROP

iptables -P OUTPUT DROP

——创建新的链:

iptables -N allowed_ips

--如果源属于允许范围的一部分,则接受

iptables -A allowed_ips -m iprange --src-range 192.168.1.30-50 -j ACCEPT

--如果不是,则返回到调用者链继续处理

iptables -A allowed_ips -j RETURN

--使所有进出机器的流量都通过我们的新链

iptables -A INPUT -j allowed_ips

iptables -A OUTPUT -j allowed_ips

就是这样!当然,你可能需要额外的规则,比如允许所有来自/到 lo 接口的流量等。

答案4

您也可以使用发酵我在过去的一年里也使用过它,它在条件防火墙规则等方面给了我很大帮助。

相关内容