#!/usr/bin/env python3 """Vendor the permissively licensed third-party semgrep rule packs (#492). For each source below this script 1. checks out the upstream repository at its pinned commit, 2. copies the selected rule files and their semgrep test files *verbatim* to ``compliance-agent/rules/vendor//upstream/`` (``semgrep --test`` runs on them), together with the upstream LICENSE, 3. writes the pack the agent runs, ``compliance-agent/rules/vendor//pack.yaml``: every kept rule with its id prefixed by the source (``gitlab-``, ``0xdea-``, ``elttam-``) and its ``languages`` in flow style, 4. writes ``rules.json``, the index of the pack (id, languages, first CWE) the control-map test reads, and 5. writes ``NOTICE`` (provenance, licence, what was left out and why) and ``UPSTREAM`` (repository and pinned commit). Licence is the hard rule, as Prüfwerk is a service offered to others: only MIT-licensed rules are vendored. Never the Semgrep registry / semgrep-rules (Semgrep Rules License), opengrep-rules (Commons Clause) or Trail of Bits (AGPL). GitLab's repository mixes licences per directory *and* per file, so every GitLab rule file must carry its ``License: MIT`` header. Usage:: scripts/vendor-semgrep-rules.py # clone at the pins scripts/vendor-semgrep-rules.py --upstream DIR # DIR/ are clones Requires PyYAML. The output is deterministic: running it again at the same pins changes nothing. """ from __future__ import annotations import argparse import fnmatch import json import pathlib import re import shutil import subprocess import sys import tempfile import yaml ROOT = pathlib.Path(__file__).resolve().parent.parent VENDOR = ROOT / "compliance-agent" / "rules" / "vendor" # Rules whose text matches a rule of the Semgrep registry (semgrep/semgrep-rules, # Semgrep Rules License v1.0): the same message or the same patterns. They may # have been ported independently from the same origin (bandit), but a copy # cannot be ruled out, so they are not vendored at all. REGISTRY_LOOKALIKE = "matches a Semgrep registry rule (provenance spot-check); not vendored" # Rules that fire far more often than they find anything on the nightly # fixtures and public samples (noise budget, #492), or that only enumerate code # for a manual audit. Their files are vendored (the licence allows it), the # pack leaves them out. SOURCES = { "gitlab": { "name": "GitLab SAST rules", "url": "https://gitlab.com/gitlab-org/security-products/sast-rules", "commit": "53bf5cf6df3c51b6c02110f5a638b5e6213666cd", "version": "v2.10.1 (2026-09-21)", "licence": "MIT (per-file header `License: MIT (c) GitLab Inc.`)", "copyright": "Copyright (c) 2011-present GitLab Inc.", # Only these, and every rule file in them must say MIT. "not_selected": [ "c/: every file is GPL-2.0 (generated from flawfinder), not MIT", "go/ except crypto/rule-tlsversion: Apache-2.0 ports of gosec, not MIT", "scala/: MIT, but no Scala in the products we scan", "rules/lgpl/: LGPL-3.0 (njsscan/mobsfscan); mobsfscan runs separately", "rules/lgpl-cc/: LGPL with Commons Clause", "rules/gitlab/: GitLab EE licence", ], "include": [ "csharp/**", "java/**", "javascript/**", "python/**", "go/crypto/rule-tlsversion.*", ], "require_header": "License: MIT (c) GitLab Inc.", "exclude": { "javascript/xss/rule-mustache-escape": REGISTRY_LOOKALIKE, "python/exec/rule-start-process-with-no-shell": REGISTRY_LOOKALIKE, "python/exec/rule-subprocess-popen-shell-true": REGISTRY_LOOKALIKE, "python/ssh/rule-ssh-nohost-key-verification": REGISTRY_LOOKALIKE, "python/flask/rule-app-debug": REGISTRY_LOOKALIKE, "python/deserialization/rule-marshal": REGISTRY_LOOKALIKE, "python/deserialization/rule-dill": REGISTRY_LOOKALIKE, "python/crypto/rule-crypto-encrypt-ec": REGISTRY_LOOKALIKE, }, "drop": { "gitlab-python_assert_rule-assert-used": "16 hits in psf/requests, all in tests; a plain `assert` is not a weakness in our customers' Python", }, }, "0xdea": { "name": "0xdea semgrep-rules (C/C++)", "url": "https://github.com/0xdea/semgrep-rules", "commit": "dae50da6e6e629750f1daec73a01ef9206a372ab", "version": "v2.0.0 + 20 commits (2026-09-25)", "licence": "MIT", "copyright": "Copyright (c) 2022 raptor (Marco Ivaldi)", "not_selected": [ "rules/noisy/: upstream marks these unsuitable for general use", ], "include": ["rules/c/**"], "require_header": None, "exclude": {}, "drop": { "0xdea-raptor-missing-return": "FP storm: 1514 hits in FreeRTOS-Kernel (port macros); a review hint by upstream's own description (code quality / audit aid), not a weakness", "0xdea-raptor-typos": "FP storm: 989 hits in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness", "0xdea-raptor-interesting-api-calls": "FP storm: 718 hits in lwIP; lists every call of an \"interesting\" API for a manual audit", "0xdea-raptor-signed-unsigned-conversion": "FP storm: 221 hits in FreeRTOS-Kernel and lwIP, nearly all benign casts", "0xdea-raptor-suspicious-assert": "FP storm: 176 hits in FreeRTOS-Kernel and lwIP (configASSERT/LWIP_ASSERT on sizes)", "0xdea-raptor-format-string-bugs": "FP storm: 61 hits in lwIP, all literal formats joined with a macro (\"%s\"NEWLINE); our cra-ai-20-c-non-literal-format-string covers the real case", "0xdea-raptor-argv-envp-access": "43 hits on every argv/getenv read; an audit aid, not a weakness", "0xdea-raptor-mismatched-memory-management": "36 hits in lwIP, sampled hits are plain matching malloc/free pairs", "0xdea-raptor-write-into-stack-buffer": "27 hits on every write into a stack array; an audit aid, not a weakness", "0xdea-raptor-integer-truncation": "23 hits in lwIP, sampled hits assign small constants (`x = 1`)", "0xdea-raptor-missing-default-in-switch": "22 hits; a review hint by upstream's own description (code quality / audit aid), not a weakness", "0xdea-raptor-missing-break-in-switch": "intended fallthrough in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness", "0xdea-raptor-pointer-subtraction": "16 hits in lwIP, all `len = end - start` length arithmetic", "0xdea-raptor-high-entropy-assignment": "14 hits, sampled hits are base64 tables and exception-name strings; gitleaks covers committed secrets", }, }, "elttam": { "name": "elttam semgrep-rules", "url": "https://github.com/elttam/semgrep-rules", "commit": "244268562cc92d33f54b8a60a187df5520f91b26", "version": "main (2026-08-03, no tags)", "licence": "MIT (LICENSE names 'Copyright (c) 2020 Semgrep': the MIT text of " "the repository template the first commit came from)", "copyright": "Copyright (c) 2020 Semgrep; rules by elttam", "include": [ "rules/generic/**", "rules/go/**", "rules/java/**", "rules/php/**", "rules/yaml/**", "rules-audit/**", ], "not_selected": [], "require_header": None, "exclude": { # Not vendored at all. "rules/generic/*": "a `mode: join` rule (experimental semgrep join mode, " "no single-file semantics); not vendored", "rules/yaml/kubernetes/*": "derived from Semgrep registry rules " "(same paths and wording, 'Upstream PR 2630'); not vendored", "rules/yaml/github-actions/*": "CI workflow hygiene, not product code; not vendored", "rules-audit/**/entrypoints/*": "enumerates every controller/route for a manual " "audit, not a weakness; not vendored", "rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporter": "one " "of its rules does not parse in semgrep 1.177, which fails the file's test; " "not vendored (the XML variant is)", "rules/php/php-filter-chain-read-from-oracle": "fails its own upstream test in " "semgrep 1.177 (a false positive on a line marked ok); not vendored", "rules-audit/javascript/rand-token": "fails its own upstream test in semgrep " "1.177 (misses a line marked ruleid); not vendored", "rules-audit/**/orm-leak/*": "ORM-leak review hints whose upstream tests name " "rules that do not exist (`semgrep --test` fails); not vendored", "rules-audit/c/lang/security/audit/exec*": "enumerates every process start for a " "manual audit, not a weakness; not vendored", "rules-audit/java/lang/security/audit/processbuilder*": "enumerates every " "ProcessBuilder for a manual audit, not a weakness; not vendored", }, "drop": {}, }, } # What goes into the pack from a rule, in this order; the rest follows sorted. ID_PREFIX = {"gitlab": "gitlab-", "0xdea": "0xdea-", "elttam": "elttam-"} RULE_EXT = (".yml", ".yaml") def run(*args: str, cwd: pathlib.Path | None = None) -> str: return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout def checkout(source: str, spec: dict, upstream: pathlib.Path | None, tmp: pathlib.Path) -> pathlib.Path: if upstream is not None: repo = upstream / source head = run("git", "rev-parse", "HEAD", cwd=repo).strip() if head != spec["commit"]: sys.exit(f"{repo} is at {head}, the pin is {spec['commit']}") return repo repo = tmp / source run("git", "clone", "--quiet", spec["url"] + ".git", str(repo)) run("git", "checkout", "--quiet", spec["commit"], cwd=repo) return repo def matches(rel: str, globs) -> bool: return any(fnmatch.fnmatch(rel, g) for g in globs) def excluded(rel: str, spec: dict) -> str | None: """The reason a file is not vendored, by its stem (``dir/rule-x`` covers ``dir/rule-x.yml``, its test ``dir/rule-x.py`` and a test dir ``dir/rule-x/``).""" for pattern, reason in spec["exclude"].items(): stem = pattern if rel == stem or rel.startswith(stem + ".") or rel.startswith(stem + "/"): return reason if fnmatch.fnmatch(rel, pattern) or fnmatch.fnmatch(rel, pattern + "/*"): return reason return None def is_test_only(path: pathlib.Path) -> bool: return ".test." in path.name or ".fixed." in path.name def namespaced(source: str, rule_id: str) -> str: # No dots: semgrep puts the config's path in front of a rule id with dots, # and the agent strips that prefix at the last id it knows. return ID_PREFIX[source] + re.sub(r"[^A-Za-z0-9_-]", "-", rule_id) def first_cwe(rule: dict) -> str | None: cwe = (rule.get("metadata") or {}).get("cwe") if isinstance(cwe, list): cwe = cwe[0] if cwe else None found = re.match(r"\s*(CWE-\d+)", str(cwe)) if cwe else None return found.group(1) if found else None def flow_list(values) -> str: return "[" + ", ".join(str(v) for v in values) + "]" def emit_rule(rule: dict, new_id: str) -> str: rest = {k: v for k, v in rule.items() if k not in ("id", "languages")} body = yaml.safe_dump( rest, sort_keys=False, allow_unicode=True, width=100, default_flow_style=False ) lines = [f" - id: {new_id}", f" languages: {flow_list(rule['languages'])}"] lines += [" " + line if line else "" for line in body.rstrip("\n").split("\n")] return "\n".join(lines) + "\n" def vendor(source: str, spec: dict, repo: pathlib.Path) -> dict: out = VENDOR / source if out.exists(): shutil.rmtree(out) (out / "upstream").mkdir(parents=True) shutil.copyfile(repo / "LICENSE", out / "LICENSE") kept, left_out, files = [], [], [] for path in sorted(p for p in repo.rglob("*") if p.is_file() and ".git" not in p.parts): rel = path.relative_to(repo).as_posix() if not matches(rel, spec["include"]): continue reason = excluded(rel, spec) if reason: if path.suffix in RULE_EXT and not is_test_only(path): for rule in yaml.safe_load(path.read_text())["rules"]: left_out.append((namespaced(source, rule["id"]), rel, reason)) continue dest = out / "upstream" / rel dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, dest) if path.suffix in RULE_EXT and not is_test_only(path): text = path.read_text() if spec["require_header"] and spec["require_header"] not in text.split("---")[0]: sys.exit(f"{source}: {rel} does not carry '{spec['require_header']}'") files.append(rel) for rule in yaml.safe_load(text)["rules"]: new_id = namespaced(source, rule["id"]) if new_id in spec["drop"]: left_out.append((new_id, rel, spec["drop"][new_id])) else: kept.append((new_id, rel, rule)) unknown = set(spec["drop"]) - {r[0] for r in left_out} if unknown: sys.exit(f"{source}: drop list names rules that do not exist: {sorted(unknown)}") ids = [k[0] for k in kept] if len(ids) != len(set(ids)): sys.exit(f"{source}: duplicate rule ids after namespacing") pack = [ f"# {spec['name']}, vendored by scripts/vendor-semgrep-rules.py; do not edit.", f"# Upstream: {spec['url']} at {spec['commit']}", f"# Licence: {spec['licence']}; see LICENSE and NOTICE next to this file.", f"# Changed from upstream: ids prefixed with '{ID_PREFIX[source]}', rules", "# left out as listed in NOTICE, rules re-serialised into one file.", "rules:", ] text = "\n".join(pack) + "\n" + "".join(emit_rule(rule, new_id) for new_id, _, rule in kept) # The agent reads ids and languages line by line: each rule must have # exactly one `- id:` line, and no other line may look like one. id_lines = [l for l in text.splitlines() if l.strip().startswith("- id:")] if len(id_lines) != len(kept): sys.exit(f"{source}: a rule body contains a line starting with '- id:'") (out / "pack.yaml").write_text(text) # The index the control-map test reads (the agent has no YAML parser): # each rule's id, languages and first CWE id. index = [ {"id": new_id, "languages": rule["languages"], "cwe": first_cwe(rule)} for new_id, _, rule in kept ] (out / "rules.json").write_text(json.dumps(index, indent=1) + "\n") notice = [ f"{spec['name']}", "=" * len(spec["name"]), "", f"Upstream: {spec['url']}", f"Commit: {spec['commit']}", f"Version: {spec['version']}", f"Licence: {spec['licence']}", f"Copyright: {spec['copyright']}", "", "Prüfwerk runs these rules with its own semgrep invocation (--metrics=off,", "local files only). upstream/ holds the selected files unchanged, with", "their semgrep tests. pack.yaml is what the agent runs: the same rules with", f"ids prefixed by '{ID_PREFIX[source]}', re-serialised into one file, without", "the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py.", "", f"Selected from upstream: {', '.join(spec['include'])}", f"Rules in the pack: {len(kept)} (from {len(files)} files)", "", *(["Not selected:", *[f"- {n}" for n in spec["not_selected"]], ""] if spec["not_selected"] else []), "Left out", "--------", "", ] if not left_out: notice.append("Nothing.") for rule_id, rel, reason in sorted(left_out): notice.append(f"- {rule_id} ({rel}): {reason}") (out / "NOTICE").write_text("\n".join(notice) + "\n") (out / "UPSTREAM").write_text(f"{spec['url']} {spec['commit']}\n") return {"kept": len(kept), "left_out": len(left_out), "files": len(files)} def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--upstream", type=pathlib.Path, help="directory with clones named by source") args = parser.parse_args() with tempfile.TemporaryDirectory() as tmp: for source, spec in SOURCES.items(): repo = checkout(source, spec, args.upstream, pathlib.Path(tmp)) print(source, vendor(source, spec, repo)) if __name__ == "__main__": main()