保护源站仅允许cloudflare的IP访问网站

当你的网站受到cc攻击,或者恶意采集等最低成本的解决方法就是使用cloudflare的代理服务。但是如果被攻击者记录了源服务器IP,那么攻击者就可以绕过Cloudflare的代理服务。

为了更好的保护源站服务器可以设置仅允许Cloudflare的ip访问,禁止其他ip的访问请求。可以使用系统防火墙设置规则,也可以使用web服务器进行设置,下面介绍了三种方法,大家根据自己的系统环境任选其一就行。

Cloudflare IP 范围获取地址: https://www.cloudflare.com/zh-cn/ips/

apache配置

<IfModule mod_rewrite.c>
    # 其他URL重写规则
    
    # 访问控制规则
    Order deny,allow
    Deny from all
    
    # 允许Cloudflare IP范围
    Allow from 173.245.48.0/20
    Allow from 103.21.244.0/22
    Allow from 103.22.200.0/22
    Allow from 103.31.4.0/22
    Allow from 141.101.64.0/18
    Allow from 108.162.192.0/18
    Allow from 190.93.240.0/20
    Allow from 188.114.96.0/20
    Allow from 197.234.240.0/22
    Allow from 198.41.128.0/17
    Allow from 162.158.0.0/15
    Allow from 104.16.0.0/13
    Allow from 104.24.0.0/14
    Allow from 172.64.0.0/13
    Allow from 131.0.72.0/22
</IfModule>

nginx配置

location / {
  allow   173.245.48.0/20;
  allow   103.21.244.0/22;
  allow   103.22.200.0/22;
  allow   103.31.4.0/22;
  allow   141.101.64.0/18;
  allow   108.162.192.0/18;
  allow   190.93.240.0/20;
  allow   188.114.96.0/20;
  allow   197.234.240.0/22;
  allow   198.41.128.0/17;
  allow   162.158.0.0/15;
  allow   104.16.0.0/12;
  allow   172.64.0.0/13;
  allow   131.0.72.0/22;
  deny    all;
}

iptables配置

添加cloudflare ips-v4 iptables 白名单的命令:

for i in `curl https://www.cloudflare.com/ips-v4`;
    do iptables -I INPUT -p tcp -m multiport --dports http,https -s $i -j ACCEPT;
done

添加cloudflare ips-v6 iptables 白名单的命令:

for i in `curl https://www.cloudflare.com/ips-v6`;
    do ip6tables -I INPUT -p tcp -m multiport --dports http,https -s $i -j ACCEPT;
done

丢弃白名单以外的 ipv4 80,443 tcp 包:

iptables -A INPUT -p tcp -m multiport --dports http,https -j DROP

丢弃白名单以外的 ipv6 80,443 tcp 包:

ip6tables -A INPUT -p tcp -m multiport --dports http,https -j DROP

开机自启

上面就配置好了IP白名单,但是服务器重启,这些就会丢失,下面就来配置开机自启动。
首先安装 iptables-persistent:

apt install iptables-persistent

完成后运行:

iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6

以上就配置好了开机自启动。

清空规则,还原

当然如果不玩了,要清空上面规则命令如下:

iptables -P INPUT ACCEPT
iptables -F
> /etc/iptables/rules.v4
> /etc/iptables/rules.v6
庄朋龙
庄朋龙

一个爱生活的技术菜鸟

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注