Skip to content
Merged
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
84 changes: 84 additions & 0 deletions docs/AIR_GAP.md
Original file line number Diff line number Diff line change
@@ -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/<name>/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/<repo>` 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.
27 changes: 18 additions & 9 deletions skills/triage/scripts/triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,27 @@
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)
if headers:
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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)")
Expand Down Expand Up @@ -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")
Expand Down
35 changes: 23 additions & 12 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4492,8 +4492,16 @@ async function cmdScan(): Promise<boolean> {
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
Expand All @@ -4514,18 +4522,21 @@ async function cmdScan(): Promise<boolean> {
}
}

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.
Expand Down
42 changes: 42 additions & 0 deletions src/scanners.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import {
mergeFindings,
suppressBaselined,
runScanners,
airGapScanners,
isAirGap,
SCANNERS,
type ScanDeps,
type ScannerDef,
} from "./scanners.js";
Expand Down Expand Up @@ -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([
{
Expand Down
79 changes: 75 additions & 4 deletions src/scanners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> };
}

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<string, string>;
/** 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<string, string> = {};
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<string, number> = { critical: 4, high: 3, medium: 2, low: 1 };

/** Cross-scanner dedup key: a CVE/GHSA id if present in the finding, else its name. */
Expand Down
Loading