pol*_*lot 19 linux firewall iptables
我想制定一些简单的 iptables 规则来拒绝所有传入连接并允许传出。我怎样才能做到这一点?
Yoh*_*ann 32
用 root 访问试试这个:
# Set default chain policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Accept on localhost
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow established sessions to receive traffic
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Run Code Online (Sandbox Code Playgroud)
请注意,这将残酷地切断所有正在运行的连接- 这包括您可能用于管理服务器的 SSH 连接之类的东西。仅当您有权访问本地控制台时才使用此选项。
有关如何为 SSH 添加例外的信息,请参阅 Miphix 的回答。
小智 14
如果您通过 SSH 远程工作,您可能需要添加以下内容(-I
在 中的所有其他规则之前插入INPUT
):
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
Run Code Online (Sandbox Code Playgroud)
如果您的 SSH 服务正在侦听另一个端口,则您必须使用该端口而不是22
.
否则,您可能会意外失去访问权限。
请注意,其他答案不包括 IPv6!如果您的系统接受 IPv6 流量,则没有一条 iptables 规则适用于 ipv6 流量。
我建议使用 iptables-restore 和 save,而不是直接使用 iptables / ip6tables。这些工具允许指定具有多个规则的 iptables 配置,并使用一个命令轻松加载它。
创建一个包含以下内容的文件(我将其命名为 iptables.rules):
*filter
# drop forwarded traffic. you only need it of you are running a router
:FORWARD DROP [0:0]
# Accept all outgoing traffic
:OUTPUT ACCEPT [623107326:1392470726908]
# Block all incoming traffic, all protocols (tcp, udp, icmp, ...) everything.
# This is the base rule we can define exceptions from.
:INPUT DROP [11486:513044]
# do not block already running connections (important for outgoing)
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# do not block localhost
-A INPUT -i lo -j ACCEPT
# do not block icmp for ping and network diagnostics. Remove if you do not want this
# note that -p icmp has no effect on ipv6, so we need an extra ipv6 rule
-4 -A INPUT -p icmp -j ACCEPT
-6 -A INPUT -p ipv6-icmp -j ACCEPT
# allow some incoming ports for services that should be public available
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
# commit changes
COMMIT
Run Code Online (Sandbox Code Playgroud)
请注意,如果您想允许 ICMP 和流量到特定端口,我添加了一些额外的示例。
现在您可以使用以下命令加载它:
iptables-restore < iptables.rules
ip6tables-restore < iptables.rules
Run Code Online (Sandbox Code Playgroud)
现在您的规则也涵盖 ipv6 并且易于管理。
给 Debian 用户的附加说明:如果您对规则感到满意,则可以apt install iptables-persistent
在重新启动后恢复规则。规则不会在关机时自动保存,因此运行netfilter-persistent save
以更新持久性规则。
归档时间: |
|
查看次数: |
77103 次 |
最近记录: |