
Данный Python скрипт позволяет отправлять уведомления о событиях CloudFlare Firewall в Slack канал:
import os
import requests
import json
import datetime
### CloudFlare ###
token = "XXXXXXXXXXXXXXXX"
zoneId = "XXXXXXXXXXXXXXXX"
timeRange = 5 # Minutes
source = "waf"
action = "drop" # drop|simulate|challenge More info: https://api.cloudflare.com/#firewall-events-list-events
urlCloudFlare = "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/security/events"
### END OF BLOCK ###
### Slack ###
webHook = "https://hooks.slack.com/services/AAAAAAAA/BBBBBBBB/CCCCCCCCCCCCCCCC"
channelId = "XXXXXXXX"
### END OF BLOCK ###
### Functions ###
def slackNotify(ip, country, time, ruleMessage):
headers = {
'Content-type': 'application/json',
}
data = '{"channel":"' + channelId + '","text":"IP address: `' + ip + '` from: `' + country + '` was blocked by `' + source + '` at ' + time + ' UTC' + '\nReason: ' + ruleMessage + '\n\n"}'
response = requests.post(webHook, headers=headers, data=data)
### END OF BLOCK ###
sinceTime = (datetime.datetime.utcnow() - datetime.timedelta(minutes=timeRange))
sinceTime = sinceTime.strftime("%Y-%m-%dT%H:%M:%SZ")
headers = {
'Authorization': 'Bearer ' + token,
}
params = (
('kind', 'firewall'),
('since', sinceTime),
('action', action),
('source', source),
)
response = requests.get(urlCloudFlare, headers=headers, params=params).json()
count = len(response['result'])
for x in range(count):
ip = response['result'][x]['ip']
country = response['result'][x]['country']
time = response['result'][x]['occurred_at']
ruleMessage = response['result'][x]['matches'][0]['metadata']['rule_message']
time = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%SZ')
slackNotify(ip, country, str(time), ruleMessage)
### Print for debugging ###
# response = json.dumps(response, indent=4)
# print(response)
### END OF BLOCK ###
Данный скрипт проверяет события за последние 5 минут, соответственно ставим его в cron с частотой каждые 5 минут.

Для того, чтобы можно было обращаться к CloudFlare по API, нужно в настройках аккаунта создать токен. Дадим ему только право чтения фаервола.


