在Ubuntu 24.04下使用UFW禁止国外IP访问SSH(同时支持IPv4/IPv6)并记录被拒IP的步骤如下:
1. 安装必要工具
sudo apt update
sudo apt install ufw git -y
2. 启用IPv6支持(确保UFW同时管理IPv4/IPv6)
sudo sed -i 's/IPV6=no/IPV6=yes/g' /etc/default/ufw
3. 获取中国IP地址段
# 创建IP列表目录
mkdir -p ~/ip-lists && cd ~/ip-lists
# 下载中国IPv4地址段
wget https://raw.githubusercontent.com/herrbischoff/country-ip-blocks/master/ipv4/cn.cidr
# 下载中国IPv6地址段
wget https://raw.githubusercontent.com/herrbischoff/country-ip-blocks/master/ipv6/cn.cidr
4. 添加UFW规则(关键步骤)
# 清空现有SSH规则
sudo ufw delete allow 22/tcp 2>/dev/null
sudo ufw delete allow 22 2>/dev/null
# 允许中国IP访问SSH(IPv4 + IPv6)
for ip in $(cat ~/ip-lists/cn.cidr); do
sudo ufw allow proto tcp from $ip to any port 22 comment 'Allow China SSH'
done
# 添加拒绝规则并记录日志(IPv4)
sudo ufw insert 1 deny proto tcp from any to any port 22 log comment 'Block Non-China SSH (IPv4)'
# 添加拒绝规则并记录日志(IPv6)
sudo ufw insert 1 deny proto tcp from any to any port 22 log comment 'Block Non-China SSH (IPv6)'
5. 启用UFW防火墙
sudo ufw enable
sudo ufw reload
6. 验证规则状态
sudo ufw status numbered
输出应包含类似内容:
To Action From
-- ------ ----
[ 1] 22/tcp DENY IN Anywhere # Block Non-China SSH (IPv4)
[ 2] 22/tcp (v6) DENY IN Anywhere (v6) # Block Non-China SSH (IPv6)
[ 3] 22/tcp ALLOW IN 1.0.1.0/24 # Allow China SSH
[ 4] 22/tcp ALLOW IN 2409:8000::/20 # Allow China SSH
...(更多中国IP规则)
7. 查看被拒IP日志
# 实时监控拒绝日志
sudo tail -f /var/log/ufw.log | grep 'UFW BLOCK.*DPT=22'
# 按日期提取被拒IP
grep 'UFW BLOCK.*DPT=22' /var/log/ufw.log | awk '{print $NF}' | sort -u
重要说明:
-
规则顺序:
insert 1
确保拒绝规则位于规则链顶部,优先于中国IP的允许规则。 -
日志位置:
所有拒绝记录保存在/var/log/ufw.log
,格式示例:[UFW BLOCK] IN=eth0 OUT= MAC=... SRC=123.45.67.89 DST=your.server.ip ... DPT=22 ...
-
更新IP列表(建议每月执行):
cd ~/ip-lists wget -O cn.cidr https://raw.githubusercontent.com/herrbischoff/country-ip-blocks/master/ipv4/cn.cidr wget -O cn.cidr6 https://raw.githubusercontent.com/herrbischoff/country-ip-blocks/master/ipv6/cn.cidr sudo ufw reload
-
防止锁定自己:
操作前确保已添加本地IP白名单:sudo ufw allow from 你的本地IP to any port 22
故障排查:
- 测试连接(从国外IP):
ssh user@your.server -v # 应返回超时或被拒
- 检查规则顺序:
sudo ufw status numbered
- 查看完整日志:
sudo grep -a 'UFW BLOCK' /var/log/ufw.log
此配置实现了:
- 仅允许中国IP访问SSH
- 自动拒绝国外IP并记录日志
- 同时支持IPv4/IPv6
- 日志包含完整连接信息(源IP、时间等)