Skip to content

Instantly share code, notes, and snippets.

@eaguad1337
Created March 21, 2023 15:23
Show Gist options
  • Save eaguad1337/17438e660ca30b56a16a998f9270ffb7 to your computer and use it in GitHub Desktop.
Save eaguad1337/17438e660ca30b56a16a998f9270ffb7 to your computer and use it in GitHub Desktop.
Cloudflare command for Wazuh
#!/usr/bin/env python3
import sys
import os
import requests
import json
import datetime
# from socket import socket, AF_UNIX, SOCK_DGRAM
ACTION = None
IP = None
PWD = os.getcwd()
TOKEN = None
ACCOUNT = None
USER = None
MODE = 'block' # block or challenge
def main():
# Adding the ip to null route
if ACTION == 'add':
data = {
"mode": MODE,
"configuration": {
"target": "ip",
"value": IP
},
"notes": "Added via OSSEC Command"
}
headers = {
"X-Auth-Email": USER,
"X-Auth-Key": TOKEN,
"Content-Type": "application/json"
}
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT}/firewall/access_rules/rules",
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
debug(f"IP Banned: {IP}")
sys.exit(0)
else:
debug(f"Failed to add {IP} to null route: {response.text}")
sys.exit(1)
# Deleting from null route
# be careful not to remove your default route
elif ACTION == 'delete':
headers = {
"X-Auth-Email": USER,
"X-Auth-Key": TOKEN,
"Content-Type": "application/json"
}
params = {
"mode": MODE,
"configuration_target": "ip",
"configuration_value": IP
}
response = requests.get(
f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT}/firewall/access_rules/rules",
headers=headers,
params=params
)
if response.status_code != 200:
debug(f"Failed to get rule ID for {IP}: {response.text}")
sys.exit(1)
rule_id = response.json()['result'][0]['id']
response = requests.delete(
f"https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/{rule_id}",
headers=headers
)
if response.status_code == 200:
debug(f'IP Banned: {IP}')
sys.exit(0)
else:
debug(f"Failed to remove {IP} from null route: {response.text}")
sys.exit(1)
def debug(msg):
with open('/var/ossec/logs/active-responses.log', 'a') as f:
msg = f"{datetime.datetime.now()} - {sys.argv[0]}: {msg}"
print(msg)
f.write(msg + '\n')
if __name__ == "__main__":
debug('Starting cloudflare-ban.py')
# select(files to read from, files to write to, magic, timeout)
json_alert = json.loads(input())
IP = json_alert['parameters']['alert']['data']['srcip']
ACTION = json_alert['command']
TOKEN = json_alert['parameters']['extra_args'][0]
ACCOUNT = json_alert['parameters']['extra_args'][1]
USER = json_alert['parameters']['extra_args'][2]
debug(f'Attempting to {ACTION} {IP}')
if ACTION != "delete" and ACTION != "add":
debug(f"Invalid action: {ACTION}")
exit(0)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment