|
| 1 | +#!/usr/bin/env bash |
| 2 | +# Agent Repo Benchmark scan. Runs OSV-Scanner, Gitleaks and Semgrep on a repository under hard |
| 3 | +# time limits, and lists the file and line candidates each code check reads. It reads the |
| 4 | +# repository and runs none of its code. |
| 5 | +# Usage: bash scan.sh <repository directory> <output directory> |
| 6 | +set -u |
| 7 | +REPO=$(cd "${1:-.}" && pwd) |
| 8 | +OUT=${2:-/tmp/agent-repo-benchmark} |
| 9 | +mkdir -p "$OUT/bin" |
| 10 | +cd "$OUT" || exit 1 |
| 11 | +export PATH="$OUT/bin:$HOME/.local/bin:$PATH" |
| 12 | +case "$(uname -m)" in aarch64|arm64) OSV_ARCH=arm64; GL_ARCH=arm64 ;; *) OSV_ARCH=amd64; GL_ARCH=x64 ;; esac |
| 13 | +latest() { curl -fsSIL -o /dev/null -w '%{url_effective}' "https://github.com/$1/releases/latest" | sed 's#.*/tag/##'; } |
| 14 | +SKIP=(-g '!.git' -g '!node_modules' -g '!vendor' -g '!dist' -g '!build' -g '!**/test/**' -g '!**/tests/**' -g '!**/docs/**' -g '!**/examples/**' -g '!*.md' -g '!*.lock' -g '!*-lock.json') |
| 15 | + |
| 16 | +# Candidate lines for each code check: where tools are declared, where they run commands, |
| 17 | +# and the words a sandbox, a confirmation, a destructive action or a shared key leaves behind. |
| 18 | +cand() { rg -n -i --no-heading -M 220 "${SKIP[@]}" -e "$2" "$REPO" 2>/dev/null | sed "s#^$REPO/##" | head -40 > "cand-$1.txt"; } |
| 19 | +cand tools '(@tool\b|\.tool\(|registerTool|server\.tool|inputSchema|def tool_|tools\s*=\s*\[|function_tool|ToolDefinition)' |
| 20 | +cand exec '(subprocess\.|os\.system|os\.popen|shell\s*=\s*True|child_process|execSync|spawnSync|\bexecFile\(|\beval\(|Popen\()' |
| 21 | +cand sandbox '(docker|podman|firejail|bubblewrap|bwrap|seccomp|gvisor|nsjail|e2b|sandbox|allowlist|allow_list)' |
| 22 | +cand confirm '(approv|confirm|consent|human.in.the.loop|ask_user|require_approval|yolo)' |
| 23 | +cand destructive '(def (delete|remove|send|publish|pay|transfer|refund)_|"(delete|remove|send|publish|pay|transfer)_[a-z_]+"|rm -rf|rmtree\(|unlink\()' |
| 24 | +cand credentials '((os\.environ|getenv|process\.env)[^\n]{0,40}(key|token|secret|password))' |
| 25 | +cand scope '(allowed_tools|allowedtools|disallowed|denylist|deny_list|permission|scopes?\b)' |
| 26 | + |
| 27 | +# Semgrep reads the five folders with the most tool and command lines, never the whole tree. |
| 28 | +DIRS=$(cat cand-tools.txt cand-exec.txt | cut -d: -f1 | xargs -r -n1 dirname | sort | uniq -c | sort -rn | head -5 | awk -v r="$REPO" '{print r"/"$2}') |
| 29 | +[ -n "$DIRS" ] || DIRS="$REPO" |
| 30 | + |
| 31 | +( |
| 32 | + V=$(latest google/osv-scanner) |
| 33 | + curl -fsSL -o bin/osv-scanner "https://github.com/google/osv-scanner/releases/download/$V/osv-scanner_linux_$OSV_ARCH" && chmod +x bin/osv-scanner \ |
| 34 | + && echo "OSV-Scanner $V" > osv.version \ |
| 35 | + && timeout 150 osv-scanner scan source --recursive --format json "$REPO" > osv.json 2> osv.err |
| 36 | + echo $? > osv.exit |
| 37 | +) & |
| 38 | +( |
| 39 | + V=$(latest gitleaks/gitleaks) |
| 40 | + curl -fsSL "https://github.com/gitleaks/gitleaks/releases/download/$V/gitleaks_${V#v}_linux_$GL_ARCH.tar.gz" | tar -xz -C bin gitleaks \ |
| 41 | + && echo "Gitleaks $V" > gitleaks.version \ |
| 42 | + && timeout 120 gitleaks dir --redact --no-banner --report-format json --report-path gitleaks.json "$REPO" 2> gitleaks.err |
| 43 | + echo $? > gitleaks.exit |
| 44 | +) & |
| 45 | +( |
| 46 | + timeout 100 uv tool install -q semgrep > semgrep.install 2>&1 || timeout 100 python3 -m pip install -q --user semgrep >> semgrep.install 2>&1 |
| 47 | + if command -v semgrep > /dev/null; then |
| 48 | + echo "Semgrep $(semgrep --version)" > semgrep.version |
| 49 | + # shellcheck disable=SC2086 |
| 50 | + timeout 120 semgrep scan --config p/default --metrics=off --json --jobs 4 --timeout 5 --max-target-bytes 200000 $DIRS > semgrep.json 2> semgrep.err |
| 51 | + fi |
| 52 | + echo $? > semgrep.exit |
| 53 | +) & |
| 54 | +wait |
| 55 | + |
| 56 | +python3 - "$OUT" "$REPO" <<'PY' |
| 57 | +import json, os, sys |
| 58 | +out, repo = sys.argv[1], sys.argv[2].rstrip("/") + "/" |
| 59 | +rel = lambda p: str(p or "").replace(repo, "", 1) |
| 60 | +def load(name): |
| 61 | + try: |
| 62 | + with open(os.path.join(out, name)) as f: |
| 63 | + return json.load(f) |
| 64 | + except Exception: |
| 65 | + return None |
| 66 | +def text(name): |
| 67 | + try: |
| 68 | + with open(os.path.join(out, name)) as f: |
| 69 | + return f.read().strip() |
| 70 | + except Exception: |
| 71 | + return None |
| 72 | +summary = {"versions": [v for v in (text("osv.version"), text("gitleaks.version"), text("semgrep.version")) if v]} |
| 73 | +osv = load("osv.json") |
| 74 | +if osv is None: |
| 75 | + summary["osv"] = {"ran": False, "exit": text("osv.exit"), "error": (text("osv.err") or "")[-300:]} |
| 76 | +else: |
| 77 | + rows = [] |
| 78 | + for result in osv.get("results", []): |
| 79 | + for pkg in result.get("packages", []): |
| 80 | + vulns = {v.get("id"): v for v in pkg.get("vulnerabilities", [])} |
| 81 | + for group in pkg.get("groups", []): |
| 82 | + try: |
| 83 | + score = float(group.get("max_severity") or 0) |
| 84 | + except ValueError: |
| 85 | + score = 0 |
| 86 | + fixed = any(e.get("fixed") for vid in group.get("ids", []) for a in vulns.get(vid, {}).get("affected", []) for r in a.get("ranges", []) for e in r.get("events", [])) |
| 87 | + p = pkg.get("package", {}) |
| 88 | + rows.append({"package": f'{p.get("name")}@{p.get("version")}', "ids": group.get("ids", [])[:3], "score": score, "fixed": fixed, "source": result.get("source", {}).get("path", "").replace(os.sep, "/").split("/")[-1]}) |
| 89 | + high = [r for r in rows if r["score"] >= 7 and r["fixed"]] |
| 90 | + summary["osv"] = {"ran": True, "vulnerabilities": len(rows), "highOrCriticalWithFix": len(high), "worst": sorted(high, key=lambda r: -r["score"])[:10]} |
| 91 | +gl = load("gitleaks.json") |
| 92 | +summary["gitleaks"] = {"ran": gl is not None, "exit": text("gitleaks.exit"), "findings": [{"rule": g.get("RuleID"), "file": rel(g.get("File")), "line": g.get("StartLine")} for g in (gl or [])][:300]} |
| 93 | +sg = load("semgrep.json") |
| 94 | +if sg is None: |
| 95 | + summary["semgrep"] = {"ran": False, "exit": text("semgrep.exit"), "install": (text("semgrep.install") or "")[-300:]} |
| 96 | +else: |
| 97 | + errors = [r for r in sg.get("results", []) if r.get("extra", {}).get("severity") == "ERROR"] |
| 98 | + summary["semgrep"] = {"ran": True, "results": len(sg.get("results", [])), "errors": [{"rule": r.get("check_id", "").split(".")[-1], "file": rel(r.get("path")), "line": r.get("start", {}).get("line")} for r in errors][:25]} |
| 99 | +# The three scanner checks. A hit outside test, fixture and example paths is "review": a reader |
| 100 | +# opens the line and fails the check only when it holds up. |
| 101 | +import re |
| 102 | +testish = re.compile(r"(^|/)(tests?|__tests__|fixtures?|examples?|docs?|spec)(/|$)|\.(test|spec)\.[a-z]+$|(^|/)test_[^/]*\.py$|_test\.(py|go)$") |
| 103 | +def scanner_check(cid, name, reference, ran, hits): |
| 104 | + status = "not run" if not ran else ("review" if hits else "pass") |
| 105 | + return {"id": cid, "name": name, "reference": reference, "status": status, "hits": hits[:15]} |
| 106 | +leaks = [f for f in summary["gitleaks"]["findings"] if not testish.search(str(f["file"]))] |
| 107 | +summary["checks"] = [ |
| 108 | + {"id": 1, "name": "No known high or critical vulnerability with a fix", "reference": "OWASP ASI04; MCP04", |
| 109 | + "status": "not run" if not summary["osv"].get("ran") else ("fail" if summary["osv"]["highOrCriticalWithFix"] else "pass"), |
| 110 | + "hits": summary["osv"].get("worst", [])}, |
| 111 | + scanner_check(2, "No real credential in the tree", "OWASP MCP01", summary["gitleaks"]["ran"], leaks), |
| 112 | + scanner_check(3, "No error-severity code finding that holds up", "OWASP ASI05; MCP05", summary["semgrep"].get("ran"), summary["semgrep"].get("errors", [])), |
| 113 | +] |
| 114 | +summary["candidates"] = {} |
| 115 | +for name in ("tools", "exec", "sandbox", "confirm", "destructive", "credentials", "scope"): |
| 116 | + lines = (text(f"cand-{name}.txt") or "").splitlines() |
| 117 | + summary["candidates"][name] = lines[:15] |
| 118 | +summary["gitleaks"]["findings"] = summary["gitleaks"]["findings"][:25] |
| 119 | +print(json.dumps(summary, indent=1)) |
| 120 | +PY |
0 commit comments