"""
AIPTX Beast Mode - WAF Signatures Database
==========================================

Comprehensive database of WAF signatures for fingerprinting.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Any


@dataclass
class WAFSignatureEntry:
    """Entry in the WAF signature database."""
    waf_id: str
    name: str
    vendor: str
    detection_patterns: dict[str, list[str | re.Pattern]] = field(default_factory=dict)
    block_status_codes: list[int] = field(default_factory=list)
    typical_block_messages: list[str] = field(default_factory=list)
    known_weaknesses: list[str] = field(default_factory=list)
    difficulty_rating: int = 5  # 1-10, higher = harder to bypass


WAF_SIGNATURES_DB: dict[str, WAFSignatureEntry] = {
    "cloudflare": WAFSignatureEntry(
        waf_id="cloudflare",
        name="Cloudflare WAF",
        vendor="Cloudflare",
        detection_patterns={
            "headers": [
                "cf-ray",
                "cf-cache-status",
                "cf-request-id",
                re.compile(r"__cfduid"),
            ],
            "body": [
                re.compile(r"cloudflare", re.I),
                re.compile(r"ray id:", re.I),
                re.compile(r"attention required", re.I),
            ],
            "server": [re.compile(r"cloudflare", re.I)],
        },
        block_status_codes=[403, 503, 520, 521, 522, 523, 524, 525, 526],
        typical_block_messages=[
            "Access denied",
            "Checking your browser",
            "Please complete the security check",
        ],
        known_weaknesses=[
            "Unicode normalization bypass",
            "Double encoding bypass",
            "IPv6 origin access",
        ],
        difficulty_rating=7,
    ),

    "aws_waf": WAFSignatureEntry(
        waf_id="aws_waf",
        name="AWS WAF",
        vendor="Amazon Web Services",
        detection_patterns={
            "headers": [
                "x-amzn-requestid",
                "x-amz-cf-id",
                "x-amz-id-2",
            ],
            "body": [
                re.compile(r"request blocked", re.I),
            ],
            "server": [re.compile(r"awselb|cloudfront", re.I)],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "Request blocked",
            "Forbidden",
        ],
        known_weaknesses=[
            "Version comment bypass (MySQL)",
            "Case variation",
            "Parameter pollution",
        ],
        difficulty_rating=6,
    ),

    "akamai": WAFSignatureEntry(
        waf_id="akamai",
        name="Akamai Kona Site Defender",
        vendor="Akamai",
        detection_patterns={
            "headers": [
                "x-akamai-transformed",
                "akamai-grn",
            ],
            "cookies": [
                re.compile(r"ak_bmsc"),
                re.compile(r"bm_sz"),
            ],
            "body": [
                re.compile(r"akamai", re.I),
                re.compile(r"reference#", re.I),
            ],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "Access Denied",
            "Reference #",
        ],
        known_weaknesses=[
            "Mixed case keywords",
            "Comment injection",
            "Operator substitution (|| for OR)",
        ],
        difficulty_rating=8,
    ),

    "imperva": WAFSignatureEntry(
        waf_id="imperva",
        name="Imperva Incapsula",
        vendor="Imperva",
        detection_patterns={
            "headers": [
                "x-iinfo",
            ],
            "cookies": [
                re.compile(r"incap_ses_"),
                re.compile(r"visid_incap_"),
                re.compile(r"nlbi_"),
            ],
            "body": [
                re.compile(r"incapsula", re.I),
                re.compile(r"incident id", re.I),
            ],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "Request unsuccessful",
            "Incident ID",
        ],
        known_weaknesses=[
            "GBK encoding bypass",
            "Hex encoding",
            "Newline character substitution",
        ],
        difficulty_rating=8,
    ),

    "modsecurity": WAFSignatureEntry(
        waf_id="modsecurity",
        name="ModSecurity",
        vendor="Trustwave (Open Source)",
        detection_patterns={
            "headers": [
                "x-mod-security",
            ],
            "body": [
                re.compile(r"mod_security", re.I),
                re.compile(r"modsecurity", re.I),
                re.compile(r"owasp", re.I),
            ],
            "server": [re.compile(r"mod_security", re.I)],
        },
        block_status_codes=[403, 406],
        typical_block_messages=[
            "Not Acceptable",
            "Mod_security",
        ],
        known_weaknesses=[
            "Paranoia level dependent",
            "Tab character bypass",
            "XOR operator substitution",
            "Comment between keywords",
        ],
        difficulty_rating=5,  # Depends heavily on configuration
    ),

    "f5_asm": WAFSignatureEntry(
        waf_id="f5_asm",
        name="F5 BIG-IP ASM",
        vendor="F5 Networks",
        detection_patterns={
            "headers": [
                "x-wa-info",
            ],
            "cookies": [
                re.compile(r"bigipserver"),
                re.compile(r"^ts[a-zA-Z0-9]{16,}"),
            ],
            "body": [
                re.compile(r"the requested url was rejected", re.I),
                re.compile(r"support id", re.I),
            ],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "The requested URL was rejected",
            "Support ID",
        ],
        known_weaknesses=[
            "Parameter pollution",
            "Encoding variations",
        ],
        difficulty_rating=7,
    ),

    "barracuda": WAFSignatureEntry(
        waf_id="barracuda",
        name="Barracuda WAF",
        vendor="Barracuda Networks",
        detection_patterns={
            "cookies": [
                re.compile(r"barra_counter_session"),
            ],
            "body": [
                re.compile(r"barracuda", re.I),
                re.compile(r"you have been blocked", re.I),
            ],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "You have been blocked",
        ],
        known_weaknesses=[
            "Case variation",
            "URL encoding",
        ],
        difficulty_rating=5,
    ),

    "sucuri": WAFSignatureEntry(
        waf_id="sucuri",
        name="Sucuri CloudProxy",
        vendor="Sucuri (GoDaddy)",
        detection_patterns={
            "headers": [
                "x-sucuri-id",
                "x-sucuri-cache",
            ],
            "body": [
                re.compile(r"sucuri", re.I),
                re.compile(r"cloudproxy", re.I),
            ],
            "server": [re.compile(r"sucuri", re.I)],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "Access Denied - Sucuri",
        ],
        known_weaknesses=[
            "Standard encoding bypasses",
        ],
        difficulty_rating=4,
    ),

    "wordfence": WAFSignatureEntry(
        waf_id="wordfence",
        name="Wordfence",
        vendor="Defiant (WordPress)",
        detection_patterns={
            "cookies": [
                re.compile(r"wfwaf-authcookie"),
            ],
            "body": [
                re.compile(r"wordfence", re.I),
                re.compile(r"blocked by wordfence", re.I),
                re.compile(r"your access to this site has been limited", re.I),
            ],
        },
        block_status_codes=[403, 503],
        typical_block_messages=[
            "Blocked by Wordfence",
            "Your access has been limited",
        ],
        known_weaknesses=[
            "Longer payloads (may bypass regex)",
            "Alternative event handlers",
            "Plugin-specific bypasses",
        ],
        difficulty_rating=4,
    ),

    "fortinet": WAFSignatureEntry(
        waf_id="fortinet",
        name="Fortinet FortiWeb",
        vendor="Fortinet",
        detection_patterns={
            "headers": [
                "fortiwafsid",
            ],
            "cookies": [
                re.compile(r"cookiesession1"),
            ],
            "body": [
                re.compile(r"fortinet", re.I),
                re.compile(r"fortiweb", re.I),
            ],
            "server": [re.compile(r"forti", re.I)],
        },
        block_status_codes=[403],
        typical_block_messages=[
            "Attack detected",
        ],
        known_weaknesses=[
            "Encoding bypasses",
            "Case manipulation",
        ],
        difficulty_rating=6,
    ),
}


def get_signature(waf_id: str) -> WAFSignatureEntry | None:
    """Get a WAF signature by ID."""
    return WAF_SIGNATURES_DB.get(waf_id.lower())


def get_all_signatures() -> list[WAFSignatureEntry]:
    """Get all WAF signatures."""
    return list(WAF_SIGNATURES_DB.values())


__all__ = [
    "WAFSignatureEntry",
    "WAF_SIGNATURES_DB",
    "get_signature",
    "get_all_signatures",
]
