Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/AIR_GAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,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
Expand Down
132 changes: 132 additions & 0 deletions src/airgap/threat-data.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
});
});
153 changes: 153 additions & 0 deletions src/airgap/threat-data.ts
Original file line number Diff line number Diff line change
@@ -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<ThreatManifest>;
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<string, string>; 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<string, string> = {};
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 };
}
31 changes: 31 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4501,6 +4501,37 @@ async function cmdScan(): Promise<boolean> {
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. See docs/AIR_GAP.md.
const tdDir = process.env.KIT_THREAT_DATA_DIR;
if (tdDir) {
const { verifyThreatData } = await import("./airgap/threat-data.js");
const pubRef = process.env.KIT_THREAT_DATA_PUBKEY ?? "";
const pubPem = existsSync(pubRef) ? readFileSync(pubRef, "utf8") : pubRef;
if (!pubPem) {
console.error(
`${c.red}✗ KIT_THREAT_DATA_DIR set but KIT_THREAT_DATA_PUBKEY missing — cannot verify the bundle (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());

Expand Down