Download scripts/ingest/normalize_owasp_sigma.py from continuum-oss/ccrb: direct link, hf CLI and curl.
- Browser
- Download file 6.5 kB
-
https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/ingest/normalize_owasp_sigma.py
- Command line
-
hf download hf://datasets/continuum-oss/ccrb/scripts/ingest/normalize_owasp_sigma.py
-
curl -L -o normalize_owasp_sigma.py https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/ingest/normalize_owasp_sigma.py
6.5 kB
| """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 | |