diff --git a/CHANGELOG.md b/CHANGELOG.md index 8085f1ed..5f9644a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.27.0] - 2026-06-24 + +### Added + +- **No-egress / air-gap support — the offline-enclave stack lands for real (#98, #80).** A 4-deep stacked-PR chain (#83/#84/#85/#93) had squash-merged out of order, leaving it incompletely on main (`[air_gap]` config absent despite "#85 merged"; #84/#93 auto-closed). Reconstructed by rebasing the full stack tip onto current main: + - **`KIT_AIRGAP=1` offline scan mode (#83)** — runs only offline-capable scanners; no network. + - **Signed offline threat-data bundle (#84)** — Ed25519 + SHA-256 verified local threat data; fail-closed on a bad signature. + - **Declarative `[air_gap]` config in `.kit.toml` (#85)** — internal mirror endpoints honored by the triage subprocess even when the env var isn't exported (`process.env` still wins); `air_gap` added to the config schema. + - **Offline provenance verification — `kit verify-provenance` (#93)** — cosign `--offline` against a shipped-in trusted root; fail-closed. + + Net: link triage at internal mirrors (#73), scan against signed local DBs, verify artifact provenance offline, with a tamper-evident + SIEM-exportable audit trail (1.24.0) — nothing reaches the public internet. Pure helpers fixture-tested (33 airgap+triage tests). The cloud scanners (Socket/Snyk) are deliberately out of this path — neither is air-gappable (#103). + ## [1.26.1] - 2026-06-24 ### Changed diff --git a/docs/AIR_GAP.md b/docs/AIR_GAP.md index a9bd2e90..82fd3cef 100644 --- a/docs/AIR_GAP.md +++ b/docs/AIR_GAP.md @@ -12,6 +12,23 @@ queries at your **internal mirrors** instead, and run the heavy scanners against > install rather than waving it through. Point the endpoints at reachable > internal mirrors so triage can actually evaluate targets. +## Declarative config (recommended) + +Everything below can be set with `KIT_*` env vars **or** checked into +`.kit.toml` so the enclave posture is reproducible and versioned. Env vars +override the file when both are set. + +```toml +[air_gap] +enabled = true # turns on offline scan mode +npm_registry = "https://npm.corp.internal" +pypi_index = "https://pypi.corp.internal" +github_api = "https://ghe.corp.internal/api/v3" +docker_registry = "https://registry.corp.internal" +threat_data_dir = "/opt/kit/threat-data" +threat_data_pubkey = "/etc/kit/threat-data.pub" +``` + ## 1. Point the triage gate at internal mirrors The triage script reads its registry hosts from the environment, defaulting to @@ -62,6 +79,36 @@ What the mode does per scanner: Install the scanners through your internal package mirror or an approved binary cache; kit never downloads them itself. +### Verified offline threat-data bundle (signed) + +Stale or tampered threat data silently degrades every verdict. To give the +sync-in a trust chain that is **fully offline-verifiable** (no Fulcio/Rekor), +ship the DBs as a _signed bundle_ and point kit at it: + +```bash +export KIT_AIRGAP=1 +export KIT_THREAT_DATA_DIR=/opt/kit/threat-data +export KIT_THREAT_DATA_PUBKEY=/etc/kit/threat-data.pub # PEM (path or inline) +kit scan +``` + +The bundle dir contains: + +- `manifest.json` — `{ version, artifacts: [{ path, sha256, env? }] }` +- `manifest.json.sig` — a base64 **Ed25519** signature over `manifest.json`, made + on the connected host with the key whose public half is `KIT_THREAT_DATA_PUBKEY` +- the artifacts themselves (e.g. `grype.db`, `osv.db`, a bumblebee catalog) + +kit verifies the manifest **signature**, then the **SHA-256** of every artifact, +then sets each artifact's declared `env` var to its absolute path (e.g. +`GRYPE_DB_CACHE_DIR`) so the scanner uses the verified local DB. **Any failure — +bad signature, checksum mismatch, missing/extra-path artifact — rejects the whole +bundle and `kit scan` refuses to run (fail-closed).** The bundle author declares +the `env` wiring per artifact, so kit hard-codes no scanner-version specifics. + +Build the bundle on a connected host (sync DBs → write manifest with SHA-256 → +`openssl pkeyutl -sign` / equivalent Ed25519 signing), then transfer it in. + ## 3. Bumblebee (known-compromise scan) offline - `KIT_BUMBLEBEE_BIN` — use a pre-installed, internally-vetted bumblebee binary @@ -69,13 +116,69 @@ cache; kit never downloads them itself. - `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 +## 4. Offline provenance verification + +cosign/SLSA verification normally reaches Sigstore's Fulcio CA + Rekor log +(public). `kit verify-provenance` runs cosign **fully offline** instead: it uses +the bundle's inclusion proof (`--offline`) and a **shipped-in** Sigstore +`trusted_root.json` (`--trusted-root`) that you distribute and refresh into the +enclave — no Fulcio/Rekor egress. kit does not reimplement the crypto; it +orchestrates cosign and is **fail-closed** (missing cosign, missing trust root, +missing identity constraints, or any non-zero cosign exit ⇒ NOT verified). + +```bash +kit verify-provenance dist/app.tar.gz \ + --bundle dist/app.sigstore \ + --trusted-root /etc/kit/trusted_root.json \ + --identity "/org/repo/.github/workflows/release.yml@refs/tags/v1" \ + --issuer "https://token.actions.githubusercontent.com" +``` -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.) +Defaults for `--trusted-root` / `--identity` / `--issuer` can live in +`.kit.toml [air_gap]` (`provenance_trusted_root` / `provenance_cert_identity` / +`provenance_cert_issuer`) or the matching `KIT_PROVENANCE_*` env vars, so the +command is just `kit verify-provenance --bundle `. + +**Operational note:** the enclave owner is responsible for distributing and +periodically refreshing `trusted_root.json` (a TUF mirror snapshot or pinned +roots) from a connected host — that is the trust anchor for offline +verification. + +## 5. Memory in a classified enclave + +kit's memory store inherits the **classification of the machine it runs on**. +There is intentionally **no per-row classification column**, for two reasons: + +1. **Under system-high it is redundant.** A workstation accredited at one level + (e.g. SECRET) treats everything on it at that level — every captured row is + already SECRET, so a column adds no information. +2. **kit cannot enforce it.** Multi-level separation is the job of a trusted + reference monitor in the OS (SELinux MLS, labeled IPC/filesystems), not a CLI + reading and writing its own SQLite file. A classification field that kit + manages itself would be advisory metadata dressed up as a control — it would + imply a separation guarantee kit cannot keep. kit does not claim to separate + classification levels internally. + +The operational posture instead: + +- **The whole `memory.db` carries the enclave's level.** Run kit at system-high; + treat the database, its WAL, and any backups at the accredited level. +- **File handling is already conservative.** Encrypted backups and restores are + written `0o600` (owner-only); store `memory.db` on the same labeled volume as + the rest of the enclave's data at that level. +- **Purge = delete the database.** On a system-high machine there is no lower + level to preserve, so spill or decommission response is to destroy `memory.db` + (and backups) per your media-handling procedure, not to filter a column. +- **Capture-time redaction still applies.** `KIT_MEMORY_REDACT` strips secrets + before they ever reach the store (see redaction docs); that is orthogonal to + classification and worth enabling regardless of level. +- **Spill (wrong-level content pasted into a higher machine) is a procedural + matter**, handled by your incident process — not something an application-level + tag can prevent or remediate. + +If you genuinely need a single install to span multiple levels, that is an +OS/MLS platform requirement: accredit the platform for multi-level operation and +run kit on top of it. It is not, and should not be, a kit feature. ## What still never leaves the enclave diff --git a/package-lock.json b/package-lock.json index 64c2869e..78051f5a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.26.1", + "version": "1.27.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.26.1", + "version": "1.27.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index e9563ade..4e04f5ee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.26.1", + "version": "1.27.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/airgap/config.test.ts b/src/airgap/config.test.ts new file mode 100644 index 00000000..277b914e --- /dev/null +++ b/src/airgap/config.test.ts @@ -0,0 +1,64 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { resolveAirGap, airGapTriageEnv } from "./config.js"; + +describe("resolveAirGap", () => { + it("reads settings from .kit.toml [air_gap] when no env is set", () => { + const s = resolveAirGap( + { + enabled: true, + npm_registry: "https://npm.corp", + threat_data_dir: "/opt/td", + threat_data_pubkey: "/etc/k.pub", + }, + {}, + ); + assert.equal(s.enabled, true); + assert.equal(s.npmRegistry, "https://npm.corp"); + assert.equal(s.threatDataDir, "/opt/td"); + assert.equal(s.threatDataPubkey, "/etc/k.pub"); + }); + + it("env overrides the checked-in config value", () => { + const s = resolveAirGap( + { npm_registry: "https://npm.corp" }, + { KIT_NPM_REGISTRY: "https://npm.override" }, + ); + assert.equal(s.npmRegistry, "https://npm.override"); + }); + + it("KIT_AIRGAP truthy enables even if config is silent", () => { + assert.equal(resolveAirGap(undefined, { KIT_AIRGAP: "1" }).enabled, true); + assert.equal(resolveAirGap(undefined, { KIT_AIRGAP: "true" }).enabled, true); + assert.equal(resolveAirGap(undefined, {}).enabled, false); + }); + + it("config enabled=true holds even without the env var", () => { + assert.equal(resolveAirGap({ enabled: true }, {}).enabled, true); + }); + + it("is all-undefined / disabled with empty inputs", () => { + const s = resolveAirGap(undefined, {}); + assert.equal(s.enabled, false); + assert.equal(s.npmRegistry, undefined); + assert.equal(s.threatDataDir, undefined); + }); +}); + +describe("airGapTriageEnv", () => { + it("emits only the mirror vars that resolved to a value", () => { + const env = airGapTriageEnv({ + enabled: true, + npmRegistry: "https://npm.corp", + githubApi: "https://ghe.corp/api/v3", + }); + assert.deepEqual(env, { + KIT_NPM_REGISTRY: "https://npm.corp", + KIT_GITHUB_API: "https://ghe.corp/api/v3", + }); + }); + + it("is empty when no mirrors are configured", () => { + assert.deepEqual(airGapTriageEnv({ enabled: true }), {}); + }); +}); diff --git a/src/airgap/config.ts b/src/airgap/config.ts new file mode 100644 index 00000000..f1ebfa1b --- /dev/null +++ b/src/airgap/config.ts @@ -0,0 +1,69 @@ +/** + * Resolve the effective air-gap posture from `.kit.toml [air_gap]` + env. + * + * The checked-in `.kit.toml` makes the enclave config reproducible; env vars + * (KIT_AIRGAP, KIT_NPM_REGISTRY, …) override it for one-off/CI runs. Pure + + * deterministic so it is fully testable. + */ +import type { kitConfig } from "../config.js"; + +export interface AirGapSettings { + enabled: boolean; + npmRegistry?: string; + pypiIndex?: string; + githubApi?: string; + dockerRegistry?: string; + threatDataDir?: string; + /** Trusted Ed25519 public key — a file path or an inline PEM. */ + threatDataPubkey?: string; + /** Offline provenance: shipped-in Sigstore trusted_root.json + identity constraints. */ + provenanceTrustedRoot?: string; + provenanceCertIdentity?: string; + provenanceCertIssuer?: string; +} + +function envTrue(v: string | undefined): boolean { + return ["1", "true", "yes"].includes((v ?? "").trim().toLowerCase()); +} + +/** env value wins when set (non-empty); otherwise the checked-in config value. */ +function pick(envVal: string | undefined, cfgVal: string | undefined): string | undefined { + const e = envVal?.trim(); + return e ? e : (cfgVal ?? undefined); +} + +export function resolveAirGap( + cfg: kitConfig["air_gap"], + env: NodeJS.ProcessEnv = process.env, +): AirGapSettings { + const ag = cfg ?? {}; + return { + // env KIT_AIRGAP (truthy) OR config enabled; an explicit KIT_AIRGAP=0 does + // NOT force-disable a config-enabled posture (env only adds), keeping the + // checked-in enclave config authoritative unless the operator opts in. + enabled: envTrue(env.KIT_AIRGAP) || ag.enabled === true, + npmRegistry: pick(env.KIT_NPM_REGISTRY, ag.npm_registry), + pypiIndex: pick(env.KIT_PYPI_INDEX, ag.pypi_index), + githubApi: pick(env.KIT_GITHUB_API, ag.github_api), + dockerRegistry: pick(env.KIT_DOCKER_REGISTRY, ag.docker_registry), + threatDataDir: pick(env.KIT_THREAT_DATA_DIR, ag.threat_data_dir), + threatDataPubkey: pick(env.KIT_THREAT_DATA_PUBKEY, ag.threat_data_pubkey), + provenanceTrustedRoot: pick(env.KIT_PROVENANCE_TRUSTED_ROOT, ag.provenance_trusted_root), + provenanceCertIdentity: pick(env.KIT_PROVENANCE_CERT_IDENTITY, ag.provenance_cert_identity), + provenanceCertIssuer: pick(env.KIT_PROVENANCE_CERT_ISSUER, ag.provenance_cert_issuer), + }; +} + +/** + * The `KIT_*` mirror env vars to inject into the triage subprocess so a + * config-declared mirror is honored (triage.py reads these from its env). + * Only includes keys that resolved to a value. + */ +export function airGapTriageEnv(s: AirGapSettings): Record { + const e: Record = {}; + if (s.npmRegistry) e.KIT_NPM_REGISTRY = s.npmRegistry; + if (s.pypiIndex) e.KIT_PYPI_INDEX = s.pypiIndex; + if (s.githubApi) e.KIT_GITHUB_API = s.githubApi; + if (s.dockerRegistry) e.KIT_DOCKER_REGISTRY = s.dockerRegistry; + return e; +} diff --git a/src/airgap/provenance.test.ts b/src/airgap/provenance.test.ts new file mode 100644 index 00000000..0441eae4 --- /dev/null +++ b/src/airgap/provenance.test.ts @@ -0,0 +1,78 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + buildCosignArgs, + missingField, + verifyProvenance, + type ProvenanceVerifyOptions, + type ProvenanceDeps, +} from "./provenance.js"; + +const full: ProvenanceVerifyOptions = { + artifact: "dist/app.tar.gz", + bundle: "dist/app.sigstore", + trustedRoot: "/etc/kit/trusted_root.json", + certIdentity: "/org/repo/.github/workflows/release.yml@refs/tags/v1", + certIssuer: "https://token.actions.githubusercontent.com", +}; + +describe("missingField", () => { + it("returns null when all required fields are present", () => { + assert.equal(missingField(full), null); + }); + it("flags the first missing/empty field", () => { + assert.equal(missingField({ ...full, bundle: "" }), "bundle"); + assert.equal(missingField({ artifact: "a" }), "bundle"); + }); +}); + +describe("buildCosignArgs", () => { + it("builds an offline verify-blob argv with trust root + identity constraints", () => { + assert.deepEqual(buildCosignArgs(full), [ + "verify-blob", + "--offline", + "--trusted-root", + "/etc/kit/trusted_root.json", + "--bundle", + "dist/app.sigstore", + "--certificate-identity", + full.certIdentity, + "--certificate-oidc-issuer", + full.certIssuer, + "dist/app.tar.gz", + ]); + }); +}); + +describe("verifyProvenance (fail-closed)", () => { + const okRun = async () => ({ ok: true, stdout: "Verified OK", stderr: "" }); + + it("verifies when cosign exits 0", async () => { + const deps: ProvenanceDeps = { resolveBin: async () => "/usr/bin/cosign", run: okRun }; + assert.deepEqual(await verifyProvenance(full, deps), { ok: true }); + }); + + it("refuses (fail-closed) when a required field is missing", async () => { + const deps: ProvenanceDeps = { resolveBin: async () => "/usr/bin/cosign", run: okRun }; + const r = await verifyProvenance({ ...full, certIdentity: "" }, deps); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /certIdentity/); + }); + + it("refuses when cosign is not installed", async () => { + const deps: ProvenanceDeps = { resolveBin: async () => null, run: okRun }; + const r = await verifyProvenance(full, deps); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /cosign not found/); + }); + + it("refuses when cosign rejects the bundle (non-zero)", async () => { + const deps: ProvenanceDeps = { + resolveBin: async () => "/usr/bin/cosign", + run: async () => ({ ok: false, stdout: "", stderr: "error: no matching signatures" }), + }; + const r = await verifyProvenance(full, deps); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /cosign rejected the bundle/); + }); +}); diff --git a/src/airgap/provenance.ts b/src/airgap/provenance.ts new file mode 100644 index 00000000..07d88233 --- /dev/null +++ b/src/airgap/provenance.ts @@ -0,0 +1,103 @@ +/** + * Offline SLSA/Sigstore provenance verification for an air-gapped enclave. + * + * kit does NOT reimplement Sigstore verification — it orchestrates **cosign**, + * the correct verifier, in fully OFFLINE mode: + * + * cosign verify-blob --offline \ + * --trusted-root \ + * --bundle \ + * --certificate-identity --certificate-oidc-issuer \ + * + * + * `--offline` skips the Rekor network lookup (uses the bundle's inclusion + * proof); `--trusted-root` supplies the Fulcio/Rekor/CT trust roots that the + * operator distributes into the enclave (no Fulcio/Rekor egress). Everything is + * FAIL-CLOSED: a missing cosign, missing trust root, missing identity + * constraints, or a non-zero exit all mean NOT VERIFIED — kit never reports + * "verified" unless cosign returned success. + */ + +export interface ProvenanceVerifyOptions { + /** Path to the artifact whose provenance is being checked. */ + artifact: string; + /** Path to the Sigstore bundle (.sigstore/.bundle) for the artifact. */ + bundle: string; + /** Path to a shipped-in Sigstore trusted_root.json (the offline trust anchor). */ + trustedRoot: string; + /** Required identity constraint — the SAN cosign must match (e.g. a repo URI). */ + certIdentity: string; + /** Required OIDC issuer constraint (e.g. https://token.actions.githubusercontent.com). */ + certIssuer: string; +} + +/** Fields that must all be present, or verification is refused (fail-closed). */ +const REQUIRED: (keyof ProvenanceVerifyOptions)[] = [ + "artifact", + "bundle", + "trustedRoot", + "certIdentity", + "certIssuer", +]; + +/** Returns the first missing/empty required field, or null when all present. */ +export function missingField(opts: Partial): string | null { + for (const k of REQUIRED) { + const v = opts[k]; + if (typeof v !== "string" || v.trim() === "") return k; + } + return null; +} + +/** Build the cosign argv for offline blob verification. Pure (assumes validated opts). */ +export function buildCosignArgs(opts: ProvenanceVerifyOptions): string[] { + return [ + "verify-blob", + "--offline", + "--trusted-root", + opts.trustedRoot, + "--bundle", + opts.bundle, + "--certificate-identity", + opts.certIdentity, + "--certificate-oidc-issuer", + opts.certIssuer, + opts.artifact, + ]; +} + +export interface ProvenanceDeps { + /** Resolve the cosign binary, or null if not installed. */ + resolveBin: (bin: string) => Promise; + /** Run a command without throwing; ok=true iff exit 0. */ + run: (bin: string, args: string[]) => Promise<{ ok: boolean; stdout: string; stderr: string }>; +} + +export type ProvenanceResult = { ok: true } | { ok: false; reason: string }; + +/** + * Verify provenance offline via cosign. Fail-closed: any missing input, + * missing cosign, or non-zero cosign exit → `{ ok: false }`. Only a clean + * cosign success returns `{ ok: true }`. + */ +export async function verifyProvenance( + opts: Partial, + deps: ProvenanceDeps, +): Promise { + const missing = missingField(opts); + if (missing) { + return { ok: false, reason: `missing ${missing} — cannot verify provenance (fail-closed)` }; + } + const cosign = await deps.resolveBin("cosign"); + if (!cosign) { + return { ok: false, reason: "cosign not found — cannot verify provenance (fail-closed)" }; + } + const args = buildCosignArgs(opts as ProvenanceVerifyOptions); + const res = await deps.run(cosign, args); + if (!res.ok) { + const detail = + (res.stderr || res.stdout || "").trim().split("\n").pop() ?? "verification failed"; + return { ok: false, reason: `cosign rejected the bundle: ${detail}` }; + } + return { ok: true }; +} diff --git a/src/airgap/threat-data.test.ts b/src/airgap/threat-data.test.ts new file mode 100644 index 00000000..26fb1d8a --- /dev/null +++ b/src/airgap/threat-data.test.ts @@ -0,0 +1,132 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { generateKeyPairSync, sign as cryptoSign } from "node:crypto"; +import { + parseManifest, + sha256Hex, + verifyThreatData, + type ThreatManifest, + type VerifyDeps, +} from "./threat-data.js"; + +function deps(dir: string, publicKeyPem: string): VerifyDeps { + return { + dir, + publicKeyPem, + readFile: (rel) => readFileSync(join(dir, rel)), + resolvePath: (rel) => resolve(dir, rel), + }; +} + +/** Build a signed bundle in a tmp dir; returns {dir, pub}. */ +function makeBundle(artifacts: { path: string; bytes: string; env?: string }[]) { + const dir = mkdtempSync(join(tmpdir(), "kit-td-")); + const { publicKey, privateKey } = generateKeyPairSync("ed25519"); + for (const a of artifacts) writeFileSync(join(dir, a.path), a.bytes); + const manifest: ThreatManifest = { + version: 1, + created: new Date().toISOString(), + artifacts: artifacts.map((a) => ({ + path: a.path, + sha256: sha256Hex(Buffer.from(a.bytes)), + env: a.env, + })), + }; + const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2)); + writeFileSync(join(dir, "manifest.json"), manifestBytes); + const sig = cryptoSign(null, manifestBytes, privateKey).toString("base64"); + writeFileSync(join(dir, "manifest.json.sig"), sig); + return { dir, pub: publicKey.export({ type: "spki", format: "pem" }) as string }; +} + +describe("parseManifest", () => { + it("rejects bad json, missing fields, bad sha, path escape", () => { + assert.throws(() => parseManifest("{nope"), /not valid JSON/); + assert.throws(() => parseManifest(JSON.stringify({ artifacts: [] })), /version/); + assert.throws( + () => parseManifest(JSON.stringify({ version: 1, artifacts: [{ path: "a", sha256: "xx" }] })), + /sha256/, + ); + assert.throws( + () => + parseManifest( + JSON.stringify({ + version: 1, + artifacts: [{ path: "../escape", sha256: "a".repeat(64) }], + }), + ), + /escapes the bundle/, + ); + }); +}); + +describe("verifyThreatData", () => { + it("verifies a correctly signed bundle and returns the env wiring", () => { + const { dir, pub } = makeBundle([ + { path: "grype.db", bytes: "fake-grype-db", env: "GRYPE_DB_CACHE_DIR" }, + { path: "osv.db", bytes: "fake-osv-db" }, + ]); + try { + const r = verifyThreatData(deps(dir, pub)); + assert.ok(r.ok); + assert.equal(r.ok && r.artifacts, 2); + assert.equal(r.ok && r.env.GRYPE_DB_CACHE_DIR, resolve(dir, "grype.db")); + assert.ok(r.ok && !("OSV" in r.env)); // no env declared for osv.db + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("FAILS CLOSED on a tampered artifact", () => { + const { dir, pub } = makeBundle([{ path: "grype.db", bytes: "fake-grype-db" }]); + try { + writeFileSync(join(dir, "grype.db"), "tampered!"); // change bytes after signing + const r = verifyThreatData(deps(dir, pub)); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /tampered|mismatch/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("FAILS CLOSED on a bad signature / wrong key", () => { + const { dir } = makeBundle([{ path: "a.db", bytes: "x" }]); + const other = generateKeyPairSync("ed25519").publicKey.export({ + type: "spki", + format: "pem", + }) as string; + try { + const r = verifyThreatData(deps(dir, other)); // verify with the WRONG key + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /signature/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("FAILS CLOSED on a missing artifact", () => { + const { dir, pub } = makeBundle([{ path: "a.db", bytes: "x" }]); + try { + rmSync(join(dir, "a.db")); + const r = verifyThreatData(deps(dir, pub)); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /missing/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("FAILS CLOSED when the manifest or signature file is absent", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-td-empty-")); + try { + const r = verifyThreatData(deps(dir, "not-a-key")); + assert.equal(r.ok, false); + assert.match(r.ok === false ? r.reason : "", /manifest\.json not found/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/airgap/threat-data.ts b/src/airgap/threat-data.ts new file mode 100644 index 00000000..eaebbb9c --- /dev/null +++ b/src/airgap/threat-data.ts @@ -0,0 +1,153 @@ +/** + * Verified offline threat-data bundle. + * + * In a no-egress enclave the scanners' vulnerability DBs (and the bumblebee + * catalog) must be synced in from a connected host. The risk: stale or + * *tampered* threat data silently degrades every downstream verdict. This module + * gives that transfer a trust chain that is FULLY OFFLINE-VERIFIABLE (no Fulcio / + * Rekor / network): + * + * 1. The bundle ships a `manifest.json` listing each artifact + its SHA-256, + * plus a detached `manifest.json.sig` — an Ed25519 signature over the + * manifest bytes, produced on the connected host with a key the enclave + * trusts out-of-band (configured via KIT_THREAT_DATA_PUBKEY). + * 2. kit verifies the signature over the manifest, then SHA-256s every listed + * artifact against the manifest. Any failure → fail-closed (the whole + * bundle is rejected; `kit scan --airgap` refuses rather than scan against + * unverified data). + * 3. Each artifact may declare an `env` var; on success kit points the scanner + * at the verified file (e.g. `GRYPE_DB_CACHE_DIR`). The bundle author + * declares the wiring, so kit hard-codes no scanner-version specifics. + * + * Pure/deterministic and dependency-injected (fs + hash) so it is fully tested + * without real DBs. node:crypto only. + */ +import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto"; + +export interface ThreatArtifact { + /** Path of the artifact relative to the bundle dir. */ + path: string; + /** Lowercase hex SHA-256 of the artifact's bytes. */ + sha256: string; + /** Optional: env var to set to the artifact's absolute path so a scanner finds it. */ + env?: string; +} + +export interface ThreatManifest { + /** Bundle schema version. */ + version: number; + /** ISO-8601 build time (informational). */ + created?: string; + artifacts: ThreatArtifact[]; +} + +/** Parse + shape-validate a manifest. Throws on anything malformed (fail-closed). */ +export function parseManifest(json: string): ThreatManifest { + let obj: unknown; + try { + obj = JSON.parse(json); + } catch { + throw new Error("threat-data manifest is not valid JSON"); + } + const m = obj as Partial; + if (typeof m.version !== "number") throw new Error("manifest: missing numeric `version`"); + if (!Array.isArray(m.artifacts)) throw new Error("manifest: `artifacts` must be an array"); + for (const [i, a] of m.artifacts.entries()) { + if (!a || typeof a.path !== "string" || !a.path) { + throw new Error(`manifest: artifact[${i}] missing \`path\``); + } + if (typeof a.sha256 !== "string" || !/^[0-9a-f]{64}$/i.test(a.sha256)) { + throw new Error(`manifest: artifact[${i}] (${a.path}) has no valid sha256`); + } + if (a.env !== undefined && (typeof a.env !== "string" || !/^[A-Z_][A-Z0-9_]*$/.test(a.env))) { + throw new Error(`manifest: artifact[${i}] (${a.path}) has an invalid env var name`); + } + if (a.path.includes("..") || a.path.startsWith("/")) { + // never let a manifest point outside the bundle dir + throw new Error(`manifest: artifact[${i}] path escapes the bundle: ${a.path}`); + } + } + return m as ThreatManifest; +} + +export function sha256Hex(bytes: Buffer): string { + return createHash("sha256").update(bytes).digest("hex"); +} + +/** Verify a detached Ed25519 signature over the manifest bytes. Never throws. */ +export function verifyManifestSignature( + manifestBytes: Buffer, + signature: Buffer, + publicKeyPem: string, +): boolean { + try { + const key = createPublicKey(publicKeyPem); + // Ed25519: algorithm is null; key type is enforced by the key object. + return cryptoVerify(null, manifestBytes, key, signature); + } catch { + return false; + } +} + +export type VerifyResult = + | { ok: true; env: Record; artifacts: number } + | { ok: false; reason: string }; + +export interface VerifyDeps { + /** Absolute bundle directory. */ + dir: string; + /** Trusted Ed25519 public key (PEM/SPKI), out-of-band. */ + publicKeyPem: string; + /** Read a file under the bundle as bytes; reject (throw) if missing. */ + readFile: (relPath: string) => Buffer; + /** Resolve a bundle-relative path to the absolute path used for env wiring. */ + resolvePath: (relPath: string) => string; +} + +/** + * Verify a threat-data bundle end to end: signature over the manifest, then + * SHA-256 of every artifact. Returns the env map to wire scanners on success; + * a single problem fails the whole bundle (fail-closed). + */ +export function verifyThreatData(deps: VerifyDeps): VerifyResult { + let manifestBytes: Buffer; + let sigB64: Buffer; + try { + manifestBytes = deps.readFile("manifest.json"); + } catch { + return { ok: false, reason: "manifest.json not found in bundle" }; + } + try { + sigB64 = deps.readFile("manifest.json.sig"); + } catch { + return { ok: false, reason: "manifest.json.sig (detached signature) not found in bundle" }; + } + + const signature = Buffer.from(sigB64.toString("utf8").trim(), "base64"); + if (!verifyManifestSignature(manifestBytes, signature, deps.publicKeyPem)) { + return { ok: false, reason: "manifest signature does not verify against the trusted key" }; + } + + let manifest: ThreatManifest; + try { + manifest = parseManifest(manifestBytes.toString("utf8")); + } catch (e) { + return { ok: false, reason: (e as Error).message }; + } + + const env: Record = {}; + for (const a of manifest.artifacts) { + let bytes: Buffer; + try { + bytes = deps.readFile(a.path); + } catch { + return { ok: false, reason: `artifact missing: ${a.path}` }; + } + const actual = sha256Hex(bytes); + if (actual.toLowerCase() !== a.sha256.toLowerCase()) { + return { ok: false, reason: `artifact tampered (sha256 mismatch): ${a.path}` }; + } + if (a.env) env[a.env] = deps.resolvePath(a.path); + } + return { ok: true, env, artifacts: manifest.artifacts.length }; +} diff --git a/src/cli.ts b/src/cli.ts index 4384cec8..4919745c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4486,23 +4486,109 @@ async function cmdSentinelStatus(): Promise { return true; } +async function cmdVerifyProvenance(): Promise { + const args = process.argv.slice(3); + // First positional that isn't a value-flag's argument = the artifact. + const VALUE_FLAGS = new Set(["--bundle", "--trusted-root", "--identity", "--issuer"]); + let artifact: string | undefined; + for (let i = 0; i < args.length; i++) { + if (VALUE_FLAGS.has(args[i])) { + i++; + continue; + } + if (!args[i].startsWith("-")) { + artifact = args[i]; + break; + } + } + if (!artifact) { + console.error( + "usage: kit verify-provenance --bundle [--trusted-root ] [--identity ] [--issuer ]", + ); + return false; + } + const { resolveAirGap } = await import("./airgap/config.js"); + const { verifyProvenance } = await import("./airgap/provenance.js"); + const { resolveToolBin } = await import("./utils/resolveTool.js"); + const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); + const config = await loadConfig(resolveConfigPath()); + const ag = resolveAirGap(config.air_gap, process.env); + const res = await verifyProvenance( + { + artifact, + bundle: flagValue(args, "--bundle"), + trustedRoot: flagValue(args, "--trusted-root") ?? ag.provenanceTrustedRoot, + certIdentity: flagValue(args, "--identity") ?? ag.provenanceCertIdentity, + certIssuer: flagValue(args, "--issuer") ?? ag.provenanceCertIssuer, + }, + { + resolveBin: (b) => resolveToolBin(b), + run: async (b, a) => { + const r = await execFileNoThrow(b, a, { timeout: 60_000 }); + return { ok: r.ok, stdout: r.stdout, stderr: r.stderr }; + }, + }, + ); + if (res.ok) { + console.log(`${c.green}✓ provenance verified${c.reset} ${c.dim}${artifact}${c.reset}`); + return true; + } + console.error(`${c.red}✗ ${res.reason}${c.reset}`); + return false; +} + async function cmdScan(): Promise { const jsonMode = hasFlag(process.argv, "--json"); const { runScanners, suppressBaselined, dedupKey } = await import("./scanners.js"); 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, airGapScanners, isAirGap } = await import("./scanners.js"); + const { SCANNERS, airGapScanners } = 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()) { + const config = await loadConfig(resolveConfigPath()); + + // Air-gap posture from `.kit.toml [air_gap]` + env (env overrides). When + // enabled, drop cloud-only scanners and run the rest against local DBs with no + // network. See docs/AIR_GAP.md. + const { resolveAirGap } = await import("./airgap/config.js"); + const ag = resolveAirGap(config.air_gap, process.env); + const airgap = airGapScanners(SCANNERS, ag.enabled); + if (ag.enabled) { console.log( `${c.dim}air-gap mode: offline scanners only${airgap.dropped.length ? ` (skipping cloud-only: ${airgap.dropped.join(", ")})` : ""}${c.reset}`, ); + // Verified offline threat-data bundle (optional): point scanners at a + // signed, integrity-checked local DB set. Fail-closed — never scan against + // unverified threat data. + if (ag.threatDataDir) { + const tdDir = ag.threatDataDir; + const { verifyThreatData } = await import("./airgap/threat-data.js"); + const pubRef = ag.threatDataPubkey ?? ""; + const pubPem = pubRef && existsSync(pubRef) ? readFileSync(pubRef, "utf8") : pubRef; + if (!pubPem) { + console.error( + `${c.red}✗ air-gap threat-data dir set but no public key (threat_data_pubkey / KIT_THREAT_DATA_PUBKEY) — cannot verify (fail-closed)${c.reset}`, + ); + return false; + } + const res = verifyThreatData({ + dir: tdDir, + publicKeyPem: pubPem, + readFile: (rel) => readFileSync(resolve(tdDir, rel)), + resolvePath: (rel) => resolve(tdDir, rel), + }); + if (!res.ok) { + console.error( + `${c.red}✗ threat-data bundle rejected: ${res.reason} (fail-closed)${c.reset}`, + ); + return false; + } + Object.assign(airgap.env, res.env); + console.log( + `${c.dim}verified threat-data bundle: ${res.artifacts} artifact(s) signed + checksummed${c.reset}`, + ); + } } - const config = await loadConfig(resolveConfigPath()); // Resolve scanner tokens (SNYK_TOKEN, …) from a configured tooling Infisical // project so `kit scan` works without an `infisical run` wrapper (#65). The @@ -5429,6 +5515,7 @@ async function main(): Promise { "agent-audit": cmdAgentAudit, sentinel: cmdSentinel, scan: cmdScan, + "verify-provenance": cmdVerifyProvenance, "gha-audit": cmdGhaAudit, sbom: cmdSbom, init: cmdInit, diff --git a/src/config.ts b/src/config.ts index 0b175795..52b5cf29 100644 --- a/src/config.ts +++ b/src/config.ts @@ -300,6 +300,24 @@ export interface kitConfig { supply_chain?: { internal_scopes?: string[] }; /** `kit scan` settings — a tooling Infisical project to resolve scanner tokens (SNYK_TOKEN, …) from. */ scan?: { tooling?: { project_id?: string; env?: string } }; + /** + * No-egress / air-gapped posture (declarative; see docs/AIR_GAP.md). Equivalent + * to the `KIT_*` env vars, but checked in so the enclave config is reproducible. + * Env vars, when set, override these. `enabled` turns on offline scan mode. + */ + air_gap?: { + enabled?: boolean; + npm_registry?: string; + pypi_index?: string; + github_api?: string; + docker_registry?: string; + threat_data_dir?: string; + threat_data_pubkey?: string; + /** Offline provenance (`kit verify-provenance`): shipped-in Sigstore trust + identity constraints. */ + provenance_trusted_root?: string; + provenance_cert_identity?: string; + provenance_cert_issuer?: string; + }; web?: { search?: WebSearchConfig; }; @@ -566,6 +584,21 @@ const kitConfigSchema = z }) .passthrough() .optional(), + air_gap: z + .object({ + enabled: z.boolean().optional(), + npm_registry: z.string().optional(), + pypi_index: z.string().optional(), + github_api: z.string().optional(), + docker_registry: z.string().optional(), + threat_data_dir: z.string().optional(), + threat_data_pubkey: z.string().optional(), + provenance_trusted_root: z.string().optional(), + provenance_cert_identity: z.string().optional(), + provenance_cert_issuer: z.string().optional(), + }) + .passthrough() + .optional(), web: WebConfigSchema, setup: z .object({ diff --git a/src/scanners.test.ts b/src/scanners.test.ts index 6a840962..2d72d54e 100644 --- a/src/scanners.test.ts +++ b/src/scanners.test.ts @@ -152,6 +152,45 @@ describe("airGapScanners", () => { }); }); +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/triage.ts b/src/triage.ts index dbcc2e9d..268b3c80 100644 --- a/src/triage.ts +++ b/src/triage.ts @@ -84,6 +84,23 @@ export function verdictPassed(output: string): boolean { return lines.includes("TRIAGE PASSED"); } +/** + * Mirror env vars (KIT_NPM_REGISTRY, …) derived from `.kit.toml [air_gap]`, so a + * config-declared internal mirror is honored by the triage subprocess even when + * the operator didn't export the env var. Best-effort: never breaks triage if + * the config can't be read. Env vars already in `process.env` still win. + */ +async function airGapMirrorEnv(): Promise> { + try { + const { loadConfig } = await import("./config.js"); + const { resolveAirGap, airGapTriageEnv } = await import("./airgap/config.js"); + const cfg = await loadConfig(resolve(process.cwd(), ".kit.toml")); + return airGapTriageEnv(resolveAirGap(cfg.air_gap, process.env)); + } catch { + return {}; + } +} + /** * Run triage on a target */ @@ -99,11 +116,11 @@ export async function runTriage(type: TriageType, target: string): Promise