SPB Git

Repository Public

semgrep.py 14.2 KB 281 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/audit/runners/semgrep.py8# Module           : Security9# Repository       : https://git.spboucher.ai/qyvora10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Semgrep runner: custom QYVORA rules + cached registry packs, local and offline.4243How source confidentiality is ensured (verified against `semgrep scan --help` of the pinned version):44  * only local rule files are passed to `--config` (the custom rules of security/policies/semgrep and the45    registry packs cached by install-tools.sh): Semgrep contacts its registry only for `--config auto`,46    `p/...` or `r/...` values, none of which is used here;47  * `--metrics=off` and SEMGREP_SEND_METRICS=off disable usage metrics; `--disable-version-check` removes48    the version ping; `--oss-only` keeps the community engine; there is no login, so no upload of findings;49  * on macOS the process runs under `sandbox-exec` with a profile that denies every network operation,50    so a successful run also demonstrates that nothing was sent. The result records whether the sandbox51    was applied.5253Standalone: python3 security/audit/runners/semgrep.py [--full]54"""5556from __future__ import annotations5758import hashlib59import json60import os61import re62import shutil63import sys64from pathlib import Path6566sys.path.insert(0, str(Path(__file__).resolve().parents[1]))67from lib.common import (FAILED, POLICIES, REPO, RUN, TOOLS_HOME, Context, apply_triage, finding,  # noqa: E40268                        load_json, not_run, run_cmd, tool_pins, tool_result, which, write_json)6970RULES = POLICIES / "semgrep"71REGISTRY = TOOLS_HOME / "semgrep-registry"72NO_NETWORK = "(version 1)(allow default)(deny network*)"73COVERAGE = (74    "Semgrep community engine on Swift (support level: experimental; single-file, no cross-function data flow). "75    "Custom rules in security/policies/semgrep (counts in the metrics): syntax-tree pattern rules for "76    "UserDefaults writes, non-constant-time ==/!= on tag/MAC/secret names and trap calls; the other rules are "77    "regex rules that match text line by line, comments included, and cannot follow a value across lines or "78    "through renaming (`try! $X` had to be a regex: the Swift pattern also matches `try` and `try?`). "79    "Semgrep's Swift parser rejects some Swift 6 constructs of this code base (#Preview, ~Copyable, "80    "nonisolated(unsafe), `do throws`): in the files listed under files_with_parse_errors the pattern rules "81    "see a partial tree and may miss matches; regex rules are unaffected. "82    "They catch constructs by name and shape: logging calls mentioning secret-named values, pasteboard use "83    "outside QClipboard, generators other than SystemRandom, http:// literals, server-trust overrides, weak "84    "Keychain classes, file writes outside FileStore, try!/fatalError/precondition in input-handling modules, "85    "runtime debug switches. They do not prove the absence of a leak: a secret held in a neutrally named "86    "variable, a timing leak that is not an == on a named tag, or a trap by array index or arithmetic "87    "overflow is invisible to them (covered by the fuzzing, timing and review parts of the audit). "88    "Registry packs (rules only, cached locally): p/swift and p/secrets; the p/mobsfscan pack is the rule "89    "set of mobsfscan, which the mobsfscan runner executes, so it is not run a second time here."90)919293def _version(exe: str) -> str:94    code, out, _, _ = run_cmd([exe, "--disable-version-check", "--version"], env={"SEMGREP_SEND_METRICS": "off"})95    return out.strip().splitlines()[-1] if code == 0 and out.strip() else ""969798def _sandbox_prefix() -> list[str]:99    sb = shutil.which("sandbox-exec")100    if not sb:101        return []102    code, _, _, _ = run_cmd([sb, "-p", NO_NETWORK, "/usr/bin/true"])103    return [sb, "-p", NO_NETWORK] if code == 0 else []104105106def _rule_meta() -> dict:107    """id -> {kind, qy_severity, cwe, masvs, message} read from the custom rule files (tiny YAML subset)."""108    meta: dict = {}109    for f in sorted(RULES.glob("qyvora-*.yaml")):110        current = None111        for line in f.read_text().splitlines():112            m = re.match(r"\s*- id:\s*(\S+)", line)113            if m:114                current = m.group(1)115                meta[current] = {"file": f.name}116                continue117            if current:118                m = re.match(r"\s+(kind|qy_severity|cwe|masvs):\s*\"?([^\"]+)\"?\s*$", line)119                if m:120                    meta[current][m.group(1)] = m.group(2).strip()121    return meta122123124def _line(path: Path, n: int) -> str:125    try:126        return path.read_text(errors="replace").splitlines()[n - 1].strip()127    except (OSError, IndexError):128        return ""129130131def run_tests(exe: str) -> dict:132    """`semgrep --test` over the custom rules: each rule has positive (ruleid) and negative (ok) snippets."""133    cmd = _sandbox_prefix() + [exe, "--test", "--metrics=off", "--disable-version-check", str(RULES)]134    code, out, err, secs = run_cmd(cmd, env={"SEMGREP_SEND_METRICS": "off"}, timeout=600)135    text = out + err136    m = re.search(r"(\d+)/(\d+): ", text)137    passed, total = (int(m.group(1)), int(m.group(2))) if m else (0, 0)138    ok = code == 0 and "All tests passed" in text and total > 0139    return {"passed": passed if ok else passed, "total": total, "ok": ok, "duration_s": round(secs, 1),140            "output_tail": text.strip()[-600:] if not ok else ""}141142143def run(ctx: Context) -> dict:144    exe = which("semgrep")145    if not exe:146        return not_run("semgrep", "static", "semgrep is not installed (run security/audit/install-tools.sh)", COVERAGE)147    version = _version(exe)148    pin = (tool_pins().get("tools", {}).get("semgrep", {}) or {}).get("version", "")149    scopes = load_json(RULES / "scopes.json", {}) or {}150    inventory_rules = set((scopes.get("inventory_rules") or {}).get("rules", []))151    exclusions = scopes.get("exclusions", [])152    meta = _rule_meta()153    sandbox = _sandbox_prefix()154    env = {"SEMGREP_SEND_METRICS": "off", "SEMGREP_ENABLE_VERSION_CHECK": "0"}155156    tests = run_tests(exe)157    records = [{158        "area": "static", "name": "semgrep custom rule tests (semgrep --test)", "algorithm": "", "parameter_set": "",159        "cases": tests["total"], "passed": tests["passed"], "failed": tests["total"] - tests["passed"],160        "skipped": 0, "note": "one positive and one negative snippet set per rule",161    }]162163    results, errors, scanned, commands, packs, skipped_scopes = [], [], set(), [], {}, []164    total_secs = 0.0165    for scope in scopes.get("scopes", []):166        cfg = scope["config"]167        if cfg.startswith("registry:"):168            name = cfg.split(":", 1)[1]169            path = REGISTRY / f"{name}.yaml"170            if not path.exists() or path.stat().st_size == 0:171                skipped_scopes.append(f"p/{name}: pack not cached (install-tools.sh could not fetch it)")172                continue173            fetched = (REGISTRY / f"{name}.yaml.fetched")174            packs[f"p/{name}"] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),175                                  "fetched": fetched.read_text().strip() if fetched.exists() else "unknown"}176        else:177            path = RULES / cfg178        targets = [t for t in scope["targets"] if (REPO / t).exists()]179        if not targets:180            continue181        raw = ctx.raw_path(f"semgrep-{Path(cfg.replace(':', '-')).stem}.json")182        cmd = sandbox + [exe, "scan", "--metrics=off", "--disable-version-check", "--oss-only", "--json", "--quiet",183                         "--no-git-ignore", "--config", str(path), "-o", str(raw)] + targets184        code, _, err, secs = run_cmd(cmd, env=env, timeout=1800)185        total_secs += secs186        commands.append(" ".join(c if " " not in c else repr(c) for c in cmd[len(sandbox):]))187        data = load_json(raw)188        if code not in (0, 1) or data is None:189            return tool_result(tool="semgrep", category="static", status=FAILED, version=version,190                               reason=f"semgrep exited {code} on {cfg}: {err.strip()[-400:]}", coverage=COVERAGE,191                               duration_s=total_secs, tests=records)192        for r in data.get("results", []):193            r["_scope"] = cfg194            results.append(r)195        errors += [f"{cfg}: {e.get('message', '')[:200]}" for e in data.get("errors", [])]196        scanned.update(data.get("paths", {}).get("scanned", []))197198    findings, inventory, suppressed, occurrence = [], {}, {}, {}199    seen = set()200    results.sort(key=lambda r: (r["path"], r["start"]["line"], r["check_id"]))201    for r in results:202        if r["_scope"].startswith("qyvora"):203            rule = r["check_id"].split(".")[-1]204        else:  # registry rule: drop the local cache path that Semgrep prefixes to the identifier205            rule = r["check_id"].split("semgrep-registry.")[-1]206        path, line = r["path"], r["start"]["line"]207        key = (rule, path, line)208        if key in seen:209            continue210        seen.add(key)211        hit = next((e for e in exclusions if e["rule"] == rule and path.startswith(e["path"])), None)212        if hit:213            suppressed.setdefault(f"{rule} @ {hit['path']}", {"count": 0, "justification": hit["justification"]})["count"] += 1214            continue215        text = _line(REPO / path, line)216        # Identical lines in one file (e.g. the same precondition twice) get distinct fingerprints.217        occurrence[(rule, path, text)] = occurrence.get((rule, path, text), 0) + 1218        nth = occurrence[(rule, path, text)]219        evidence = text if nth == 1 else f"{text}  [occurrence {nth}]"220        if rule in inventory_rules:221            inventory.setdefault(rule, []).append({"location": f"{path}:{line}", "line": text[:200]})222            continue223        extra = r.get("extra", {})224        m = meta.get(rule, {})225        if rule in meta:226            severity = m.get("qy_severity", "medium")227            cwe, masvs = m.get("cwe", ""), m.get("masvs", "")228        else:229            severity = {"ERROR": "high", "WARNING": "medium", "INFO": "low"}.get(extra.get("severity", ""), "low")230            md = extra.get("metadata", {})231            cwe = md.get("cwe", "")232            cwe = (cwe[0] if isinstance(cwe, list) and cwe else cwe) or ""233            cwe = str(cwe).split(":")[0]234            masvs = str(md.get("masvs", "") or "")235        findings.append(finding(236            title=f"{rule}: {text[:90]}" if text else rule, severity=severity, location=f"{path}:{line}",237            tool="semgrep", rule=rule, description=" ".join(extra.get("message", "").split()),238            cwe=cwe, masvs=masvs, area="app" if path.startswith("App/") else "engine", evidence=evidence,239            recommendation="Review the match; fix it, or record a justified triage entry in security/policies/triage.json."))240    findings = apply_triage(findings)241    write_json(ctx.raw_path("semgrep-inventory.json"), inventory)242243    for rule, items in sorted(inventory.items()):244        records.append({"area": "static", "name": f"semgrep inventory: {rule}", "algorithm": "", "parameter_set": "",245                        "cases": len(items), "passed": len(items), "failed": 0, "skipped": 0,246                        "note": "constructs listed for manual review (not defects); see raw/semgrep-inventory.json"})247248    custom_ids = sorted(meta)249    metrics = {250        "custom_rules": len(custom_ids),251        "custom_rules_pattern": sum(1 for r in meta.values() if r.get("kind") == "pattern"),252        "custom_rules_regex": sum(1 for r in meta.values() if r.get("kind") == "regex"),253        "rule_tests_passed": tests["passed"], "rule_tests_total": tests["total"],254        "registry_packs": packs,255        "registry_packs_not_run": skipped_scopes,256        "files_scanned": len(scanned),257        "raw_matches": len(seen),258        "findings": len(findings),259        "inventory_matches": {k: len(v) for k, v in sorted(inventory.items())},260        "suppressed_by_scope": suppressed,261        "engine_errors": sorted(set(errors))[:40],262        "files_with_parse_errors": sorted({m.group(1) for e in errors for m in [re.search(r"at line (\S+?):\d+", e)] if m}),263        "network": "denied by sandbox-exec (deny network*)" if sandbox else "not sandboxed (sandbox-exec unavailable); flags only",264        "pinned_version": pin, "version_matches_pin": version == pin,265    }266    status = RUN267    reason = ""268    if not tests["ok"]:269        status = FAILED270        reason = f"semgrep --test: {tests['passed']}/{tests['total']} rule tests passed. {tests['output_tail']}"271    elif skipped_scopes:272        reason = "registry part incomplete: " + "; ".join(skipped_scopes)273    return tool_result(tool="semgrep", category="static", status=status, version=version, reason=reason,274                       command=" && ".join(commands), duration_s=total_secs + tests["duration_s"],275                       coverage=COVERAGE, metrics=metrics, tests=records, findings=findings,276                       artifacts=["security/reports/raw/semgrep-*.json"])277278279if __name__ == "__main__":280    print(json.dumps(run(Context("full" if "--full" in sys.argv else "quick")), indent=2))281
Files main
Menu

Theme