#!/bin/bash
# UFW 防火墙配置脚本
# 适用于 Ubuntu 22.04

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
  echo "请使用 sudo 运行此脚本"
  exit 1
fi

echo "========================================="
echo "开始配置 UFW 防火墙规则"
echo "========================================="

# 1. 禁用UFW（确保配置过程中不会被锁定）
echo ">>> 临时禁用 UFW"
ufw disable

# 2. 重置UFW到默认状态（清除所有现有规则）
echo ">>> 重置 UFW 到默认状态"
echo "y" | ufw reset

# 3. 设置默认策略：允许所有出站流量，拒绝所有入站流量
echo ">>> 设置默认策略：允许出站，拒绝入站"
ufw default allow outgoing
echo "执行: ufw default allow outgoing"

ufw default deny incoming
echo "执行: ufw default deny incoming"

# 4. 允许白名单IP的所有流量（入站方向）
echo ">>> 添加白名单 IP 规则（允许所有端口和协议）"

echo "执行: ufw allow from 42.192.52.227/32"
ufw allow from 42.192.52.227/32

echo "执行: ufw allow from 43.154.83.213/32"
ufw allow from 43.154.83.213/32

echo "执行: ufw allow from 144.24.164.121/32"
ufw allow from 144.24.164.121/32

echo "执行: ufw allow from 132.145.87.10/32"
ufw allow from 132.145.87.10/32

echo "执行: ufw allow from 140.238.0.0/16"
ufw allow from 140.238.0.0/16

# 5. 允许公网访问指定端口（TCP 和 UDP）
echo ">>> 开放公网端口（0.0.0.0/0）"

echo "执行: ufw allow from 0.0.0.0/0 to any port 443 proto tcp"
ufw allow from 0.0.0.0/0 to any port 443 proto tcp

echo "执行: ufw allow from 0.0.0.0/0 to any port 443 proto udp"
ufw allow from 0.0.0.0/0 to any port 443 proto udp

echo "执行: ufw allow from 0.0.0.0/0 to any port 22333 proto tcp"
ufw allow from 0.0.0.0/0 to any port 22333 proto tcp

echo "执行: ufw allow from 0.0.0.0/0 to any port 22333 proto udp"
ufw allow from 0.0.0.0/0 to any port 22333 proto udp

echo "执行: ufw allow from 0.0.0.0/0 to any port 25000:26000 proto tcp"
ufw allow from 0.0.0.0/0 to any port 25000:26000 proto tcp

echo "执行: ufw allow from 0.0.0.0/0 to any port 25000:26000 proto udp"
ufw allow from 0.0.0.0/0 to any port 25000:26000 proto udp

# 6. 禁止非白名单IP的ICMP请求（ping）
echo ">>> 配置 ICMP 规则（仅允许白名单IP）"
echo "注意：默认拒绝策略已经阻止非白名单的ICMP，白名单IP可以ping"

# 7. 启用UFW
echo ">>> 启用 UFW 防火墙"
echo "y" | ufw enable

# 8. 显示当前规则
echo "========================================="
echo "UFW 防火墙配置完成！当前规则如下："
echo "========================================="
ufw status verbose

echo ""
echo "配置总结："
echo "- 出站流量：全部允许"
echo "- 入站流量：默认拒绝"
echo "- 开放端口：443, 22333, 25000-26000 (TCP/UDP)"
echo "- 白名单IP：42.192.52.227, 43.154.83.213, 144.24.164.121, 132.145.87.10, 140.238.0.0/16"
echo "- ICMP：仅白名单IP可访问"
