diff --git a/docs/AIR_GAP.md b/docs/AIR_GAP.md new file mode 100644 index 00000000..a9bd2e90 --- /dev/null +++ b/docs/AIR_GAP.md @@ -0,0 +1,84 @@ +# Running kit in an air-gapped / no-egress environment + +kit is local-first and makes **zero LLM calls and no telemetry**, so it already +fits a restricted enclave. The one place the default configuration reaches the +public internet is the **triage gate**, which queries package registries to +evaluate a target before install. In an air-gapped network you point those +queries at your **internal mirrors** instead, and run the heavy scanners against +**local databases**. Nothing else phones home. + +> Fail-closed by design: if a registry/mirror is unreachable, triage records a +> CRITICAL ("cannot verify") and withholds `TRIAGE PASSED`, so kit **blocks** the +> install rather than waving it through. Point the endpoints at reachable +> internal mirrors so triage can actually evaluate targets. + +## 1. Point the triage gate at internal mirrors + +The triage script reads its registry hosts from the environment, defaulting to +the public registries. Set these (in the shell, CI job, or the environment kit +runs under) to your internal mirrors: + +| Env var | Default | Used for | +| :-------------------- | :--------------------------- | :----------------------------------------------------------------------- | +| `KIT_NPM_REGISTRY` | `https://registry.npmjs.org` | npm package metadata (`kit triage npm:…`) | +| `KIT_PYPI_INDEX` | `https://pypi.org` | PyPI metadata (`pip:…`); expects `/pypi//json` | +| `KIT_GITHUB_API` | `https://api.github.com` | repo metadata (`repo:…`, `skill` fallback) — GitHub Enterprise API base | +| `KIT_DOCKER_REGISTRY` | `https://hub.docker.com` | image metadata (`docker:…`); expects the `/v2/repositories/` shape | + +The mirror must expose the same JSON shapes as the upstream it mirrors (most +internal npm/PyPI proxies and GitHub Enterprise do). The package/repo name is +the only attacker-influenceable part and is only ever interpolated into the URL +_path_ — the host comes from these operator-set vars, never from the target. + +```bash +export KIT_NPM_REGISTRY="https://npm.corp.internal" +export KIT_PYPI_INDEX="https://pypi.corp.internal" +export KIT_GITHUB_API="https://ghe.corp.internal/api/v3" +export KIT_DOCKER_REGISTRY="https://registry.corp.internal" +kit triage npm:left-pad # now evaluated against the internal mirror +``` + +## 2. Run the scanners locally / offline + +Set **`KIT_AIRGAP=1`** and `kit scan` switches to offline mode: it drops +cloud-only scanners and folds each remaining scanner's offline flags/env in so it +runs against a **pre-synced local DB with no network**. + +```bash +export KIT_AIRGAP=1 +kit scan # → "air-gap mode: offline scanners only (skipping cloud-only: snyk, semgrep)" +``` + +What the mode does per scanner: + +| Scanner | Air-gap behavior | +| :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **trivy** | adds `--offline-scan --skip-db-update` (pre-sync the DB on a connected host with `trivy --download-db-only`, or point `TRIVY_DB_REPOSITORY` at an OCI mirror) | +| **grype** | sets `GRYPE_DB_AUTO_UPDATE=false` (provide a cached DB via `GRYPE_DB_CACHE_DIR`, synced with `grype db update` on a connected host) | +| **osv-scanner** | adds `--offline` (point at a synced local OSV DB) | +| **snyk** | **skipped** — talks to the Snyk cloud | +| **semgrep** | **skipped** — `--config auto` fetches the registry (local-ruleset support is a tracked follow-up) | + +Install the scanners through your internal package mirror or an approved binary +cache; kit never downloads them itself. + +## 3. Bumblebee (known-compromise scan) offline + +- `KIT_BUMBLEBEE_BIN` — use a pre-installed, internally-vetted bumblebee binary + instead of letting kit fetch the pinned release from GitHub. +- `KIT_BUMBLEBEE_CATALOG` — point at an internally-mirrored exposure catalog. +- `KIT_BUMBLEBEE=0` — disable the download/scan entirely where policy forbids it. + +## 4. Known limitation: provenance verification + +cosign/SLSA provenance verification depends on Sigstore's Fulcio CA + Rekor +transparency log, which are public services. Full online verification is not +possible in a no-egress enclave today; use offline-bundle verification where +your toolchain supports it, or treat provenance as an out-of-band, connected-host +check. (Tracked as an air-gap follow-up.) + +## What still never leaves the enclave + +Secret resolution, the memory store, the audit log, `kit check`/`review` +verdicts, agent/MCP config and GitHub-Actions auditing, and SBOM generation are +all fully local and make no network calls regardless of the settings above. diff --git a/skills/triage/scripts/triage.py b/skills/triage/scripts/triage.py index d6d5fcd6..fd721bda 100644 --- a/skills/triage/scripts/triage.py +++ b/skills/triage/scripts/triage.py @@ -33,6 +33,15 @@ NEW_DAYS = 30 # younger than this => warning (insufficient track record) ABANDONED_DAYS = 730 # no release/push in this long => warning +# Registry endpoints — overridable so an AIR-GAPPED / no-egress environment can +# point triage at INTERNAL MIRRORS instead of the public hosts. These are set by +# the operator (trusted env), default to the public registries, and have any +# trailing slash trimmed. See docs/AIR_GAP.md. +NPM_REGISTRY = os.environ.get("KIT_NPM_REGISTRY", "https://registry.npmjs.org").rstrip("/") +PYPI_INDEX = os.environ.get("KIT_PYPI_INDEX", "https://pypi.org").rstrip("/") +GITHUB_API = os.environ.get("KIT_GITHUB_API", "https://api.github.com").rstrip("/") +DOCKER_REGISTRY = os.environ.get("KIT_DOCKER_REGISTRY", "https://hub.docker.com").rstrip("/") + def _get_json(url, headers=None): h = dict(UA) @@ -40,11 +49,11 @@ def _get_json(url, headers=None): h.update(headers) req = urllib.request.Request(url, headers=h) # The URL is intentionally dynamic: a registry-triage tool MUST fetch the - # target's page. SSRF is not reachable here -- the host is a hardcoded, - # allowlisted registry (registry.npmjs.org / pypi.org / api.github.com / - # hub.docker.com) and only the package/repo name is interpolated into the - # PATH (url-quoted for npm/pip, parsed to owner/repo for GitHub). The - # attacker cannot redirect the host. Reviewed false positive. + # target's page. SSRF is not reachable here -- the host comes from an + # operator-set registry constant (public registry by default, or an internal + # mirror via KIT_*_REGISTRY/INDEX/API env) and only the package/repo name is + # interpolated into the PATH (url-quoted for npm/pip, parsed to owner/repo for + # GitHub). The attacker controls the path, never the host. Reviewed false positive. # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected with urllib.request.urlopen(req, timeout=TIMEOUT) as r: return json.load(r), r.status @@ -103,7 +112,7 @@ def emit(self): def triage_npm(rep): pkg = rep.target - url = f"https://registry.npmjs.org/{urllib.parse.quote(pkg, safe='@/')}" + url = f"{NPM_REGISTRY}/{urllib.parse.quote(pkg, safe='@/')}" try: data, _ = _get_json(url) except urllib.error.HTTPError as e: @@ -140,7 +149,7 @@ def triage_npm(rep): def triage_pip(rep): pkg = rep.target - url = f"https://pypi.org/pypi/{urllib.parse.quote(pkg)}/json" + url = f"{PYPI_INDEX}/pypi/{urllib.parse.quote(pkg)}/json" try: data, _ = _get_json(url) except urllib.error.HTTPError as e: @@ -190,7 +199,7 @@ def triage_repo(rep): if token: headers["Authorization"] = f"Bearer {token}" try: - data, _ = _get_json(f"https://api.github.com/repos/{or_}", headers=headers) + data, _ = _get_json(f"{GITHUB_API}/repos/{or_}", headers=headers) except urllib.error.HTTPError as e: if e.code == 404: rep.critical(f"repo '{or_}' not found (or private)") @@ -223,7 +232,7 @@ def triage_docker(rep): repo = rep.target api_repo = repo if "/" in repo else f"library/{repo}" try: - data, _ = _get_json(f"https://hub.docker.com/v2/repositories/{api_repo}") + data, _ = _get_json(f"{DOCKER_REGISTRY}/v2/repositories/{api_repo}") except urllib.error.HTTPError as e: if e.code == 404: rep.critical(f"image '{repo}' not found on Docker Hub") diff --git a/src/cli.ts b/src/cli.ts index fe4e41c2..4384cec8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4492,8 +4492,16 @@ async function cmdScan(): Promise { const { resolveToolBin } = await import("./utils/resolveTool.js"); const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); const { loadBaseline, baselineGet, baselineSet, saveBaseline } = await import("./baseline.js"); - const { SCANNERS } = await import("./scanners.js"); + const { SCANNERS, airGapScanners, isAirGap } = await import("./scanners.js"); const cwd = process.cwd(); + // Air-gap mode (KIT_AIRGAP=1): drop cloud-only scanners and run the rest + // against local DBs with no network. See docs/AIR_GAP.md. + const airgap = airGapScanners(SCANNERS, isAirGap()); + if (isAirGap()) { + console.log( + `${c.dim}air-gap mode: offline scanners only${airgap.dropped.length ? ` (skipping cloud-only: ${airgap.dropped.join(", ")})` : ""}${c.reset}`, + ); + } const config = await loadConfig(resolveConfigPath()); // Resolve scanner tokens (SNYK_TOKEN, …) from a configured tooling Infisical @@ -4514,18 +4522,21 @@ async function cmdScan(): Promise { } } - const { merged, runs } = await runScanners({ - resolve: (bin) => resolveToolBin(bin), - run: async (bin, args) => { - const r = await execFileNoThrow(bin, args, { - timeout: 180_000, - env: { ...process.env, ...toolingTokens }, - }); - return { ok: r.ok, stdout: r.stdout }; + const { merged, runs } = await runScanners( + { + resolve: (bin) => resolveToolBin(bin), + run: async (bin, args) => { + const r = await execFileNoThrow(bin, args, { + timeout: 180_000, + env: { ...process.env, ...airgap.env, ...toolingTokens }, + }); + return { ok: r.ok, stdout: r.stdout }; + }, + hasEnv: (name) => Boolean(process.env[name] || toolingTokens[name]), + detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), }, - hasEnv: (name) => Boolean(process.env[name] || toolingTokens[name]), - detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), - }); + airgap.scanners, + ); // --update-baseline: freeze the current findings as accepted (#59 noise-reduction), // reusing the shared .kit-baseline.json under a "scan" category. diff --git a/src/scanners.test.ts b/src/scanners.test.ts index b591def3..ac42cda3 100644 --- a/src/scanners.test.ts +++ b/src/scanners.test.ts @@ -5,6 +5,9 @@ import { mergeFindings, suppressBaselined, runScanners, + airGapScanners, + isAirGap, + SCANNERS, type ScanDeps, type ScannerDef, } from "./scanners.js"; @@ -83,6 +86,45 @@ describe("runScanners (injected deps)", () => { }); }); +describe("isAirGap", () => { + it("is true for 1/true/yes, false otherwise", () => { + assert.equal(isAirGap({ KIT_AIRGAP: "1" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "true" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "YES" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "0" }), false); + assert.equal(isAirGap({}), false); + }); +}); + +describe("airGapScanners", () => { + it("is a no-op when disabled", () => { + const plan = airGapScanners(SCANNERS, false); + assert.equal(plan.scanners, SCANNERS); + assert.deepEqual(plan.dropped, []); + assert.deepEqual(plan.env, {}); + }); + + it("drops cloud-only scanners and folds offline args/env for the rest", () => { + const plan = airGapScanners(SCANNERS, true); + // cloud-only (snyk, semgrep) are excluded + assert.deepEqual(plan.dropped.sort(), ["semgrep", "snyk"]); + assert.ok(!plan.scanners.some((s) => s.id === "snyk" || s.id === "semgrep")); + // trivy gets its offline flags appended + const trivy = plan.scanners.find((s) => s.id === "trivy")!; + assert.ok(trivy.args.includes("--offline-scan") && trivy.args.includes("--skip-db-update")); + // osv-scanner gets --offline + assert.ok(plan.scanners.find((s) => s.id === "osv-scanner")!.args.includes("--offline")); + // grype contributes offline env, not args + assert.equal(plan.env.GRYPE_DB_AUTO_UPDATE, "false"); + }); + + it("does not mutate the original registry", () => { + const before = JSON.stringify(SCANNERS); + airGapScanners(SCANNERS, true); + assert.equal(JSON.stringify(SCANNERS), before); + }); +}); + describe("suppressBaselined", () => { const merged = mergeFindings([ { diff --git a/src/scanners.ts b/src/scanners.ts index c0e67cb1..b193a3d7 100644 --- a/src/scanners.ts +++ b/src/scanners.ts @@ -24,21 +24,92 @@ export interface ScannerDef { needsToken?: string; /** marker files that make the scanner applicable; undefined = always */ detect?: string[]; + /** Cannot run with no network (needs a hosted backend) — dropped in air-gap mode. */ + cloudOnly?: boolean; + /** Extra args/env applied in air-gap mode so the scanner runs against a local DB. */ + offline?: { args?: string[]; env?: Record }; } export const SCANNERS: ScannerDef[] = [ - { id: "snyk", bin: "snyk", args: ["test", "--sarif"], format: "sarif", needsToken: "SNYK_TOKEN" }, - { id: "trivy", bin: "trivy", args: ["fs", "--format", "sarif", "--quiet", "."], format: "sarif" }, - { id: "grype", bin: "grype", args: ["dir:.", "-o", "sarif", "-q"], format: "sarif" }, + // snyk talks to the Snyk cloud → not usable in a no-egress enclave. { + id: "snyk", + bin: "snyk", + args: ["test", "--sarif"], + format: "sarif", + needsToken: "SNYK_TOKEN", + cloudOnly: true, + }, + { + id: "trivy", + bin: "trivy", + args: ["fs", "--format", "sarif", "--quiet", "."], + format: "sarif", + // run against the pre-synced local DB; never reach out to update it + offline: { args: ["--offline-scan", "--skip-db-update"] }, + }, + { + id: "grype", + bin: "grype", + args: ["dir:.", "-o", "sarif", "-q"], + format: "sarif", + offline: { env: { GRYPE_DB_AUTO_UPDATE: "false" } }, + }, + { + // `--config auto` fetches the semgrep registry; without a local ruleset it + // can't run offline, so it's dropped in air-gap mode (point it at a local + // ruleset via a future KIT_SEMGREP_CONFIG to re-enable — tracked). id: "semgrep", bin: "semgrep", args: ["scan", "--sarif", "--quiet", "--config", "auto", "."], format: "sarif", + cloudOnly: true, + }, + { + id: "osv-scanner", + bin: "osv-scanner", + args: ["--format", "json", "-r", "."], + format: "osv", + offline: { args: ["--offline"] }, }, - { id: "osv-scanner", bin: "osv-scanner", args: ["--format", "json", "-r", "."], format: "osv" }, ]; +/** True when air-gap mode is requested via env (KIT_AIRGAP=1/true/yes). */ +export function isAirGap(env: NodeJS.ProcessEnv = process.env): boolean { + return ["1", "true", "yes"].includes((env.KIT_AIRGAP ?? "").trim().toLowerCase()); +} + +export interface AirGapPlan { + /** Scanners that can run offline, with their offline args folded in. */ + scanners: ScannerDef[]; + /** Env to inject into every scanner run (e.g. disable DB auto-update). */ + env: Record; + /** ids of cloud-only scanners excluded because they need network. */ + dropped: string[]; +} + +/** + * Transform the registry for air-gap mode: drop `cloudOnly` scanners and fold + * each remaining scanner's `offline` args/env in so it runs against a local DB + * with no network. A no-op (returns the input) when `enabled` is false. + */ +export function airGapScanners(defs: ScannerDef[], enabled: boolean): AirGapPlan { + if (!enabled) return { scanners: defs, env: {}, dropped: [] }; + const scanners: ScannerDef[] = []; + const env: Record = {}; + const dropped: string[] = []; + for (const d of defs) { + if (d.cloudOnly) { + dropped.push(d.id); + continue; + } + if (d.offline?.env) Object.assign(env, d.offline.env); + const extra = d.offline?.args ?? []; + scanners.push(extra.length ? { ...d, args: [...d.args, ...extra] } : d); + } + return { scanners, env, dropped }; +} + const RANK: Record = { critical: 4, high: 3, medium: 2, low: 1 }; /** Cross-scanner dedup key: a CVE/GHSA id if present in the finding, else its name. */