File size: 6,498 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""Normalize OWASP CheatSheetSeries and SigmaHQ detection rules into CCRB corpora."""

from __future__ import annotations

import re
import zipfile
from pathlib import Path
from typing import Any

CODE_FENCE_RE = re.compile(
    r"```([a-zA-Z0-9_+-]*)\s*\n(.*?)```",
    re.DOTALL,
)
HEADING_RE = re.compile(r"^(#{1,4})\s+(.+)$", re.MULTILINE)
ATTACK_TAG_RE = re.compile(r"attack\.(t\d{4}(?:\.\d{3})?)", re.IGNORECASE)


def _clean_ws(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()


def parse_owasp_cheatsheets_zip(
    zip_path: Path,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    """Parse OWASP CheatSheetSeries archive into remediation docs and secure code snippets."""
    rem_docs: list[dict[str, Any]] = []
    code_docs: list[dict[str, Any]] = []

    with zipfile.ZipFile(zip_path, "r") as zf:
        md_files = sorted(
            n
            for n in zf.namelist()
            if "/cheatsheets/" in n and n.lower().endswith(".md") and not n.endswith("Index.md")
        )
        for name in md_files:
            raw_md = zf.read(name).decode("utf-8", errors="replace")
            slug = Path(name).stem
            title_match = re.search(r"^#\s+(.+)$", raw_md, re.MULTILINE)
            sheet_title = _clean_ws(title_match.group(1)) if title_match else slug.replace("_", " ")

            # Split into H2 sections for focused remediation documents
            sections = re.split(r"(?m)^##\s+", raw_md)
            for sec_idx, sec in enumerate(sections[1:], start=1):
                lines = sec.splitlines()
                sec_heading = _clean_ws(lines[0]) if lines else f"Section {sec_idx}"
                sec_body = "\n".join(lines[1:]).strip()
                prose_only = _clean_ws(CODE_FENCE_RE.sub(" ", sec_body))
                if len(prose_only) >= 120:
                    rem_docs.append(
                        {
                            "document_id": f"rem_owasp_{slug}_{sec_idx:02d}",
                            "title": f"{sheet_title} — {sec_heading}",
                            "text": prose_only[:4000],
                            "source": "OWASP CheatSheetSeries",
                            "track": "remediation",
                            "source_id": f"OWASP-{slug}-{sec_idx:02d}",
                            "license": "CC-BY-SA-4.0",
                            "url": f"https://cheatsheetseries.owasp.org/cheatsheets/{slug}.html",
                        }
                    )

            # Extract code snippets with preceding heading context
            for code_idx, match in enumerate(CODE_FENCE_RE.finditer(raw_md), start=1):
                lang = match.group(1).strip().lower() or "text"
                code_body = match.group(2).strip()
                if len(code_body) < 40 or lang in {"text", "txt", "output", "console"}:
                    continue
                prefix_text = raw_md[: match.start()]
                headings = HEADING_RE.findall(prefix_text)
                nearest_heading = _clean_ws(headings[-1][1]) if headings else sheet_title
                code_docs.append(
                    {
                        "document_id": f"code_owasp_{slug}_{code_idx:03d}",
                        "title": f"{sheet_title}: {nearest_heading} ({lang})",
                        "text": f"Context: {sheet_title} - {nearest_heading}\n\n```{lang}\n{code_body[:3000]}\n```",
                        "source": "OWASP CheatSheetSeries",
                        "track": "code",
                        "source_id": f"OWASP-CODE-{slug}-{code_idx:03d}",
                        "license": "CC-BY-SA-4.0",
                        "language": lang,
                        "url": f"https://cheatsheetseries.owasp.org/cheatsheets/{slug}.html",
                    }
                )

    return rem_docs, code_docs


def _extract_yaml_scalar(text: str, key: str) -> str:
    m = re.search(rf"(?m)^{re.escape(key)}:\s*(.+)$", text)
    if not m:
        return ""
    val = m.group(1).strip()
    if (val.startswith("'") and val.endswith("'")) or (val.startswith('"') and val.endswith('"')):
        val = val[1:-1]
    return _clean_ws(val)


def _extract_detection_block(text: str) -> str:
    m = re.search(r"(?ms)^detection:\s*\n((?:[ \t]+.*\n?)+)", text)
    if not m:
        return ""
    return m.group(0).strip()


def parse_sigma_rules_zip(
    zip_path: Path,
    *,
    max_rules: int | None = 3500,
) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
    """Parse SigmaHQ rules archive into security detection code docs and ATT&CK edges."""
    code_docs: list[dict[str, Any]] = []
    edges: list[dict[str, str]] = []

    with zipfile.ZipFile(zip_path, "r") as zf:
        yml_files = sorted(
            n
            for n in zf.namelist()
            if "/rules" in n and (n.endswith(".yml") or n.endswith(".yaml"))
        )
        for name in yml_files:
            if max_rules is not None and len(code_docs) >= max_rules:
                break
            raw_yml = zf.read(name).decode("utf-8", errors="replace")
            status = _extract_yaml_scalar(raw_yml, "status").lower()
            if status in {"deprecated", "unsupported"}:
                continue
            rule_id = _extract_yaml_scalar(raw_yml, "id")
            title = _extract_yaml_scalar(raw_yml, "title")
            desc = _extract_yaml_scalar(raw_yml, "description")
            detection_block = _extract_detection_block(raw_yml)
            if not rule_id or not title or not detection_block:
                continue

            doc_id = f"code_sigma_{re.sub(r'[^A-Za-z0-9_-]+', '_', rule_id)}"
            attack_ids = sorted({m.upper() for m in ATTACK_TAG_RE.findall(raw_yml)})
            for tid in attack_ids:
                edges.append({"src": doc_id, "rel": "detects_attack", "dst": tid})

            text_parts = []
            if desc:
                text_parts.append(desc)
            text_parts.append(f"```yaml\n{detection_block[:2500]}\n```")

            code_docs.append(
                {
                    "document_id": doc_id,
                    "title": f"Sigma Detection: {title}",
                    "text": "\n\n".join(text_parts),
                    "source": "SigmaHQ",
                    "track": "code",
                    "source_id": rule_id,
                    "license": "DRL-1.1",
                    "language": "sigma-yaml",
                    "attack_ids": attack_ids,
                }
            )

    return code_docs, edges