Last active
March 27, 2022 17:22
-
-
Save rhashemian/2695fcc0b1872ad4b3b044db9cedd574 to your computer and use it in GitHub Desktop.
Python script to turn on or off "under attack" mode in Cloudflare for one, some, or all sites in your account.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
''' | |
By Robert Hashemian | |
Turn on or off "under attack" mode in Cloudflare for one, some, or all sites in your account. | |
Get api token from: https://dash.cloudflare.com/profile/api-tokens | |
permission needed: #zone_settings:edit | |
Replace xxxxxxxxxxxxxxxx... below with the token. | |
Set file permission to execute or run script fronted with python3 command. | |
Examples: | |
./CFattackmode.py example.com,example.net ON | |
./CFattackmode.py ALLSITES ON | |
./CFattackmode.py ALLSITES OFF | |
''' | |
import urllib.request, json, sys | |
# cloudflare api endpoint | |
urlstr = "https://api.cloudflare.com/client/v4/{}" | |
# required headers | |
hdr = {"Authorization":"Bearer xxxxxxxxxxxxxxxx...", | |
"Content-Type":"application/json"} | |
# based on https://api.cloudflare.com/#zone-settings-change-security-level-setting | |
# mode values: off, essentially_off, low, medium, high, under_attack | |
# set mode for a site | |
def setmode(name,id,mode='medium'): | |
req = urllib.request.Request(urlstr.format(f'zones/{id}/settings/security_level'),data=f'{{"value":"{mode}"}}'.encode(),headers=hdr,method="PATCH") | |
with urllib.request.urlopen(req) as url: | |
data = url.read().decode() | |
# display result | |
print(name,id,data) | |
# check arguments | |
if (len(sys.argv) != 3 or sys.argv[2] not in ['ON','OFF']): | |
print('Needs 2 arguments, site_names/ALLSITES and ON/OFF to set/reset under attack mode!') | |
sys.exit() | |
allsites=sys.argv[1]=="ALLSITES" | |
# convert sites to list | |
sites=[x.strip().lower() for x in sys.argv[1].split(',')] | |
mode = "medium" if sys.argv[2] != "ON" else "under_attack" | |
# print(allsites, mode) | |
# get all sites in one shot | |
req = urllib.request.Request(urlstr.format("zones?per_page=300"),headers=hdr) | |
with urllib.request.urlopen(req) as url: | |
data = url.read().decode() | |
# parse json | |
zones = json.loads(data) | |
# iterate thru sites/zones. if site name matches, take action. unless ALLSITES was requested in which case take action for all sites. | |
for zone in zones["result"]: | |
if (allsites or zone["name"].strip().lower() in sites): | |
setmode(zone["name"],zone["id"],mode) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment