Update owasp2traefik.py

Should fix resulting exported rules to match Traefik standards.
This commit is contained in:
fab 2025-01-03 11:31:58 +01:00 committed by GitHub
parent 93271ca213
commit c7a580c983
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -4,20 +4,50 @@ import json
OUTPUT_DIR = "waf_patterns/traefik/" OUTPUT_DIR = "waf_patterns/traefik/"
def load_owasp_rules(file_path): def load_owasp_rules(file_path):
with open(file_path, "r") as f: try:
return json.load(f) with open(file_path, "r") as f:
return json.load(f)
except FileNotFoundError:
print(f"[-] Error: File '{file_path}' not found.")
exit(1)
except json.JSONDecodeError:
print(f"[-] Error: Invalid JSON in '{file_path}'.")
exit(1)
def generate_traefik_conf(rules): def generate_traefik_conf(rules):
os.makedirs(OUTPUT_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True)
config_file = os.path.join(OUTPUT_DIR, "middleware.toml") config_file = os.path.join(OUTPUT_DIR, "middleware.toml")
with open(config_file, "w") as f: try:
f.write("[http.middlewares]\n") with open(config_file, "w") as f:
for rule in rules: f.write("[http.middlewares]\n\n")
f.write(f"[http.middlewares.bad_bot_block_{rule['category']}]\n") rule_counter = 1 # Unique identifier for each middleware
f.write(f" [http.middlewares.bad_bot_block_{rule['category']}.plugin.badbot]\n")
f.write(f" userAgent = [\"{rule['pattern']}\"]\n") # Group rules by category
print(f"[+] Traefik WAF rules generated at {config_file}") grouped_rules = {}
for rule in rules:
category = rule.get("category", "default")
if category not in grouped_rules:
grouped_rules[category] = []
grouped_rules[category].append(rule)
# Write grouped rules to the TOML file
for category, rules_in_category in grouped_rules.items():
f.write(f"[http.middlewares.bad_bot_block_{category}]\n")
f.write(f" [http.middlewares.bad_bot_block_{category}.plugin.badbot]\n")
f.write(" userAgent = [\n")
unique_rules = set() # Use a set to deduplicate rules
for rule in rules_in_category:
# Escape special characters in the pattern
pattern = rule['pattern'].replace('"', '\\"').replace("\\", "\\\\")
unique_rules.add(f' "{pattern}"')
f.write(",\n".join(unique_rules) + "\n")
f.write(" ]\n\n")
print(f"[+] Traefik WAF rules generated at {config_file}")
except IOError as e:
print(f"[-] Error writing to file: {e}")
exit(1)
if __name__ == "__main__": if __name__ == "__main__":
owasp_rules = load_owasp_rules("owasp_rules.json") owasp_rules = load_owasp_rules("owasp_rules.json")