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

Ubuntu只允许中国IPv4进行访问

本文简单写几行命令,作为自己的备忘。实现效果为:22端口全网可通,其他端口仅允许中国IP访问。

1、安装 IPSet

apt update && apt install ipset -y

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

mkdir /opt/chnroute/ && vim /opt/chnroute/chnroute.sh

3、写入chnroute.sh,主要功能为获取中国IPv4并写入ipset

#!/bin/bash
ipset create chnroute hash:net maxelem 65536
wget --no-check-certificate -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'| awk -F\| '/CN\|ipv4/ { printf("%s/%d\n", $4, 32-log($5)/log(2)) }'>/opt/chnroute/chnroute.txt
ipset flush chnroute
while read ip;do
 ipset add chnroute $ip
done</opt/chnroute/chnroute.txt
ipset save chnroute >/opt/chnroute/chnroute.conf

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

chmod +x /opt/chnroute/chnroute.sh && /opt/chnroute/chnroute.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 chnroute src -p tcp -j ACCEPT
iptables -A INPUT -m set --match-set chnroute src -p udp -j ACCEPT
iptables -A INPUT -p tcp -j DROP
iptables -A INPUT -p udp -j DROP
iptables -P INPUT DROP