476 lines
18 KiB
TypeScript
476 lines
18 KiB
TypeScript
import { GrypeUpdater } from "./grype-updater";
|
|
import { execFile, spawn } from "node:child_process";
|
|
import { randomUUID } from "node:crypto";
|
|
import { createWriteStream, promises as fs } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { Transform } from "node:stream";
|
|
import { pipeline } from "node:stream/promises";
|
|
import { promisify } from "node:util";
|
|
import type { DockgeServer } from "./dockge-server";
|
|
import { log } from "./log";
|
|
import type { Stack } from "./stack";
|
|
import { ValidationError } from "./util-server";
|
|
|
|
const exec = promisify(execFile);
|
|
const severities = [ "critical", "high", "medium", "low", "negligible", "unknown" ] as const;
|
|
type Severity = typeof severities[number];
|
|
|
|
const maxImageBytes = 1024 * 1024 * 1024;
|
|
const maxImages = 20;
|
|
const maxReports = 8;
|
|
const maxFindings = 500;
|
|
const pageSize = 25;
|
|
const databaseTimeout = 15 * 60 * 1000;
|
|
const imageIdPattern = /^sha256:[a-f0-9]{64}$/;
|
|
const inspectFields = [
|
|
"\"id\":{{json .Image}}",
|
|
"\"reference\":{{json .Config.Image}}",
|
|
"\"service\":{{json (index .Config.Labels \"com.docker.compose.service\")}}",
|
|
"\"directory\":{{json (index .Config.Labels \"com.docker.compose.project.working_dir\")}}",
|
|
"\"oneOff\":{{json (index .Config.Labels \"com.docker.compose.oneoff\")}}",
|
|
];
|
|
const inspectFormat = `{${inspectFields.join(",")}}`;
|
|
|
|
interface Finding {
|
|
id: string;
|
|
namespace: string;
|
|
severity: Severity;
|
|
packageName: string;
|
|
packageType: string;
|
|
installedVersion: string;
|
|
fixedVersions: string[];
|
|
}
|
|
|
|
interface ImageScan {
|
|
id: string;
|
|
references: string[];
|
|
services: string[];
|
|
status: "pending" | "scanned" | "failed";
|
|
counts?: Record<Severity, number>;
|
|
error?: string;
|
|
truncated?: boolean;
|
|
scannerVersion?: string;
|
|
databaseBuiltAt?: string;
|
|
findings: Finding[];
|
|
}
|
|
|
|
interface ScanReport {
|
|
id: string;
|
|
stackName: string;
|
|
status: "running" | "complete" | "failed";
|
|
startedAt: string;
|
|
finishedAt?: string;
|
|
error?: string;
|
|
preparingDatabase?: boolean;
|
|
images: ImageScan[];
|
|
}
|
|
|
|
interface GrypeMatch {
|
|
vulnerability?: {
|
|
id?: string;
|
|
namespace?: string;
|
|
severity?: string;
|
|
fix?: { versions?: string[] };
|
|
};
|
|
artifact?: { name?: string; type?: string; version?: string };
|
|
}
|
|
|
|
interface ContainerImage {
|
|
id: string;
|
|
reference: string;
|
|
service: string;
|
|
directory: string;
|
|
oneOff: string;
|
|
}
|
|
|
|
/** Limit strings forwarded from third-party reports to the browser. */
|
|
function label(value: unknown, length = 160): string {
|
|
if (typeof value !== "string") {
|
|
return "";
|
|
}
|
|
return value.length > length ? value.slice(0, length - 1) + "…" : value;
|
|
}
|
|
|
|
/** Normalize scanner output while keeping the original severity and package identity. */
|
|
function normalizeFindings(output: string) {
|
|
const report = JSON.parse(output) as {
|
|
matches?: GrypeMatch[];
|
|
descriptor?: {
|
|
version?: string;
|
|
db?: { status?: { built?: string; valid?: boolean } };
|
|
};
|
|
};
|
|
if (!Array.isArray(report?.matches)) {
|
|
throw new ValidationError("imageScanInvalidReport");
|
|
}
|
|
if (report.descriptor?.db?.status?.valid === false) {
|
|
throw new ValidationError("imageScanInvalidReport");
|
|
}
|
|
|
|
const counts: Record<Severity, number> = {
|
|
critical: 0,
|
|
high: 0,
|
|
medium: 0,
|
|
low: 0,
|
|
negligible: 0,
|
|
unknown: 0,
|
|
};
|
|
const unique = new Map<string, Finding>();
|
|
for (const match of report.matches) {
|
|
const id = label(match?.vulnerability?.id, 80);
|
|
const packageName = label(match?.artifact?.name);
|
|
if (!id || !packageName) {
|
|
continue;
|
|
}
|
|
|
|
const reportedSeverity = label(match.vulnerability?.severity).toLowerCase();
|
|
const severity = severities.find(value => value === reportedSeverity) ?? "unknown";
|
|
const versions = match.vulnerability?.fix?.versions;
|
|
const finding: Finding = {
|
|
id,
|
|
packageName,
|
|
namespace: label(match.vulnerability?.namespace),
|
|
severity,
|
|
packageType: label(match.artifact?.type, 40),
|
|
installedVersion: label(match.artifact?.version),
|
|
fixedVersions: Array.isArray(versions) ? versions.slice(0, 10).map(version => label(version)).filter(Boolean) : [],
|
|
};
|
|
const key = JSON.stringify([
|
|
match.vulnerability?.id,
|
|
match.vulnerability?.namespace,
|
|
match.artifact?.name,
|
|
match.artifact?.type,
|
|
match.artifact?.version,
|
|
]);
|
|
if (!unique.has(key)) {
|
|
unique.set(key, finding);
|
|
counts[severity]++;
|
|
}
|
|
}
|
|
const findings = Array.from(unique.values()).sort((a, b) => severities.indexOf(a.severity) - severities.indexOf(b.severity)
|
|
|| a.id.localeCompare(b.id) || a.packageName.localeCompare(b.packageName));
|
|
const databaseBuiltAt = report.descriptor?.db?.status?.built;
|
|
return {
|
|
counts,
|
|
truncated: findings.length > maxFindings,
|
|
findings: findings.slice(0, maxFindings),
|
|
scannerVersion: label(report.descriptor?.version, 40),
|
|
databaseBuiltAt: typeof databaseBuiltAt === "string" && Number.isFinite(Date.parse(databaseBuiltAt)) ? databaseBuiltAt : undefined,
|
|
};
|
|
}
|
|
|
|
export class ImageVulnerabilityScan {
|
|
private updater?: GrypeUpdater;
|
|
private readonly reports = new Map<string, ScanReport>();
|
|
private readonly shutdown = new AbortController();
|
|
private active?: ScanReport;
|
|
private activeRun?: Promise<void>;
|
|
|
|
constructor(private readonly server: DockgeServer) {}
|
|
|
|
/** Start one bounded scan per host without waiting for Docker or Grype to finish. */
|
|
start(stack: Stack) {
|
|
if (this.active) {
|
|
if (this.active.stackName === stack.name && this.reports.has(stack.name)) {
|
|
return this.summary(stack.name);
|
|
}
|
|
throw new ValidationError("imageScanHostBusy");
|
|
}
|
|
const report: ScanReport = {
|
|
id: randomUUID(),
|
|
stackName: stack.name,
|
|
status: "running",
|
|
startedAt: new Date().toISOString(),
|
|
images: [],
|
|
};
|
|
this.reports.delete(stack.name);
|
|
this.reports.set(stack.name, report);
|
|
const oldest = this.reports.keys().next().value;
|
|
if (this.reports.size > maxReports && oldest !== undefined) {
|
|
this.reports.delete(oldest);
|
|
}
|
|
this.active = report;
|
|
this.activeRun = this.run(stack, report);
|
|
return this.summary(stack.name);
|
|
}
|
|
|
|
/** Return progress and counts without sending package details over the socket. */
|
|
summary(stackName: string) {
|
|
const report = this.reports.get(stackName);
|
|
if (!report) {
|
|
return null;
|
|
}
|
|
return {
|
|
...report,
|
|
images: report.images.map(({ findings, ...image }) => image),
|
|
};
|
|
}
|
|
|
|
/** Page through retained findings for the requested immutable image and report. */
|
|
page(stackName: string, reportId: unknown, imageId: unknown, severity: unknown, offset: unknown) {
|
|
if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 || offset > maxFindings
|
|
|| (severity !== "" && !severities.some(value => value === severity))) {
|
|
throw new ValidationError("imageScanInvalidRequest");
|
|
}
|
|
const report = this.reports.get(stackName);
|
|
if (!report || report.id !== reportId) {
|
|
throw new ValidationError("imageScanReportChanged");
|
|
}
|
|
const image = report.images.find(item => item.id === imageId && item.status === "scanned");
|
|
if (!image) {
|
|
throw new ValidationError("imageScanReportChanged");
|
|
}
|
|
const findings = severity ? image.findings.filter(item => item.severity === severity) : image.findings;
|
|
return {
|
|
rows: findings.slice(offset, offset + pageSize),
|
|
total: findings.length,
|
|
pageSize,
|
|
};
|
|
}
|
|
|
|
/** Forget reports for a deleted stack, including one still being scanned. */
|
|
forget(stackName: string) {
|
|
this.reports.delete(stackName);
|
|
}
|
|
|
|
private get scanner() {
|
|
this.updater ??= new GrypeUpdater(path.resolve(this.server.config.dataDir, "grype-bin"));
|
|
return this.updater;
|
|
}
|
|
|
|
startScannerUpdates() {
|
|
this.scanner.start();
|
|
}
|
|
|
|
/** Abort outstanding commands as Dockge shuts down. */
|
|
async stop() {
|
|
this.shutdown.abort();
|
|
await this.updater?.stop();
|
|
await this.activeRun;
|
|
}
|
|
|
|
/** Scan each immutable image once and keep the successful partial results. */
|
|
private async run(stack: Stack, report: ScanReport) {
|
|
try {
|
|
report.images = await this.discoverImages(stack);
|
|
if (report.images.length) {
|
|
report.preparingDatabase = true;
|
|
try {
|
|
await this.prepareDatabase();
|
|
} finally {
|
|
report.preparingDatabase = false;
|
|
}
|
|
}
|
|
|
|
for (const image of report.images) {
|
|
if (this.shutdown.signal.aborted) {
|
|
break;
|
|
}
|
|
try {
|
|
Object.assign(image, await this.scanImage(stack, image.id));
|
|
image.status = "scanned";
|
|
} catch (error) {
|
|
image.status = "failed";
|
|
image.error = this.reportError(error, "imageScanImageFailed");
|
|
}
|
|
}
|
|
report.status = "complete";
|
|
} catch (error) {
|
|
report.status = "failed";
|
|
report.error = this.reportError(error, "imageScanFailed");
|
|
} finally {
|
|
report.finishedAt = new Date().toISOString();
|
|
this.active = undefined;
|
|
}
|
|
}
|
|
|
|
/** Discover the images actually attached to this stack's running or stopped containers. */
|
|
private async discoverImages(stack: Stack): Promise<ImageScan[]> {
|
|
const cwd = path.resolve(stack.path);
|
|
const output = await this.docker(stack, stack.getComposeOptions("ps", "--all", "--orphans=false", "--quiet"));
|
|
const ids = output ? output.split(/\r?\n/) : [];
|
|
if (!ids.length) {
|
|
return [];
|
|
}
|
|
if (ids.length > 500 || !ids.every(id => /^[a-f0-9]{12,64}$/.test(id))) {
|
|
throw new ValidationError("imageScanDiscoveryFailed");
|
|
}
|
|
const inspected = await this.docker(stack, [ "container", "inspect", "--format", inspectFormat, "--", ...ids ]);
|
|
const images = new Map<string, ImageScan>();
|
|
const containers = inspected.split(/\r?\n/).map(line => JSON.parse(line) as ContainerImage);
|
|
if (containers.length !== ids.length) {
|
|
throw new ValidationError("imageScanDiscoveryFailed");
|
|
}
|
|
for (const container of containers) {
|
|
if (container.oneOff?.toLowerCase() !== "false" || !container.directory || path.resolve(container.directory) !== cwd) {
|
|
continue;
|
|
}
|
|
if (!imageIdPattern.test(container.id)) {
|
|
throw new ValidationError("imageScanDiscoveryFailed");
|
|
}
|
|
let image = images.get(container.id);
|
|
if (!image) {
|
|
image = {
|
|
id: container.id,
|
|
references: [],
|
|
services: [],
|
|
status: "pending",
|
|
findings: [],
|
|
};
|
|
images.set(container.id, image);
|
|
}
|
|
const reference = label(container.reference);
|
|
const service = label(container.service);
|
|
if (reference && image.references.length < 20 && !image.references.includes(reference)) {
|
|
image.references.push(reference);
|
|
}
|
|
if (service && image.services.length < 20 && !image.services.includes(service)) {
|
|
image.services.push(service);
|
|
}
|
|
}
|
|
if (images.size > maxImages) {
|
|
throw new ValidationError("imageScanTooManyImages");
|
|
}
|
|
return Array.from(images.values());
|
|
}
|
|
|
|
/** Export only the immutable local image and remove the archive on every exit path. */
|
|
private async scanImage(stack: Stack, id: string) {
|
|
const size = Number(await this.docker(stack, [ "image", "inspect", "--format", "{{.Size}}", "--", id ]));
|
|
if (!Number.isSafeInteger(size) || size < 0 || size > maxImageBytes) {
|
|
throw new ValidationError("imageScanImageTooLarge");
|
|
}
|
|
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "dockge-image-scan-"));
|
|
try {
|
|
const archive = path.join(directory, "image.tar");
|
|
await this.saveImage(stack, id, archive);
|
|
const stdout = await this.runGrype([ `docker-archive:${archive}`, "-o", "json" ], directory, 5 * 60 * 1000);
|
|
try {
|
|
return normalizeFindings(stdout);
|
|
} catch {
|
|
throw new ValidationError("imageScanInvalidReport");
|
|
}
|
|
} finally {
|
|
await fs.rm(directory, {
|
|
recursive: true,
|
|
force: true,
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Stream Docker's export to disk with a hard archive limit and a timeout. */
|
|
private async saveImage(stack: Stack, id: string, archive: string) {
|
|
let bytes = 0;
|
|
const limit = new Transform({
|
|
transform(chunk, encoding, callback) {
|
|
bytes += chunk.length;
|
|
if (bytes > maxImageBytes) {
|
|
callback(new ValidationError("imageScanImageTooLarge"));
|
|
} else {
|
|
callback(null, chunk);
|
|
}
|
|
},
|
|
});
|
|
const child = spawn("docker", [ "image", "save", "--", id ], {
|
|
cwd: stack.path,
|
|
stdio: [ "ignore", "pipe", "ignore" ],
|
|
timeout: 120000,
|
|
signal: this.shutdown.signal,
|
|
windowsHide: true,
|
|
});
|
|
const exited = new Promise<void>((resolve, reject) => {
|
|
child.once("error", reject);
|
|
child.once("close", code => {
|
|
if (code === 0) {
|
|
resolve();
|
|
} else {
|
|
reject(new ValidationError("imageScanExportFailed"));
|
|
}
|
|
});
|
|
});
|
|
try {
|
|
await Promise.all([ pipeline(child.stdout, limit, createWriteStream(archive, { flags: "wx",
|
|
mode: 0o600 })), exited ]);
|
|
} finally {
|
|
if (child.exitCode === null && child.signalCode === null) {
|
|
child.kill();
|
|
}
|
|
await exited.catch(() => {});
|
|
}
|
|
}
|
|
|
|
/** Run Docker without exposing raw CLI errors to the browser. */
|
|
private async docker(stack: Stack, args: string[]): Promise<string> {
|
|
const { stdout } = await exec("docker", args, {
|
|
cwd: stack.path,
|
|
timeout: 30000,
|
|
maxBuffer: 2 * 1024 * 1024,
|
|
signal: this.shutdown.signal,
|
|
windowsHide: true,
|
|
});
|
|
return stdout.trim();
|
|
}
|
|
|
|
/** Update once per report and use a valid cached database if the update fails. */
|
|
private async prepareDatabase() {
|
|
const cwd = os.tmpdir();
|
|
try {
|
|
await this.runGrype([ "db", "update" ], cwd, databaseTimeout);
|
|
} catch (error) {
|
|
if (this.shutdown.signal.aborted || error instanceof ValidationError) {
|
|
throw error;
|
|
}
|
|
this.reportError(error, "imageScanDatabaseUnavailable");
|
|
try {
|
|
await this.runGrype([ "db", "status" ], cwd, 60 * 1000);
|
|
} catch {
|
|
throw new ValidationError("imageScanDatabaseUnavailable");
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Invoke Grype with the same cache for the database update and the image scans. */
|
|
private async runGrype(args: string[], cwd: string, timeout: number): Promise<string> {
|
|
try {
|
|
const { stdout } = await exec(await this.scanner.executable(), args, {
|
|
cwd,
|
|
timeout,
|
|
maxBuffer: 32 * 1024 * 1024,
|
|
signal: this.shutdown.signal,
|
|
windowsHide: true,
|
|
env: {
|
|
...process.env,
|
|
GRYPE_DB_CACHE_DIR: path.resolve(process.env.GRYPE_DB_CACHE_DIR || path.join(this.server.config.dataDir, "grype-db")),
|
|
GRYPE_CHECK_FOR_APP_UPDATE: "false",
|
|
GRYPE_DB_AUTO_UPDATE: "false",
|
|
GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT: process.env.GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT || "10m",
|
|
TMPDIR: cwd,
|
|
TMP: cwd,
|
|
TEMP: cwd,
|
|
},
|
|
});
|
|
return stdout;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
throw new ValidationError("imageScanScannerUnavailable");
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Keep CLI output and filesystem paths out of the UI and diagnostic logs. */
|
|
private reportError(error: unknown, fallback: string): string {
|
|
if (this.shutdown.signal.aborted) {
|
|
return fallback;
|
|
}
|
|
if (error instanceof ValidationError) {
|
|
return error.message;
|
|
}
|
|
const failure = error as (NodeJS.ErrnoException & { killed?: boolean }) | undefined;
|
|
const code = failure?.killed ? "timeout" : failure?.code ?? "unknown";
|
|
log.warn("image-scan", `${fallback} (${code})`);
|
|
return fallback;
|
|
}
|
|
}
|