Ubuntu只允许Cloudflare连接

最近有一个比较特殊的需求,全站是通过Cloudflare去代理分发的,不允许除了Cloudflare之外的IP进行连接,用Ubuntu自带的iptables就可以实现。

1、安装 IPSet

apt update && apt install ipset -y

2、新建 /opt/cloudflare/cloudflare.sh

mkdir /opt/cloudflare/ && vim /opt/cloudflare/cloudflare.sh

3、写入cloudflare.sh,主要功能为获取Cloudflare的IPv4并写入ipset

#!/bin/bash
ipset create cloudflare hash:net maxelem 65536
wget -O /opt/cloudflare/cloudflareIP.txt https://www.cloudflare.com/ips-v4
ipset flush cloudflare
while read ip;do
 ipset add cloudflare $ip
done</opt/cloudflare/cloudflareIP.txt
ipset save cloudflare >/opt/cloudflare/cloudflareIP.conf

4、对 /opt/cloudflare/cloudflare.sh 授权并执行

chmod +x /opt/cloudflare/cloudflare.sh && /opt/cloudflare/cloudflare.sh

5、写入iptables规则

iptables -F
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -m set --match-set cloudflare src -p tcp -j ACCEPT
iptables -A INPUT -m set --match-set cloudflare src -p udp -j ACCEPT
iptables -A INPUT -p tcp -j DROP
iptables -A INPUT -p udp -j DROP
iptables -P INPUT DROP

数据来源:

Cloudflare官方IPv4IPv6