如何在 Ubuntu 上设置简单的防火墙?

kle*_*lew 18 linux ubuntu firewall

有人可以通过配置示例给出一些简单的步骤如何在 Ubuntu 上设置简单的防火墙(仅使用控制台)?只应允许 ssh、http 和 https 访问。

Ner*_*est 20

sudo ufw 默认拒绝

须藤 ufw 允许 http

须藤 ufw 允许 https

须藤 ufw 允许 ssh

须藤 ufw 启用

  • 前面的评论是正确的。基本上,最后运行上述脚本中的第一个命令。 (2认同)

Mik*_*age 14

使用这个脚本。

只需决定是否允许传入 ICMP (ping)。

# Clear any existing firewall stuff before we start
iptables --flush
iptables -t nat --flush
iptables -t mangle --flush

# As the default policies, drop all incoming traffic but allow all
# outgoing traffic.  This will allow us to make outgoing connections
# from any port, but will only allow incoming connections on the ports
# specified below.
iptables --policy INPUT DROP
iptables --policy OUTPUT ACCEPT

# Allow all incoming traffic if it is coming from the local loopback device
iptables -A INPUT -i lo -j ACCEPT

# Accept all incoming traffic associated with an established
# connection, or a "related" connection
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow incoming connections
# SSH
iptables -A INPUT -p tcp -i eth0 --dport 22 -m state --state NEW -j ACCEPT
# HTTP
iptables -A INPUT -p tcp -i eth0 --dport 80 -m state --state NEW -j ACCEPT
# HTTPS
iptables -A INPUT -p tcp -i eth0 --dport 443 -m state --state NEW -j ACCEPT

# Allow icmp input so that people can ping us
iptables -A INPUT -p icmp -j ACCEPT

# Reject all other incoming packets
iptables -A INPUT -j REJECT
Run Code Online (Sandbox Code Playgroud)


Ham*_*ner 8

正如对另一个答案的评论所述,您不希望在允许 ssh 端口之前失去连接。从手册页:

“远程管理

当运行 ufw enable 或通过其 initscript 启动 ufw 时,ufw 将刷新其链。这是必需的,因此 ufw 可以保持一致的状态,但它可能会丢弃现有连接(例如 ssh)。ufw 确实支持在启用防火墙之前添加规则,因此管理员可以执行以下操作:

ufw allow proto tcp from any to any port 22
Run Code Online (Sandbox Code Playgroud)

在运行“ufw enable”之前。规则仍然会被刷新,但启用防火墙后 ssh 端口将打开。请注意,一旦 ufw 被“启用”,ufw 在添加或删除规则时将不会刷新链(但在修改规则或更改默认策略时会)。”

所以这是一种使用脚本来设置它的方法。运行此脚本时,您将被注销,但运行它后,您可以通过 ssh 再次登录。

将以下内容放入脚本中并将其命名为 start-firewall.sh

#!/bin/sh
ufw allow ssh
ufw enable
ufw default deny
ufw allow http
ufw allow https
Run Code Online (Sandbox Code Playgroud)

然后使其可执行并通过执行它来运行它

$ chmod + x start-firewall.sh
$ sudo ./start-firewall.sh
Run Code Online (Sandbox Code Playgroud)

要了解更多信息,请阅读手册页