功能介绍

Use lists to refer to a group of items (such as IP addresses) collectively, by name, in rule expressions of Cloudflare products. You can create your own custom lists or use lists managed by Cloudflare, such as Managed IP Lists.

相关文档链接: https://developers.cloudflare.com/waf/tools/lists/create-dashboard/

由于免费版本只有一个IP列表可以用,所以此处我将它用作白名单可信IP的作用,不要局限思想于此用法。

用法

可以在CloudFlare的各种规则表达式中使用该功能。举例:

  1. 直接通过CloudFlare的WAF功能来编写规则 如图,可以直接对IP源地址与创建的列表的逻辑关系来采取一些措施。可以灵活结果其他字段,例如host是自己的个人笔记域名,Url包括/wp-admin/等。
  2. 在转换规则中使用列表功能来修改一些请求 如图所示,当IP在我定义的可信列表中时候,为请求设置一个特殊的自定义HTTP标头。然后就可以在源站通过识别此字段做一些访问控制(把上面的WAF功能直接通过源站相关配置来实现)。
server
{
        listen 80;
        root /var/www/html;

        location /
        {
                
                if ($http_trusted_request != 1)
                {
                        # 不可信的请求
                }
                
                # 可信的请求
         
                
        }
}

结合Github Actions

可以结合Github Actions来方便我们实时同步最新的可信IP列表

import requests
ips=[]
with open("ips.txt")as f:
    for line in f.readlines():
        line = line.strip()
        if len(line.split(","))==2:
            ips.append({'ip':line.split(",")[0].strip(),'comment':line.split(",")[1].strip()})

headers = {
    'Authorization': 'Bearer XXXXXX',
}
print(ips)
response = requests.put('https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/rules/lists/<LIST_ID>/items', headers=headers, json=ips).json()
print(response)

因为我是在私有仓库来跑的,所以直接将CloudFlare Api的凭证写到了代码里,如果有公开仓库的需求,可以使用Actions secrets
ips.txt的内容可以是这样

1.1.1.1,公司
1.1.1.2,家里

workflow的写法很简单,就是执行这个脚本即可

name: update trustip
on:
  push:
    branches:
      - main
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        python-version: [3.9]
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v2
      with:
        python-version: ${{ matrix.python-version }}
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        python -m pip install requests
        python main.py

详细的接口说明见:https://developers.cloudflare.com/waf/tools/lists/lists-api/endpoints/