2024-12-21 01:55:56 +01:00
|
|
|
import os
|
|
|
|
|
import json
|
2025-01-07 18:25:11 +01:00
|
|
|
import re
|
2025-01-03 13:14:27 +01:00
|
|
|
import logging
|
|
|
|
|
from pathlib import Path
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
from typing import List, Dict, Optional, Tuple
|
2025-02-09 12:07:05 +00:00
|
|
|
from functools import lru_cache
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# --- Configuration ---
|
|
|
|
|
LOG_LEVEL = logging.INFO # Adjust as needed (DEBUG, INFO, WARNING, ERROR)
|
|
|
|
|
OUTPUT_DIR = Path(os.getenv("OUTPUT_DIR", "waf_patterns/haproxy/"))
|
|
|
|
|
INPUT_FILE = Path(os.getenv("INPUT_FILE", "owasp_rules.json"))
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
UNSUPPORTED_PATTERNS = [
|
|
|
|
|
"@pmFromFile", "@detectSQLi", "@validateByteRange", "@detectXSS", # Core unsupported
|
|
|
|
|
# Add any other unsupported patterns discovered during testing
|
|
|
|
|
]
|
2024-12-21 01:55:56 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# Operator Mapping: ModSecurity -> HAProxy
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
OPERATOR_MAP = {
|
2025-02-28 11:15:14 +01:00
|
|
|
# String Comparisons
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
"@streq": "str -m str",
|
|
|
|
|
"@endsWith": "str -m end",
|
|
|
|
|
"@contains": "str -m sub",
|
2025-02-28 11:15:14 +01:00
|
|
|
"!@eq": "str -m !str", # Negated string equality
|
|
|
|
|
"!@within": "str -m !reg", # Negated regex (approximate)
|
|
|
|
|
# Integer Comparisons (These are handled separately)
|
2025-02-28 11:00:40 +01:00
|
|
|
"@lt": "<",
|
|
|
|
|
"@ge": ">=",
|
|
|
|
|
"@gt": ">",
|
|
|
|
|
"@eq": "==",
|
2025-02-28 11:15:14 +01:00
|
|
|
# IP address matching
|
|
|
|
|
"@ipMatch": "src_ip",
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
}
|
|
|
|
|
|
2024-12-21 01:55:56 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# --- Logging Setup ---
|
|
|
|
|
logging.basicConfig(level=LOG_LEVEL, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# --- Utility Functions ---
|
|
|
|
|
@lru_cache(maxsize=None) # Cache regex compilation for performance
|
2025-01-16 14:02:19 +01:00
|
|
|
def validate_regex(pattern: str) -> bool:
|
2025-02-28 11:15:14 +01:00
|
|
|
"""Validates a regex pattern and checks for excessive complexity."""
|
2025-01-07 18:25:11 +01:00
|
|
|
try:
|
2025-02-28 11:15:14 +01:00
|
|
|
if pattern.count(".*") > 5: # Basic complexity check
|
|
|
|
|
logger.warning(f"Regex potentially too complex: {pattern}")
|
|
|
|
|
# Optionally return False here to *reject* complex regexes
|
2025-01-07 18:25:11 +01:00
|
|
|
re.compile(pattern)
|
|
|
|
|
return True
|
|
|
|
|
except re.error as e:
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.warning(f"Invalid regex: {pattern} - {e}")
|
2025-01-07 18:25:11 +01:00
|
|
|
return False
|
|
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
def load_owasp_rules(file_path: Path) -> List[Dict]:
|
|
|
|
|
"""Loads OWASP rules from the JSON file."""
|
|
|
|
|
try:
|
|
|
|
|
with open(file_path, "r") as f:
|
|
|
|
|
return json.load(f)
|
|
|
|
|
except (FileNotFoundError, json.JSONDecodeError, Exception) as e:
|
|
|
|
|
logger.error(f"Error loading rules from {file_path}: {e}")
|
|
|
|
|
raise # Re-raise to prevent the script from continuing
|
|
|
|
|
|
|
|
|
|
def _sanitize_regex_pattern(pattern: str) -> str:
|
|
|
|
|
"""Helper function to clean up regex patterns."""
|
|
|
|
|
pattern = pattern.replace("@rx ", "").strip()
|
|
|
|
|
pattern = re.sub(r"\(\?i\)", "", pattern) # Remove (?i)
|
|
|
|
|
pattern = pattern.replace("$", r"\$") # $ -> \$
|
|
|
|
|
pattern = re.sub(r"&l(?:brace|cub);?", r"{", pattern) # {
|
|
|
|
|
pattern = re.sub(r"&r(?:brace|cub);?", r"}", pattern) # }
|
|
|
|
|
pattern = re.sub(r"\\\.\*", r"\.*", pattern) # Remove unnecessary escapes
|
|
|
|
|
pattern = re.sub(r"(?<!\\)\.(?![\w])", r"\.", pattern) # Escape .
|
|
|
|
|
pattern = re.sub(r"\(\?:", "(", pattern) # (?: -> (
|
|
|
|
|
return pattern
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def sanitize_pattern(pattern: str, location: str) -> Tuple[Optional[str], str]:
|
2025-01-07 18:25:11 +01:00
|
|
|
"""
|
2025-02-28 11:15:14 +01:00
|
|
|
Sanitizes and converts a ModSecurity pattern to its HAProxy equivalent.
|
|
|
|
|
Returns: (sanitized_pattern, acl_type) or (None, "") if unsupported.
|
2025-01-07 18:25:11 +01:00
|
|
|
"""
|
2025-02-28 11:15:14 +01:00
|
|
|
original_pattern = pattern # Keep for logging
|
|
|
|
|
|
|
|
|
|
# 1. Handle ModSecurity operators *first*.
|
|
|
|
|
for modsec_op, haproxy_op in OPERATOR_MAP.items():
|
|
|
|
|
if pattern.startswith(modsec_op):
|
|
|
|
|
if haproxy_op in ("<", ">=", ">", "=="): # Integer comparisons
|
|
|
|
|
# Integer comparisons are handled *separately*
|
|
|
|
|
return pattern.replace(modsec_op, haproxy_op).strip(), "int"
|
|
|
|
|
else: # String comparisons
|
|
|
|
|
return pattern.replace(modsec_op, haproxy_op).strip(), "hdr_sub"
|
|
|
|
|
|
|
|
|
|
# 2. Check for unsupported patterns *after* operator handling.
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
for directive in UNSUPPORTED_PATTERNS:
|
|
|
|
|
if directive in pattern:
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.warning(f"Skipping unsupported pattern (contains {directive}): {original_pattern}")
|
|
|
|
|
return None, ""
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# 3. Handle regular expressions (@rx)
|
|
|
|
|
if "@rx" in pattern:
|
|
|
|
|
return _sanitize_regex_pattern(pattern), "hdr_reg"
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# 4. If no operator and no @rx, assume it's a simple string match
|
|
|
|
|
return pattern, "hdr_sub"
|
2025-01-07 18:25:11 +01:00
|
|
|
|
|
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
def generate_haproxy_conf(rules: List[Dict]) -> None:
|
|
|
|
|
"""Generates the HAProxy WAF configuration (waf.acl)."""
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
try:
|
|
|
|
|
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
config_file = OUTPUT_DIR / "waf.acl"
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
acl_rules: Dict[str, List[str]] = {} # { location: [acl_rules] }
|
|
|
|
|
int_rules: List[str] = []
|
|
|
|
|
deny_high: List[str] = []
|
|
|
|
|
log_medium: List[str] = []
|
|
|
|
|
tarpit_low: List[str] = []
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# Process each OWASP rule
|
|
|
|
|
for rule in rules:
|
|
|
|
|
rule_id = rule.get("id", "no_id")
|
|
|
|
|
category = rule.get("category", "uncategorized").lower()
|
|
|
|
|
location = rule.get("location", "User-Agent").lower() #important! lowercase
|
|
|
|
|
pattern = rule["pattern"]
|
|
|
|
|
severity = rule.get("severity", "medium").lower()
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
sanitized_pattern, acl_type = sanitize_pattern(pattern, location)
|
2025-01-07 18:25:11 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
if sanitized_pattern is None: # Unsupported/invalid pattern
|
|
|
|
|
continue
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
if acl_type == "int": # Int comparison
|
|
|
|
|
action = "deny" if severity == "high" else "log" if severity == "medium" else "tarpit"
|
|
|
|
|
# Special cases: some locations cannot be used directly
|
|
|
|
|
if location in ("query-string", "request-uri"):
|
|
|
|
|
int_rules.append(f"http-request {action} if {{ {location} {sanitized_pattern} }}")
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
else:
|
2025-02-28 11:15:14 +01:00
|
|
|
int_rules.append(f"http-request {action} if {{ {location},{sanitized_pattern} }}")
|
|
|
|
|
|
|
|
|
|
elif acl_type in ("hdr_reg", "hdr_sub"): # String comparison
|
|
|
|
|
acl_name = f"block_{category}_{rule_id}"
|
|
|
|
|
|
|
|
|
|
# Build the ACL rule string
|
|
|
|
|
if location == "request-uri":
|
|
|
|
|
acl_string = f"acl {acl_name} path_reg -i {sanitized_pattern}"
|
|
|
|
|
elif location == "query-string":
|
|
|
|
|
# No direct query_reg in HAProxy. Need to use path, url, or url_param
|
|
|
|
|
acl_string = f"acl {acl_name} url_param_reg -i {sanitized_pattern}"
|
|
|
|
|
elif location in ("host", "content-type", "referer","user-agent"):
|
|
|
|
|
hdr_func = "hdr_reg" if acl_type == "hdr_reg" else "hdr_sub"
|
|
|
|
|
acl_string = f"acl {acl_name} {hdr_func}({location.replace('-','')}) -i {sanitized_pattern}"
|
|
|
|
|
else:
|
|
|
|
|
logger.warning(f"Unsupported location: {location} for rule: {rule_id}")
|
|
|
|
|
continue # Skip unsupported locations
|
|
|
|
|
|
|
|
|
|
if location not in acl_rules:
|
|
|
|
|
acl_rules[location] = []
|
|
|
|
|
acl_rules[location].append(acl_string)
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
if severity == "high":
|
|
|
|
|
deny_high.append(acl_name)
|
|
|
|
|
elif severity == "medium":
|
|
|
|
|
log_medium.append(acl_name)
|
|
|
|
|
elif severity == "low":
|
|
|
|
|
tarpit_low.append(acl_name)
|
|
|
|
|
|
|
|
|
|
# Write the configuration to the file
|
2025-01-03 13:14:27 +01:00
|
|
|
with open(config_file, "w") as f:
|
|
|
|
|
f.write("# HAProxy WAF ACL rules\n\n")
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# Integer Comparison Rules (if any)
|
|
|
|
|
if int_rules:
|
|
|
|
|
f.write("# Integer Comparison Rules\n")
|
|
|
|
|
for rule in int_rules:
|
|
|
|
|
f.write(f"{rule}\n")
|
|
|
|
|
f.write("\n")
|
|
|
|
|
|
|
|
|
|
# ACL Rules (by location)
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
for location, rules in acl_rules.items():
|
2025-02-28 11:15:14 +01:00
|
|
|
f.write(f"# Rules for {location.title()}\n") # title()
|
|
|
|
|
for rule in rules:
|
|
|
|
|
f.write(f"{rule}\n")
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
f.write("\n")
|
|
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
# Deny/Action Logic
|
|
|
|
|
f.write("# Deny/Action Logic\n")
|
2025-02-28 11:03:13 +01:00
|
|
|
if deny_high:
|
|
|
|
|
f.write(f"http-request deny if {' or '.join(deny_high)}\n")
|
|
|
|
|
if log_medium:
|
|
|
|
|
f.write(f"http-request log if {' or '.join(log_medium)}\n")
|
|
|
|
|
if tarpit_low:
|
|
|
|
|
f.write(f"http-request tarpit if {' or '.join(tarpit_low)}\n")
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.info(f"HAProxy WAF configuration generated at: {config_file}")
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
|
2025-01-03 13:14:27 +01:00
|
|
|
except Exception as e:
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.error(f"Error generating HAProxy configuration: {e}")
|
2025-01-03 13:14:27 +01:00
|
|
|
raise
|
|
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
|
|
|
|
|
|
2025-01-16 14:02:19 +01:00
|
|
|
def main() -> None:
|
2025-02-28 11:15:14 +01:00
|
|
|
"""Main function."""
|
2025-01-03 13:14:27 +01:00
|
|
|
try:
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.info("Loading OWASP rules...")
|
2025-01-03 13:14:27 +01:00
|
|
|
owasp_rules = load_owasp_rules(INPUT_FILE)
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.info(f"Loaded {len(owasp_rules)} rules.")
|
2025-01-03 13:14:27 +01:00
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.info("Generating HAProxy WAF configuration...")
|
2025-01-03 13:14:27 +01:00
|
|
|
generate_haproxy_conf(owasp_rules)
|
|
|
|
|
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.info("HAProxy WAF generation complete.")
|
|
|
|
|
|
2025-01-03 13:14:27 +01:00
|
|
|
except Exception as e:
|
2025-02-28 11:15:14 +01:00
|
|
|
logger.critical(f"Script failed: {e}")
|
|
|
|
|
exit(1) # Exit with an error code
|
|
|
|
|
|
2024-12-21 01:55:56 +01:00
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
Update json2haproxy.py
feat: Implement OWASP CRS to HAProxy WAF conversion with enhanced features
This commit introduces significant improvements to the script for converting OWASP Core Rule Set (CRS) rules into HAProxy Web Application Firewall (WAF) configurations.
Key changes include:
- **Expanded Operator Mapping:** Added more comprehensive mappings between ModSecurity operators and HAProxy equivalents, improving the translation of OWASP rules.
- **Location-Based ACLs:** Implemented support for inspecting different request parameters (User-Agent, Request-URI, Host, etc.) based on the `location` field in the JSON rules, increasing the WAF's coverage.
- **Rule Prioritization:** Introduced rule prioritization based on severity (high, medium, low), allowing for different actions (deny, log, tarpit) to be triggered based on the assessed risk.
- **Improved Regex Handling:** Enhanced regex validation to identify and skip overly complex or invalid patterns, preventing performance issues and potential errors.
- **Clearer ACL Logic:** Restructured the generated `waf.acl` file for better organization, separating ACL definitions from deny logic and grouping rules by request parameter location.
- **Detailed Logging:** Improved logging to provide more specific information about skipped rules, invalid patterns, and other issues, aiding in debugging and configuration.
- **Integer Comparison:** Added capability to use http-request to perform integer comparison instead of strings in the rules.
These enhancements result in a more effective, maintainable, and configurable HAProxy WAF implementation based on the OWASP CRS.
Please note that thorough testing and tuning are still crucial to ensure the WAF is working correctly and not causing false positives.
This commit addresses the following issues:
- Addresses overly aggressive rules causing false positives.
- Implements missing support for ModSecurity operators.
- Enables inspection of request parameters beyond the User-Agent header.
- Provides a more organized and maintainable HAProxy WAF configuration.
2025-02-28 10:58:24 +01:00
|
|
|
main()
|