Skip to content

🛡️ UFW(Ubuntu 防火墙)

什么是 UFW?

UFW(Uncomplicated Firewall)——不折腾的防火墙。正如其名,它把复杂的 iptables 命令简化成了人话。如果你觉得 iptables 是微积分,那 UFW 就是加减法。

基本操作

bash
# 安装(Ubuntu 通常自带)
sudo apt install ufw

# 开启防火墙
sudo ufw enable
Firewall is active and enabled on system startup

# 关闭防火墙
sudo ufw disable

# 查看状态
sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere

# 详细状态(显示规则编号)
sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 443/tcp                    ALLOW IN    Anywhere
[ 4] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

允许和拒绝规则

bash
# 允许 SSH
sudo ufw allow ssh
sudo ufw allow 22/tcp        # 效果一样

# 允许 HTTP 和 HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 允许端口范围
sudo ufw allow 3000:4000/tcp

# 只允许特定 IP 访问 SSH
sudo ufw allow from 192.168.1.100 to any port 22

# 允许特定 IP 访问所有端口
sudo ufw allow from 192.168.1.0/24

# 允许特定子网访问特定端口
sudo ufw allow from 10.0.0.0/8 to any port 3306

# 拒绝某个 IP
sudo ufw deny from 10.0.0.50

# 删除规则(按规则内容)
sudo ufw delete allow 80/tcp

# 删除规则(按编号,先查看编号)
sudo ufw status numbered
sudo ufw delete 2

应用程序配置文件

bash
# 查看可用的应用程序配置
sudo ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

# 按应用名放行
sudo ufw allow "Nginx Full"      # HTTP + HTTPS
sudo ufw allow "Nginx HTTP"      # 仅 HTTP
sudo ufw allow "OpenSSH"         # SSH

# 查看应用详情
sudo ufw app info "Nginx Full"
Profile: Nginx Full
Title: Web Server (Nginx, HTTP + HTTPS)
Description: Small, but very powerful and efficient web server

Ports:
  80,443/tcp

日志和重置

bash
# 开启日志记录
sudo ufw logging on

# 设置日志级别(low/medium/high/full)
sudo ufw logging medium

# 查看日志
sudo tail -f /var/log/ufw.log

# 重置所有规则(恢复默认)
sudo ufw reset
Resetting all rules to installed defaults. This may continue
to populate the current ruleset with the rules from the
package. Proceed with operation (y/N)?