Debian 配置防火墙安全策略

​想着提升下服务器安全策略,学习下开启及配置防火墙, Debian的防火墙是 ufw。

1. 安装 ufw

apt update
# 安装 ufw
apt install ufw 

# 查看
ufw status
# Status: inactive 未运行
# Status: active 正常运行

2. 初始化

# 重置所有规则并关闭服务(可选,但推荐以确保干净)
ufw reset

# 设置默认禁止入站
ufw default deny incoming

# 设置默认允许出站(服务器主动访问外部,如 apt update, pip install 等需要)
ufw default allow outgoing

3. 增加所需规则

# 运行 SSH
ufw allow 22/tcp comment '默认ssh端口'

# 允许 HTTP
ufw allow 80/tcp comment 'HTTP 80'

# 允许 HTTPS
ufw allow 443/tcp comment 'HTTPS 443'

# 允许指定 IP 访问 指定端口
ufw allow from 192.168.1.222 to any port 3306

# 其它自定义端口
ufw allow 6666/tcp comment '程序 TCP 6666'
ufw allow 8888/udp comment '程序 UDP 8888'

4. 启动 ufw

# 开启服务
ufw enable

# 禁用服务
# ufw disable

5. 查看状态

# 查看状态及规则
ufw status 
# 查看默认的传入/传出策略以及日志级别
ufw status verbose 

# Status: active
# Logging: on (low)
# Default: deny (incoming), allow (outgoing), disabled (routed)
# New profiles: skip
# 
# To                         Action      From
# --                         ------      ----
# 18022/tcp                  ALLOW IN    Anywhere                   # SSH 22
# 80/tcp                     ALLOW IN    Anywhere                   # HTTP 80
# 443/tcp                    ALLOW IN    Anywhere                   # HTTPS 443
# ……

6. 调整删除规则

# 查看规则编号
ufw status numbered

# Status: active
#      To                         Action      From
#      --                         ------      ----
# [ 1] 18022/tcp                  ALLOW IN    Anywhere                   # SSH 22
# [ 2] 80/tcp                     ALLOW IN    Anywhere                   # HTTP 80
# [ 3] 443/tcp                    ALLOW IN    Anywhere                   # HTTPS 443
# ……

# 上述 [1][2][3] 即为规则编号
# 若要删除编号为 3 的规则,运行
ufw delete 3

OK,完成常规防火墙配置,完成服务器部分安全策略提升。