如何在 Ubuntu 上拒绝除 HTTP 端口 80 和 HTTPS 端口 443 之外的所有传入端口

检查当前防火墙状态

检查防火墙状态。
默认情况下,UFW防火墙将被禁用:

$ sudo ufw status
Status: inactive

阻止所有传入流量

首先,我们可以使用以下Linux命令阻止所有传入流量:

$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

允许HTTP / HTTPS传入流量

UFW提供三种可能的配置文件,以允许/拒绝到Apache Web服务器的流量:

  • Apache - 端口80
  • Apache full - 端口80,443
  • Apache Secure - 端口443

nginx web服务器:

  • nginx http - 端口80
  • nginx Full - 端口80,443
  • nginx https - 端口443

使用上述配置文件名称,我们可以允许传入流量适合任何场景。

例如,要允许 Apache 打开两个端口 80,443:

$ sudo ufw allow in "Apache Full"
Rule added
Rule added (v6)

或者,仅允许在nginx服务器上打开端口443:

$ sudo ufw allow in "Nginx HTTPS"

启用防火墙

启用前,允许ssh端口,否则无法ssh远程连接服务器:

$ sudo ufw allow from any to any port 22 proto tcp
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

检查状态

$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To                         Action      From
--                         ------      ----               
80,443/tcp (Apache Full)   ALLOW IN    Anywhere                             
80,443/tcp (Apache Full (v6)) ALLOW IN    Anywhere (v6)

常见问题

错误:

$ sudo ufw allow in "Apache Full"
ERROR: Could not find a profile matching 'Apache Full'

系统上没有安装Apache Web服务器。
要安装Apache WebServer,执行:

$ sudo apt install apache2
日期:2020-07-07 20:55:17 来源:oir作者:oir