@hardkeel/benthic 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/LICENSE +92 -0
  3. package/NOTICE +16 -0
  4. package/README.md +424 -2
  5. package/action.yml +54 -0
  6. package/dist/agility.js +80 -0
  7. package/dist/badge.js +62 -0
  8. package/dist/baseline.js +81 -0
  9. package/dist/cbom-diff.js +273 -0
  10. package/dist/cbom.js +418 -0
  11. package/dist/cli.js +834 -0
  12. package/dist/cloud-aws-services.js +375 -0
  13. package/dist/cloud-aws.js +354 -0
  14. package/dist/cloud-azure-services.js +73 -0
  15. package/dist/cloud-azure.js +144 -0
  16. package/dist/cloud-common.js +242 -0
  17. package/dist/cloud-gcp-services.js +90 -0
  18. package/dist/cloud-gcp.js +150 -0
  19. package/dist/comments.js +138 -0
  20. package/dist/community-rules.js +37 -0
  21. package/dist/community.js +30 -0
  22. package/dist/deps.js +406 -0
  23. package/dist/der.js +571 -0
  24. package/dist/evidence-cli.js +235 -0
  25. package/dist/evidence-live.js +109 -0
  26. package/dist/evidence.js +512 -0
  27. package/dist/ignore.js +90 -0
  28. package/dist/image.js +1224 -0
  29. package/dist/infra.js +635 -0
  30. package/dist/inventory.js +277 -0
  31. package/dist/map-activity.js +24 -0
  32. package/dist/map-areas.js +60 -0
  33. package/dist/map-cloud-keys.js +110 -0
  34. package/dist/map-cloud.js +34 -0
  35. package/dist/map-ct.js +107 -0
  36. package/dist/map-host.js +335 -0
  37. package/dist/map-network.js +520 -0
  38. package/dist/map-people.js +79 -0
  39. package/dist/map-rank.js +70 -0
  40. package/dist/map-report.js +304 -0
  41. package/dist/map-run.js +327 -0
  42. package/dist/map-sarif.js +61 -0
  43. package/dist/map-signin.js +247 -0
  44. package/dist/map-types.js +19 -0
  45. package/dist/map-web.js +666 -0
  46. package/dist/native.js +168 -0
  47. package/dist/policy.js +221 -0
  48. package/dist/pqc.js +46 -0
  49. package/dist/profile.js +65 -0
  50. package/dist/project.js +928 -0
  51. package/dist/prose.js +159 -0
  52. package/dist/protocols.js +207 -0
  53. package/dist/registry.js +326 -0
  54. package/dist/report.js +190 -0
  55. package/dist/rules.js +230 -0
  56. package/dist/sarif-common.js +30 -0
  57. package/dist/sarif.js +114 -0
  58. package/dist/scan.js +601 -0
  59. package/dist/score.js +124 -0
  60. package/dist/secrets.js +192 -0
  61. package/dist/share-config.js +129 -0
  62. package/dist/share-lists.js +19 -0
  63. package/dist/share.js +125 -0
  64. package/dist/sonar.js +83 -0
  65. package/dist/structure.js +218 -0
  66. package/dist/suites.js +402 -0
  67. package/dist/tls-check.js +122 -0
  68. package/dist/types.js +4 -0
  69. package/dist/walk.js +78 -0
  70. package/dist/yaml.js +173 -0
  71. package/package.json +73 -4
package/dist/image.js ADDED
@@ -0,0 +1,1224 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Container images, read from a file, a folder or a registry. Nothing in the image is run. What it reads:
4
+ //
5
+ // - docker save / podman save archives (.tar, or .tar.gz), OCI image layouts and OCI archives,
6
+ // unpacked root filesystems, and images pulled read-only from a registry (registry.ts). Layers
7
+ // are applied in order, with deletions (whiteouts). What a layer gave is cached by its digest.
8
+ // - the system's encryption packages and their versions (Debian, Ubuntu, distroless and Alpine
9
+ // package lists): OpenSSL, OpenSSH, GnuTLS, NSS, Java, Go and others.
10
+ // - Go programs' built-in module list and Go version, Node packages under node_modules and
11
+ // Python packages under site-packages, matched against the same library list as manifests.
12
+ // - SSH, OpenSSL and web server settings, the SSH host keys, certificates and keys outside the
13
+ // system's list of trusted authorities, the application's own code, and the image's build
14
+ // history and environment variables, through the same checks as a folder scan.
15
+ // - programs and shared libraries that carry their own copy of an encryption library, and Java
16
+ // keystores outside the system's trust store (native.ts).
17
+ import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { createHash } from "node:crypto";
21
+ import { homedir, platform as osPlatform } from "node:os";
22
+ import { createGunzip, gunzipSync, gzipSync } from "node:zlib";
23
+ import * as zlib from "node:zlib";
24
+ import { knownLibrary } from "./deps.js";
25
+ import { runHost } from "./map-host.js";
26
+ import { ActivityLog } from "./map-activity.js";
27
+ import { toFinding } from "./map-rank.js";
28
+ import { binaryFormat, embeddedLibraries, readKeystore } from "./native.js";
29
+ import { materialFindings, pemKeyTypes, pgpKeyTypes } from "./der.js";
30
+ const BLOCK = 512;
31
+ function cstr(b, start, len) {
32
+ const end = b.indexOf(0, start);
33
+ return b.toString("utf8", start, end < 0 || end > start + len ? start + len : end);
34
+ }
35
+ function octal(b, start, len) {
36
+ // Large sizes use base-256: the first byte has its high bit set.
37
+ if (b[start] & 0x80) {
38
+ let n = 0;
39
+ for (let i = start + 1; i < start + len; i++)
40
+ n = n * 256 + b[i];
41
+ return n;
42
+ }
43
+ const s = cstr(b, start, len).trim();
44
+ return s ? parseInt(s, 8) : 0;
45
+ }
46
+ function paxRecords(data) {
47
+ const out = {};
48
+ let i = 0;
49
+ while (i < data.length) {
50
+ const sp = data.indexOf(0x20, i);
51
+ if (sp < 0)
52
+ break;
53
+ const len = Number(data.toString("utf8", i, sp));
54
+ if (!len)
55
+ break;
56
+ const rec = data.toString("utf8", sp + 1, i + len - 1);
57
+ const eq = rec.indexOf("=");
58
+ if (eq > 0)
59
+ out[rec.slice(0, eq)] = rec.slice(eq + 1);
60
+ i += len;
61
+ }
62
+ return out;
63
+ }
64
+ /**
65
+ * Read a tar stream. `choose` sees each entry's header and says whether its bytes are wanted; `entry`
66
+ * gets the header and, for kept entries, the bytes. Long names (PAX and GNU) are handled.
67
+ * `offset` gives each entry's byte position in the stream, for archives read a second time.
68
+ */
69
+ export async function readTar(stream, choose, entry) {
70
+ let buf = Buffer.alloc(0);
71
+ let pos = 0; // bytes of the stream consumed before buf[0]
72
+ let current = null;
73
+ let longName = null;
74
+ let longLink = null;
75
+ let pax = {};
76
+ let special = null;
77
+ let done = false;
78
+ const consume = (n) => {
79
+ buf = buf.subarray(n);
80
+ pos += n;
81
+ };
82
+ for await (const chunk of stream) {
83
+ if (done)
84
+ continue;
85
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
86
+ for (;;) {
87
+ if (special) {
88
+ const take = Math.min(special.left, buf.length);
89
+ if (take)
90
+ special.parts.push(Buffer.from(buf.subarray(0, take)));
91
+ special.left -= take;
92
+ consume(take);
93
+ if (special.left > 0)
94
+ break;
95
+ if (buf.length < special.pad)
96
+ break;
97
+ consume(special.pad);
98
+ const data = Buffer.concat(special.parts);
99
+ if (special.kind === "x")
100
+ pax = paxRecords(data);
101
+ else if (special.kind === "L")
102
+ longName = cstr(data, 0, data.length);
103
+ else if (special.kind === "K")
104
+ longLink = cstr(data, 0, data.length);
105
+ special = null;
106
+ continue;
107
+ }
108
+ if (current) {
109
+ const take = Math.min(current.left, buf.length);
110
+ if (take && current.keep)
111
+ current.parts.push(Buffer.from(buf.subarray(0, take)));
112
+ current.left -= take;
113
+ consume(take);
114
+ if (current.left > 0)
115
+ break;
116
+ if (buf.length < current.pad)
117
+ break;
118
+ consume(current.pad);
119
+ entry(current.h, current.keep ? Buffer.concat(current.parts) : null, current.at);
120
+ current = null;
121
+ continue;
122
+ }
123
+ if (buf.length < BLOCK)
124
+ break;
125
+ const hdr = buf.subarray(0, BLOCK);
126
+ if (hdr.every((x) => x === 0)) {
127
+ done = true;
128
+ break;
129
+ }
130
+ const size = octal(hdr, 124, 12);
131
+ const type = String.fromCharCode(hdr[156] || 48);
132
+ const pad = (BLOCK - (size % BLOCK)) % BLOCK;
133
+ consume(BLOCK);
134
+ if (type === "x" || type === "L" || type === "K") {
135
+ special = { kind: type, left: size, pad, parts: [] };
136
+ continue;
137
+ }
138
+ if (type === "g") {
139
+ special = { kind: "g", left: size, pad, parts: [] };
140
+ continue;
141
+ }
142
+ const magic = hdr.toString("latin1", 257, 262);
143
+ const prefix = magic === "ustar" ? cstr(hdr, 345, 155) : "";
144
+ let name = longName ?? pax.path ?? (prefix ? `${prefix}/${cstr(hdr, 0, 100)}` : cstr(hdr, 0, 100));
145
+ const linkname = longLink ?? pax.linkpath ?? cstr(hdr, 157, 100);
146
+ const realSize = pax.size ? Number(pax.size) : size;
147
+ longName = longLink = null;
148
+ pax = {};
149
+ name = name.replace(/^\.\//, "").replace(/^\/+/, "");
150
+ const h = { name, type: type === "\0" ? "0" : type, size: realSize, mode: octal(hdr, 100, 8), linkname };
151
+ const keep = (h.type === "0" || h.type === "7") && choose(h) === "keep";
152
+ current = { h, keep, left: realSize, pad: (BLOCK - (realSize % BLOCK)) % BLOCK, parts: [], at: pos };
153
+ }
154
+ }
155
+ }
156
+ // ---------- the image's files ----------
157
+ /** The merged filesystem: only the files that matter here are kept, with links and deletions applied. */
158
+ export class ImageFS {
159
+ files = new Map();
160
+ links = new Map(); // symbolic links: path -> target as written
161
+ goBinaries = new Map();
162
+ /** Programs that carry their own copy of an encryption library. */
163
+ embedded = new Map();
164
+ modes = new Map();
165
+ maps() {
166
+ return [this.files, this.links, this.goBinaries, this.embedded, this.modes];
167
+ }
168
+ /** Remove everything below a folder (an opaque whiteout), keeping the folder itself. */
169
+ clear(dir) {
170
+ for (const m of this.maps())
171
+ for (const k of [...m.keys()])
172
+ if (k.startsWith(dir + "/"))
173
+ m.delete(k);
174
+ }
175
+ remove(path) {
176
+ const under = path + "/";
177
+ for (const m of this.maps()) {
178
+ for (const k of [...m.keys()])
179
+ if (k === path || k.startsWith(under))
180
+ m.delete(k);
181
+ }
182
+ }
183
+ /** Follow symbolic links (up to 8) to the stored file. */
184
+ resolve(path) {
185
+ let p = norm(path);
186
+ for (let i = 0; i < 8; i++) {
187
+ // A link anywhere along the path, like /etc/ssl -> /usr/lib/ssl.
188
+ const parts = p.split("/");
189
+ let changed = false;
190
+ for (let j = parts.length; j > 0; j--) {
191
+ const head = parts.slice(0, j).join("/");
192
+ const target = this.links.get(head);
193
+ if (target === undefined)
194
+ continue;
195
+ const base = target.startsWith("/") ? "" : parts.slice(0, j - 1).join("/");
196
+ p = norm([base, target, ...parts.slice(j)].filter(Boolean).join("/"));
197
+ changed = true;
198
+ break;
199
+ }
200
+ if (!changed)
201
+ return p;
202
+ }
203
+ return p;
204
+ }
205
+ read(path) {
206
+ const b = this.files.get(this.resolve(path));
207
+ return b ? b.toString("utf8") : null;
208
+ }
209
+ list(dir) {
210
+ const d = this.resolve(dir);
211
+ const prefix = d ? d + "/" : "";
212
+ const names = new Set();
213
+ for (const m of [this.files, this.links]) {
214
+ for (const k of m.keys())
215
+ if (k.startsWith(prefix))
216
+ names.add(k.slice(prefix.length).split("/")[0]);
217
+ }
218
+ return names.size ? [...names].sort() : null;
219
+ }
220
+ }
221
+ /** A path inside the image without a leading slash, with . and .. worked out. */
222
+ export function norm(p) {
223
+ const out = [];
224
+ for (const part of p.split("/")) {
225
+ if (!part || part === ".")
226
+ continue;
227
+ if (part === "..")
228
+ out.pop();
229
+ else
230
+ out.push(part);
231
+ }
232
+ return out.join("/");
233
+ }
234
+ // Trusted authority lists: counted, not reported one by one.
235
+ const CA_STORE = /^(etc\/ssl\/certs|usr\/share\/ca-certificates|etc\/pki\/ca-trust|etc\/pki\/tls\/certs|usr\/lib\/ssl\/certs|etc\/ca-certificates|usr\/local\/share\/ca-certificates|usr\/share\/pki|etc\/pki\/java|usr\/lib\/jvm\/[^/]+\/lib\/security)\//;
236
+ const CA_BUNDLES = ["etc/ssl/certs/ca-certificates.crt", "etc/pki/tls/certs/ca-bundle.crt", "etc/ssl/cert.pem"];
237
+ // Where the system and its packages live: not the application's own code. /usr/local/bin and
238
+ // /var/www are left in, since applications are often installed there.
239
+ const SYSTEM = /^(usr\/(lib|lib32|lib64|libx32|libexec|share|include|bin|sbin|games)|usr\/local\/(lib|lib64|share|include|libexec)|lib|lib32|lib64|libx32|bin|sbin|boot|dev|proc|sys|run|tmp|snap|var\/(lib|cache|log|spool|tmp|mail|backups))(\/|$)/;
240
+ // Keys the package manager uses to check downloads: the distribution's own, like the CA list.
241
+ const VENDOR_KEYS = /^(etc\/(apk\/keys|apt\/trusted\.gpg\.d|apt\/keyrings|pki\/rpm-gpg)|usr\/share\/(apk\/keys|keyrings))\//;
242
+ const KEY_FILE = /\.(pem|crt|cer|key|pub|p8|jwk|jwks)$/i;
243
+ /** Java keystores: kept whole and read for their entries (system trust stores are skipped above). */
244
+ const KEYSTORE = /\.(jks|keystore|jceks|p12|pfx)$|(^|\/)(keystore|truststore)$/i;
245
+ const NATIVE_LIB = /\.(so(\.\d+)*|dylib|dll|node)$/;
246
+ const PACKAGE_DIRS = /(^|\/)(node_modules|site-packages|dist-packages|vendor|\.git|__pycache__|\.cache|\.npm|\.cargo\/registry|go\/pkg\/mod)\//;
247
+ const CODE_EXT = /\.(js|mjs|cjs|jsx|ts|mts|cts|tsx|py|rb|go|java|kt|kts|scala|cs|c|cc|cpp|cxx|h|hpp|rs|php|swift|sol|sh|bash|ya?ml|json|toml|ini|conf|cfg|cnf|env|properties|xml|tf|pem|crt|cer|key|pub)$|(^|\/)(dockerfile|\.env[^/]*|nginx\.conf|caddyfile)$/i;
248
+ const MAX_TEXT = 2 * 1024 * 1024;
249
+ const MAX_PROBE = 300 * 1024 * 1024;
250
+ /** The settings files read in full wherever they sit. */
251
+ const SETTINGS = /^(etc\/(ssh\/(sshd_config|ssh_config)(\.d\/[^/]+)?|ssh\/ssh_host_[a-z0-9_]+_key(\.pub)?|ssl\/openssl\.cnf|pki\/tls\/openssl\.cnf|crypto-policies\/config|os-release|nginx\/.+|apache2\/.+|httpd\/.+|haproxy\/.+|letsencrypt\/live\/.+)|usr\/lib\/ssl\/openssl\.cnf|usr\/lib\/os-release|root\/\.ssh\/[^/]+)$/;
252
+ const PACKAGE_DB = /^(var\/lib\/dpkg\/status|var\/lib\/dpkg\/status\.d\/[^/]+|lib\/apk\/db\/installed)$/;
253
+ const NODE_PKG = /(^|\/)node_modules\/(@[^/]+\/)?[^/]+\/package\.json$/;
254
+ const PY_META = /(^|\/)(site|dist)-packages\/[^/]+\.(dist-info\/METADATA|egg-info\/PKG-INFO)$/;
255
+ /** Whether the image scan wants a file's bytes. */
256
+ export function wanted(h) {
257
+ const p = h.name;
258
+ if (SETTINGS.test(p) || PACKAGE_DB.test(p) || CA_BUNDLES.includes(p))
259
+ return h.size <= MAX_TEXT ? "keep" : "skip";
260
+ if (NODE_PKG.test(p) || PY_META.test(p))
261
+ return h.size <= 512 * 1024 ? "keep" : "skip";
262
+ if (VENDOR_KEYS.test(p))
263
+ return h.size <= 512 * 1024 ? "keep" : "skip"; // counted, like the CA list
264
+ if (CA_STORE.test(p))
265
+ return "skip";
266
+ if (KEYSTORE.test(p) && !PACKAGE_DIRS.test(p))
267
+ return h.size <= MAX_TEXT ? "keep" : "skip";
268
+ // Programs: looked at once for a Go module list and built-in encryption libraries, then dropped.
269
+ if ((h.mode & 0o111) !== 0 && h.size >= 512 * 1024 && h.size <= MAX_PROBE && !/\.(so(\.\d+)*|a|o|py|js|sh)$/.test(p) && !/^(usr\/lib|lib|lib64|usr\/libexec|usr\/share)\//.test(p))
270
+ return "probe";
271
+ // Shared libraries the application brought along; the system's own come from its package list.
272
+ // /usr/local and /opt are where hand-built copies (OpenSSL from source, say) usually go.
273
+ if (NATIVE_LIB.test(p) && h.size >= 256 * 1024 && h.size <= MAX_PROBE && !/^(usr\/(lib|lib32|lib64|libx32|libexec|share)|lib|lib32|lib64|libx32)\//.test(p) && !PACKAGE_DIRS.test(p))
274
+ return "probe";
275
+ if (SYSTEM.test(p) || PACKAGE_DIRS.test(p))
276
+ return "skip";
277
+ // Elsewhere in /etc, only the settings above and keys or certificates someone put there.
278
+ if (p.startsWith("etc/"))
279
+ return KEY_FILE.test(p) && h.size <= MAX_TEXT ? "keep" : "skip";
280
+ if (CODE_EXT.test(p) && h.size <= MAX_TEXT)
281
+ return "keep";
282
+ return "skip";
283
+ }
284
+ const GO_MAGIC = Buffer.from("\xff Go buildinf:", "latin1");
285
+ function uvarint(b, at) {
286
+ let x = 0;
287
+ let s = 0;
288
+ for (let i = 0; i < 10 && at + i < b.length; i++) {
289
+ const c = b[at + i];
290
+ if (c < 0x80)
291
+ return [x + c * 2 ** s, i + 1];
292
+ x += (c & 0x7f) * 2 ** s;
293
+ s += 7;
294
+ }
295
+ return [0, 0];
296
+ }
297
+ /** The Go version and modules built into a Go program (Go 1.18 and later store them inline). */
298
+ export function goBuildInfo(b) {
299
+ const at = b.indexOf(GO_MAGIC);
300
+ if (at < 0 || at + 32 > b.length)
301
+ return null;
302
+ const flags = b[at + 15];
303
+ if ((flags & 2) === 0)
304
+ return null; // older layout with pointers; not read
305
+ let off = at + 32;
306
+ const [vlen, n1] = uvarint(b, off);
307
+ if (!n1 || vlen > 64)
308
+ return null;
309
+ off += n1;
310
+ const goVersion = b.toString("utf8", off, off + vlen);
311
+ off += vlen;
312
+ const [mlen, n2] = uvarint(b, off);
313
+ if (!n2 || mlen > 4 * 1024 * 1024)
314
+ return null;
315
+ off += n2;
316
+ // The module text has 16 bytes of marker at each end.
317
+ const mod = mlen > 32 ? b.toString("utf8", off + 16, off + mlen - 16) : "";
318
+ if (!/^go\d/.test(goVersion))
319
+ return null;
320
+ const out = { goVersion, deps: [] };
321
+ let last;
322
+ for (const line of mod.split("\n")) {
323
+ const f = line.split("\t");
324
+ if (f[0] === "path")
325
+ out.path = f[1];
326
+ else if (f[0] === "dep" && f[1] && f[2])
327
+ out.deps.push((last = { name: f[1], version: f[2] }));
328
+ else if (f[0] === "=>" && last && f[2])
329
+ last.version = f[2]; // a replace directive sets the version used
330
+ }
331
+ return out;
332
+ }
333
+ /** Undo a layer's compression (gzip, zstd or none), told by its first bytes or its media type. */
334
+ export function decompressLayer(raw, kind, notes) {
335
+ if (kind === "gzip")
336
+ return raw.pipe(createGunzip());
337
+ if (kind === "zstd") {
338
+ const z = zlib.createZstdDecompress;
339
+ if (!z) {
340
+ notes.push("A layer is zstd-compressed and this Node.js can't read it (Node 22.15 or later can), so it was skipped.");
341
+ raw.destroy();
342
+ return null;
343
+ }
344
+ return raw.pipe(z());
345
+ }
346
+ return raw;
347
+ }
348
+ function compressionOf(head) {
349
+ if (head[0] === 0x1f && head[1] === 0x8b)
350
+ return "gzip";
351
+ if (head[0] === 0x28 && head[1] === 0xb5 && head[2] === 0x2f && head[3] === 0xfd)
352
+ return "zstd";
353
+ return "tar";
354
+ }
355
+ export function play(fs, e) {
356
+ switch (e.op) {
357
+ case "clear":
358
+ fs.clear(e.dir);
359
+ return;
360
+ case "remove":
361
+ fs.remove(e.path);
362
+ return;
363
+ case "link":
364
+ fs.remove(e.path);
365
+ fs.links.set(e.path, e.target);
366
+ return;
367
+ case "hardlink": {
368
+ fs.remove(e.path);
369
+ const t = norm(e.target);
370
+ const data = fs.files.get(t);
371
+ if (data)
372
+ fs.files.set(e.path, data);
373
+ const go = fs.goBinaries.get(t);
374
+ if (go)
375
+ fs.goBinaries.set(e.path, go);
376
+ const emb = fs.embedded.get(t);
377
+ if (emb)
378
+ fs.embedded.set(e.path, emb);
379
+ const mode = fs.modes.get(t);
380
+ if (mode !== undefined)
381
+ fs.modes.set(e.path, mode);
382
+ return;
383
+ }
384
+ case "file":
385
+ fs.remove(e.path);
386
+ fs.files.set(e.path, e.data);
387
+ fs.modes.set(e.path, e.mode);
388
+ return;
389
+ case "program":
390
+ fs.remove(e.path);
391
+ fs.modes.set(e.path, e.mode);
392
+ if (e.go)
393
+ fs.goBinaries.set(e.path, e.go);
394
+ if (e.embedded?.length)
395
+ fs.embedded.set(e.path, e.embedded);
396
+ return;
397
+ }
398
+ }
399
+ /** A program or shared library, looked at once: its Go module list and any encryption library built in. */
400
+ export function probeProgram(path, mode, data) {
401
+ if (!binaryFormat(data))
402
+ return { op: "program", path, mode };
403
+ const go = goBuildInfo(data) ?? undefined;
404
+ const embedded = embeddedLibraries(data, path);
405
+ return { op: "program", path, mode, ...(go ? { go } : {}), ...(embedded.length ? { embedded } : {}) };
406
+ }
407
+ /** Apply one layer to the filesystem: deletions first, then its files. Returns what it did. */
408
+ export async function applyLayer(fs, stream) {
409
+ const events = [];
410
+ const emit = (e) => {
411
+ play(fs, e);
412
+ events.push(e);
413
+ };
414
+ const choices = new Map();
415
+ await readTar(stream, (h) => {
416
+ const c = wanted(h);
417
+ choices.set(h.name, c);
418
+ return c === "skip" ? "skip" : "keep";
419
+ }, (h, data) => {
420
+ const name = h.name.replace(/\/$/, "");
421
+ const base = name.split("/").pop() ?? "";
422
+ const dir = name.slice(0, name.length - base.length).replace(/\/$/, "");
423
+ // An opaque folder: everything below it from earlier layers is gone.
424
+ if (base === ".wh..wh..opq")
425
+ return emit({ op: "clear", dir });
426
+ if (base.startsWith(".wh."))
427
+ return emit({ op: "remove", path: (dir ? dir + "/" : "") + base.slice(4) });
428
+ if (h.type === "5")
429
+ return;
430
+ if (h.type === "2")
431
+ return emit({ op: "link", path: name, target: h.linkname });
432
+ if (h.type === "1")
433
+ return emit({ op: "hardlink", path: name, target: h.linkname });
434
+ if (!data)
435
+ return emit({ op: "remove", path: name }); // replaced by a file this scan doesn't read
436
+ if (choices.get(h.name) === "probe")
437
+ return emit(probeProgram(name, h.mode, data));
438
+ emit({ op: "file", path: name, mode: h.mode, data });
439
+ });
440
+ return events;
441
+ }
442
+ // ---------- layer cache ----------
443
+ /**
444
+ * Where layers already read are kept, by digest: a layer with the same digest has the same bytes, so
445
+ * an image that shares its base with one scanned before only reads its own layers. Only layers whose
446
+ * bytes were checked against their digest are written.
447
+ */
448
+ export function layerCacheDir() {
449
+ // QUANTUM_SCAN_CACHE is the name from before the scanner was called Benthic.
450
+ const set = process.env.BENTHIC_CACHE || process.env.QUANTUM_SCAN_CACHE;
451
+ if (set)
452
+ return set;
453
+ const base = osPlatform() === "win32" ? process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local") : process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
454
+ return join(base, "hard-keel-benthic", "layers");
455
+ }
456
+ /**
457
+ * Bumped whenever what a layer's events hold changes (what a program probe looks for, say), so a
458
+ * development build never replays answers an older build of the same version gave.
459
+ */
460
+ const CACHE_FORMAT = 3;
461
+ /** The cache's entries change when the scanner does, so a newer scanner reads every layer again. */
462
+ function cacheFile(digest, scanner) {
463
+ const m = digest.match(/^sha256:([0-9a-f]{64})$/);
464
+ return m ? join(layerCacheDir(), `${scanner.replace(/[^\w.-]/g, "_")}-f${CACHE_FORMAT}`, `${m[1]}.json.gz`) : null;
465
+ }
466
+ export function readLayerCache(digest, scanner) {
467
+ const f = cacheFile(digest, scanner);
468
+ if (!f || !existsSync(f))
469
+ return null;
470
+ try {
471
+ const list = JSON.parse(gunzipSync(readFileSync(f)).toString("utf8"));
472
+ return list.map((e) => (e.op === "file" ? { ...e, data: Buffer.from(e.data ?? "", "base64") } : e));
473
+ }
474
+ catch {
475
+ return null; // a damaged entry is read again from the image
476
+ }
477
+ }
478
+ export function writeLayerCache(digest, scanner, events) {
479
+ const f = cacheFile(digest, scanner);
480
+ if (!f)
481
+ return;
482
+ try {
483
+ mkdirSync(join(f, ".."), { recursive: true });
484
+ const body = gzipSync(JSON.stringify(events.map((e) => (e.op === "file" ? { ...e, data: e.data.toString("base64") } : e))));
485
+ const tmp = `${f}.${process.pid}.tmp`;
486
+ writeFileSync(tmp, body, { mode: 0o600 });
487
+ renameSync(tmp, f);
488
+ }
489
+ catch {
490
+ // The cache only saves time; a scan never fails because of it.
491
+ }
492
+ }
493
+ /** Read a layer, or replay it from the cache. The stream is opened only when it has to be read. */
494
+ export async function readLayer(fs, digest, open, cache, notes, stats) {
495
+ if (digest && cache?.enabled) {
496
+ const hit = readLayerCache(digest, cache.scanner);
497
+ if (hit) {
498
+ for (const e of hit)
499
+ play(fs, e);
500
+ stats.cached++;
501
+ return true;
502
+ }
503
+ }
504
+ const o = await open();
505
+ if (!o)
506
+ return false;
507
+ const hash = createHash("sha256");
508
+ o.raw.on("data", (c) => hash.update(c));
509
+ const stream = decompressLayer(o.raw, o.kind, notes);
510
+ if (!stream)
511
+ return false;
512
+ const events = await applyLayer(fs, stream);
513
+ // The tar can end before the compressed stream does; read the rest so the digest covers every byte.
514
+ if (!o.raw.readableEnded && !o.raw.destroyed) {
515
+ o.raw.unpipe();
516
+ await new Promise((resolve, reject) => {
517
+ o.raw.once("end", resolve);
518
+ o.raw.once("error", reject);
519
+ o.raw.resume();
520
+ });
521
+ }
522
+ if (digest) {
523
+ const got = `sha256:${hash.digest("hex")}`;
524
+ if (got !== digest)
525
+ throw new Error(`A layer's contents don't match its digest (${digest}); the image may be damaged or changed. Nothing from this scan was cached.`);
526
+ if (cache?.enabled)
527
+ writeLayerCache(digest, cache.scanner, events);
528
+ }
529
+ return true;
530
+ }
531
+ function readJson(src, ref) {
532
+ return new Promise((resolve, reject) => {
533
+ const s = src.open(ref);
534
+ if (!s)
535
+ return reject(new Error(`${ref} is missing`));
536
+ const parts = [];
537
+ s.on("data", (c) => parts.push(c));
538
+ s.on("end", () => {
539
+ try {
540
+ resolve(JSON.parse(Buffer.concat(parts).toString("utf8")));
541
+ }
542
+ catch (e) {
543
+ reject(e);
544
+ }
545
+ });
546
+ s.on("error", reject);
547
+ });
548
+ }
549
+ function blobRef(digest) {
550
+ const [alg, hex] = digest.split(":");
551
+ return `blobs/${alg}/${hex}`;
552
+ }
553
+ export function configOf(raw) {
554
+ const c = (raw ?? {});
555
+ return {
556
+ config: {
557
+ env: c.config?.Env ?? [],
558
+ workingDir: c.config?.WorkingDir || undefined,
559
+ user: c.config?.User || undefined,
560
+ history: (c.history ?? []).map((h) => h.created_by ?? "").filter(Boolean),
561
+ },
562
+ platform: c.os ? [c.os, c.architecture, c.variant].filter(Boolean).join("/") : undefined,
563
+ };
564
+ }
565
+ /** Pick one image from an OCI index: linux/amd64 if it's there, otherwise the first. */
566
+ async function ociManifest(open, index, notes, depth = 0) {
567
+ const ix = index;
568
+ const list = (ix.manifests ?? []).filter((m) => m.platform?.architecture !== "unknown"); // build attestations
569
+ if (!list.length)
570
+ throw new Error("The image index lists no images.");
571
+ const pick = list.find((m) => m.platform?.os === "linux" && m.platform?.architecture === "amd64") ?? list[0];
572
+ if (list.length > 1 && depth === 0)
573
+ notes.push(`The image holds ${list.length} platforms; this scan read ${pick.platform ? `${pick.platform.os}/${pick.platform.architecture}` : "the first one"}.`);
574
+ const tags = list.map((m) => m.annotations?.["io.containerd.image.name"] ?? m.annotations?.["org.opencontainers.image.ref.name"]).filter((t) => Boolean(t));
575
+ const doc = (await readJson(open, blobRef(pick.digest)));
576
+ if (doc.manifests && depth < 2) {
577
+ const inner = await ociManifest(open, doc, notes, depth + 1);
578
+ return { manifest: inner.manifest, tags: tags.length ? tags : inner.tags };
579
+ }
580
+ if (!doc.config || !doc.layers)
581
+ throw new Error("The image manifest has no layers.");
582
+ return { manifest: { config: doc.config, layers: doc.layers }, tags };
583
+ }
584
+ async function loadFromOpener(src, format, cache) {
585
+ const has = (ref) => src.has(ref);
586
+ const open = src;
587
+ const fs = new ImageFS();
588
+ const notes = [];
589
+ let layers;
590
+ let cfg;
591
+ let tags = [];
592
+ if (has("manifest.json") && format !== "oci-layout") {
593
+ const m = (await readJson(open, "manifest.json"));
594
+ if (!Array.isArray(m) || !m.length || !m[0].Layers)
595
+ throw new Error("manifest.json doesn't list any layers.");
596
+ if (m.length > 1)
597
+ notes.push(`The archive holds ${m.length} images; this scan read the first.`);
598
+ layers = m[0].Layers;
599
+ tags = m[0].RepoTags ?? [];
600
+ if (m[0].Config && has(m[0].Config))
601
+ cfg = configOf(await readJson(open, m[0].Config));
602
+ format = "docker-archive";
603
+ }
604
+ else {
605
+ const { manifest, tags: t } = await ociManifest(open, await readJson(open, "index.json"), notes);
606
+ tags = t;
607
+ layers = manifest.layers.map((l) => blobRef(l.digest));
608
+ if (has(blobRef(manifest.config.digest)))
609
+ cfg = configOf(await readJson(open, blobRef(manifest.config.digest)));
610
+ }
611
+ let read = 0;
612
+ const stats = { cached: 0 };
613
+ for (const ref of layers) {
614
+ // Newer archives name each layer by its digest; older docker save archives don't.
615
+ const hex = norm(ref).match(/^blobs\/sha256\/([0-9a-f]{64})$/)?.[1];
616
+ const ok = await readLayer(fs, hex ? `sha256:${hex}` : undefined, () => {
617
+ const head = src.peek(ref, 4);
618
+ const raw = src.open(ref);
619
+ if (!head || !raw) {
620
+ notes.push(`A layer (${ref}) is missing from the image.`);
621
+ return null;
622
+ }
623
+ return { raw, kind: compressionOf(head) };
624
+ }, cache, notes, stats);
625
+ if (ok)
626
+ read++;
627
+ }
628
+ return { fs, format, layers: read, ...(stats.cached ? { cachedLayers: stats.cached } : {}), platform: cfg?.platform, tags, config: cfg?.config, notes };
629
+ }
630
+ /** Index a tar file's entries by name, so each one can be read on its own. */
631
+ async function indexTar(file) {
632
+ const index = new Map();
633
+ const links = new Map();
634
+ await readTar(createReadStream(file), () => "skip", (h, _d, offset) => {
635
+ if (h.type === "0")
636
+ index.set(h.name.replace(/\/$/, ""), { offset, size: h.size });
637
+ else if (h.type === "2" || h.type === "1")
638
+ links.set(h.name, h.linkname);
639
+ });
640
+ // docker save writes some layers as links to an identical one.
641
+ for (const [name, target] of links) {
642
+ const t = index.get(norm(linkTarget(name, target)));
643
+ if (t)
644
+ index.set(name, t);
645
+ }
646
+ return index;
647
+ }
648
+ function linkTarget(name, target) {
649
+ if (target.startsWith("/"))
650
+ return target;
651
+ const dir = name.split("/").slice(0, -1).join("/");
652
+ return dir ? `${dir}/${target}` : target;
653
+ }
654
+ function readBytes(file, at, n) {
655
+ const fd = openSync(file, "r");
656
+ try {
657
+ const b = Buffer.alloc(n);
658
+ const got = readSync(fd, b, 0, n, at);
659
+ return b.subarray(0, got);
660
+ }
661
+ finally {
662
+ closeSync(fd);
663
+ }
664
+ }
665
+ function isGzipFile(file) {
666
+ const b = readBytes(file, 0, 2);
667
+ return b[0] === 0x1f && b[1] === 0x8b;
668
+ }
669
+ /** Read an image from a docker save or OCI archive, an OCI layout folder, or an unpacked root filesystem. */
670
+ export async function loadImage(input, cache) {
671
+ if (!existsSync(input))
672
+ throw new Error(`Can't scan ${input}: there is no such file or folder. Save an image first, for example: docker save myapp:latest -o myapp.tar`);
673
+ const st = statSync(input);
674
+ if (st.isDirectory()) {
675
+ const at = (ref) => join(input, norm(ref));
676
+ const has = (ref) => existsSync(at(ref));
677
+ const src = {
678
+ has,
679
+ open: (ref) => (has(ref) ? createReadStream(at(ref)) : null),
680
+ peek: (ref, n) => (has(ref) ? readBytes(at(ref), 0, n) : null),
681
+ };
682
+ if (has("index.json") && (has("oci-layout") || has("blobs")))
683
+ return loadFromOpener(src, "oci-layout", cache);
684
+ if (has("manifest.json"))
685
+ return loadFromOpener(src, "docker-archive", cache);
686
+ return loadFolder(input);
687
+ }
688
+ let file = input;
689
+ let tmp = null;
690
+ try {
691
+ if (isGzipFile(input)) {
692
+ // A compressed archive can't be read out of order, so unpack it once.
693
+ tmp = mkdtempSync(join(tmpdir(), "benthic-image-"));
694
+ file = join(tmp, "image.tar");
695
+ const out = createWriteStream(file);
696
+ await new Promise((resolve, reject) => {
697
+ createReadStream(input).pipe(createGunzip()).on("error", reject).pipe(out).on("finish", resolve).on("error", reject);
698
+ });
699
+ }
700
+ const index = await indexTar(file);
701
+ if (!index.has("manifest.json") && !index.has("index.json"))
702
+ throw new Error(`${input} is a tar file but not a saved image (no manifest.json or index.json). Save one with: docker save myapp:latest -o myapp.tar`);
703
+ const src = {
704
+ has: (ref) => index.has(norm(ref)),
705
+ open: (ref) => {
706
+ const e = index.get(norm(ref));
707
+ if (!e)
708
+ return null;
709
+ return e.size ? createReadStream(file, { start: e.offset, end: e.offset + e.size - 1 }) : createReadStream(file, { start: 0, end: -1 });
710
+ },
711
+ peek: (ref, n) => {
712
+ const e = index.get(norm(ref));
713
+ return e ? readBytes(file, e.offset, Math.min(n, e.size)) : null;
714
+ },
715
+ };
716
+ return await loadFromOpener(src, index.has("manifest.json") ? "docker-archive" : "oci-archive", cache);
717
+ }
718
+ finally {
719
+ if (tmp)
720
+ rmSync(tmp, { recursive: true, force: true });
721
+ }
722
+ }
723
+ /** An unpacked root filesystem on disk: read the same files a layer would give. */
724
+ function loadFolder(root) {
725
+ const fs = new ImageFS();
726
+ const notes = [];
727
+ const walk = (rel) => {
728
+ let names;
729
+ try {
730
+ names = readdirSync(join(root, rel));
731
+ }
732
+ catch {
733
+ return;
734
+ }
735
+ for (const n of names) {
736
+ const p = rel ? `${rel}/${n}` : n;
737
+ let st;
738
+ try {
739
+ st = lstatSync(join(root, p));
740
+ }
741
+ catch {
742
+ continue;
743
+ }
744
+ if (st.isSymbolicLink()) {
745
+ try {
746
+ fs.links.set(p, readlinkSync(join(root, p)));
747
+ }
748
+ catch {
749
+ // unreadable link
750
+ }
751
+ continue;
752
+ }
753
+ if (st.isDirectory()) {
754
+ if (/^(proc|sys|dev|run)$/.test(p))
755
+ continue;
756
+ if (PACKAGE_DIRS.test(p + "/") && !/node_modules|site-packages|dist-packages/.test(n) && !/(node_modules|site-packages|dist-packages)\//.test(p))
757
+ continue;
758
+ walk(p);
759
+ continue;
760
+ }
761
+ if (!st.isFile())
762
+ continue;
763
+ const h = { name: p, type: "0", size: st.size, mode: st.mode & 0o777, linkname: "" };
764
+ const c = wanted(h);
765
+ if (c === "skip")
766
+ continue;
767
+ let data;
768
+ try {
769
+ data = readFileSync(join(root, p));
770
+ }
771
+ catch {
772
+ continue;
773
+ }
774
+ if (c === "probe") {
775
+ play(fs, probeProgram(p, h.mode, data));
776
+ continue;
777
+ }
778
+ fs.files.set(p, data);
779
+ fs.modes.set(p, h.mode);
780
+ }
781
+ };
782
+ walk("");
783
+ if (!fs.files.has("etc/os-release") && !fs.links.has("etc/os-release") && !fs.files.has("usr/lib/os-release"))
784
+ notes.push("No /etc/os-release here: if this isn't a container's root filesystem, scan it as a folder instead.");
785
+ return { fs, format: "folder", layers: 0, tags: [], notes };
786
+ }
787
+ /** Packages from a Debian/Ubuntu status file (or a distroless status.d entry). */
788
+ export function dpkgPackages(text, file) {
789
+ const out = [];
790
+ let cur = { installed: true, line: 1 };
791
+ const lines = text.split(/\r?\n/);
792
+ const flush = () => {
793
+ if (cur.name && cur.version && cur.installed)
794
+ out.push({ name: cur.name, version: cur.version, file, line: cur.line });
795
+ };
796
+ lines.forEach((l, i) => {
797
+ if (!l.trim()) {
798
+ flush();
799
+ cur = { installed: true, line: i + 2 };
800
+ return;
801
+ }
802
+ const m = l.match(/^(Package|Version|Status):\s*(.+)$/);
803
+ if (!m)
804
+ return;
805
+ if (m[1] === "Package")
806
+ cur.name = m[2].trim();
807
+ if (m[1] === "Version")
808
+ cur.version = m[2].trim();
809
+ if (m[1] === "Status")
810
+ cur.installed = /\binstalled$/.test(m[2].trim());
811
+ });
812
+ flush();
813
+ return out;
814
+ }
815
+ /** Packages from Alpine's installed database. */
816
+ export function apkPackages(text, file) {
817
+ const out = [];
818
+ let cur = { line: 1 };
819
+ text.split(/\r?\n/).forEach((l, i) => {
820
+ if (!l.trim()) {
821
+ if (cur.name && cur.version)
822
+ out.push({ name: cur.name, version: cur.version, file, line: cur.line });
823
+ cur = { line: i + 2 };
824
+ return;
825
+ }
826
+ if (l.startsWith("P:"))
827
+ cur.name = l.slice(2).trim();
828
+ if (l.startsWith("V:"))
829
+ cur.version = l.slice(2).trim();
830
+ });
831
+ if (cur.name && cur.version)
832
+ out.push({ name: cur.name, version: cur.version, file, line: cur.line });
833
+ return out;
834
+ }
835
+ /** The upstream version: no epoch (1:) and no packaging suffix (-1~deb12u2, -r5). */
836
+ export function upstreamVersion(v) {
837
+ return v.replace(/^\d+:/, "").replace(/-[^-]*$/, (s) => (/^-\d/.test(s) || /^-r\d/.test(s) || /[~+]/.test(s) || /ubuntu|deb/.test(s) ? "" : s));
838
+ }
839
+ function versionAtLeast(v, min) {
840
+ const parts = v.match(/\d+/g)?.map(Number) ?? [];
841
+ for (let i = 0; i < min.length; i++) {
842
+ const a = parts[i] ?? 0;
843
+ if (a !== min[i])
844
+ return a > min[i];
845
+ }
846
+ return true;
847
+ }
848
+ /**
849
+ * What a system package means for post-quantum readiness. Only claims that hold for the upstream
850
+ * release are made; a distribution can backport features, which is why its version is shown too.
851
+ */
852
+ export function judgePackage(name, version) {
853
+ const n = name.toLowerCase();
854
+ const v = upstreamVersion(version);
855
+ if (/^(openssl|libssl\d*(\.\d+)*(t64)?|libcrypto\d*(\.\d+)*|openssl-libs|openssl3?)$/.test(n)) {
856
+ if (versionAtLeast(v, [3, 5]))
857
+ return { product: "OpenSSL", provides: "TLS, RSA, ECDSA, and ML-KEM, ML-DSA, SLH-DSA (3.5 and later)", risk: "mixed" };
858
+ if (/^1\./.test(v))
859
+ return { product: "OpenSSL", provides: "TLS, RSA, ECDSA; no post-quantum methods, and 1.x is out of upstream support", risk: "quantum-vulnerable" };
860
+ return { product: "OpenSSL", provides: "TLS, RSA, ECDSA; ML-KEM and ML-DSA arrive in 3.5", risk: "quantum-vulnerable" };
861
+ }
862
+ if (/^(openssh|openssh-server|openssh-client|openssh-client-default|openssh-server-pam)$/.test(n)) {
863
+ if (versionAtLeast(v, [9, 9]))
864
+ return { product: "OpenSSH", provides: "SSH; hybrid post-quantum key exchange by default, including mlkem768x25519 (9.9 and later)", risk: "mixed" };
865
+ if (versionAtLeast(v, [9, 0]))
866
+ return { product: "OpenSSH", provides: "SSH; hybrid post-quantum key exchange (sntrup761x25519) by default since 9.0", risk: "mixed" };
867
+ return { product: "OpenSSH", provides: "SSH; no post-quantum key exchange by default before 9.0", risk: "quantum-vulnerable" };
868
+ }
869
+ const jdk = n.match(/^openjdk-?(\d+)(-jre|-jdk)?(-headless)?$/);
870
+ if (jdk) {
871
+ if (Number(jdk[1]) >= 24)
872
+ return { product: `Java ${jdk[1]}`, provides: "Java security: ML-KEM and ML-DSA built in (JDK 24 and later)", risk: "mixed" };
873
+ return { product: `Java ${jdk[1]}`, provides: "Java security: RSA, ECDSA, ECDH; no ML-KEM or ML-DSA built in before JDK 24", risk: "quantum-vulnerable" };
874
+ }
875
+ const go = n.match(/^golang-(\d+\.\d+)(-go)?$|^go$/);
876
+ if (go) {
877
+ const gv = go[1] ?? v;
878
+ if (versionAtLeast(gv, [1, 24]))
879
+ return { product: `Go ${gv}`, provides: "Go standard library: ML-KEM, and hybrid ML-KEM TLS by default (1.24 and later)", risk: "mixed" };
880
+ return { product: `Go ${gv}`, provides: "Go standard library: no ML-KEM before 1.24", risk: "quantum-vulnerable" };
881
+ }
882
+ if (/^(libgnutls\d*(t64)?|gnutls)$/.test(n))
883
+ return { product: "GnuTLS", provides: "TLS; check its release notes for ML-KEM support", risk: "check" };
884
+ if (/^(libnss3|nss)$/.test(n))
885
+ return { product: "NSS", provides: "TLS and certificates; check its release notes for ML-KEM support", risk: "check" };
886
+ if (/^(libgcrypt\d*|libgcrypt)$/.test(n))
887
+ return { product: "Libgcrypt", provides: "RSA, ECC and symmetric encryption", risk: "check" };
888
+ if (/^(libsodium\d*|libsodium)$/.test(n))
889
+ return { product: "libsodium", provides: "X25519, Ed25519, ChaCha20", risk: "quantum-vulnerable" };
890
+ if (/^(libmbedtls\d*|libmbedcrypto\d*|mbedtls)$/.test(n))
891
+ return { product: "Mbed TLS", provides: "TLS, RSA, ECC", risk: "check" };
892
+ if (/^(libwolfssl\d*|wolfssl)$/.test(n))
893
+ return { product: "wolfSSL", provides: "TLS; post-quantum options depend on how it was built", risk: "check" };
894
+ if (/^(libgnupg|gnupg|gnupg2|gpg)$/.test(n))
895
+ return { product: "GnuPG", provides: "OpenPGP with RSA and ECC", risk: "quantum-vulnerable" };
896
+ if (n === "aws-lc")
897
+ return { product: "AWS-LC", provides: "TLS, RSA, ECDSA; recent releases add ML-KEM", risk: "check" };
898
+ if (n === "boringssl")
899
+ return { product: "BoringSSL", provides: "TLS, RSA, ECDSA; recent builds add ML-KEM hybrid key exchange", risk: "check" };
900
+ if (n === "libressl")
901
+ return { product: "LibreSSL", provides: "TLS, RSA, ECDSA; check its release notes for ML-KEM support", risk: "check" };
902
+ if (n === "ring")
903
+ return { product: "ring (Rust)", provides: "RSA, ECDSA, Ed25519, X25519; no post-quantum methods", risk: "quantum-vulnerable" };
904
+ if (/^(liboqs\d*|liboqs)$/.test(n))
905
+ return { product: "liboqs", provides: "Post-quantum algorithms (Open Quantum Safe)", risk: "quantum-safe" };
906
+ if (/^(oqs-provider|openssl-oqs-provider)$/.test(n))
907
+ return { product: "oqs-provider", provides: "Post-quantum algorithms for OpenSSL 3", risk: "quantum-safe" };
908
+ return null;
909
+ }
910
+ /** The Go toolchain a program was built with, in the same terms. */
911
+ export function judgeGo(goVersion) {
912
+ const v = goVersion.replace(/^go/, "");
913
+ if (versionAtLeast(v, [1, 24]))
914
+ return { product: `Go ${v}`, provides: "Built with Go 1.24 or later: hybrid ML-KEM TLS key exchange by default", risk: "mixed" };
915
+ if (versionAtLeast(v, [1, 23]))
916
+ return { product: `Go ${v}`, provides: "Built with Go 1.23: a pre-standard Kyber hybrid in TLS by default; rebuild with 1.24 or later for ML-KEM", risk: "check" };
917
+ return { product: `Go ${v}`, provides: "Built with Go before 1.23: no post-quantum TLS key exchange; rebuild with 1.24 or later", risk: "quantum-vulnerable" };
918
+ }
919
+ /** The image's files as a machine to check, without running anything in it. */
920
+ export function imageHostIO(fs, opensshVersion) {
921
+ return {
922
+ platform: "linux",
923
+ home: "/root",
924
+ read: (p) => fs.read(p),
925
+ list: (d) => fs.list(d),
926
+ // Only `ssh -V` is asked, for the OpenSSH version; the package list answers it.
927
+ run: (cmd, args) => (cmd === "ssh" && args[0] === "-V" && opensshVersion ? `OpenSSH_${upstreamVersion(opensshVersion)}` : null),
928
+ };
929
+ }
930
+ function osName(fs) {
931
+ const t = fs.read("etc/os-release") ?? fs.read("usr/lib/os-release");
932
+ if (!t)
933
+ return {};
934
+ const get = (k) => t.match(new RegExp(`^${k}="?([^"\\n]*)"?`, "m"))?.[1];
935
+ return { id: get("ID"), pretty: get("PRETTY_NAME") };
936
+ }
937
+ /**
938
+ * The build history as a Dockerfile, so the Dockerfile checks see it, followed by the environment
939
+ * the image starts with. Secrets passed as build arguments or ENV stay in the image for anyone who has it.
940
+ */
941
+ export function configAsDockerfile(c) {
942
+ const lines = [];
943
+ for (const h of c.history) {
944
+ let s = h.replace(/^\/bin\/sh -c #\(nop\)\s*/, "").replace(/\s+#\s*buildkit$/, "").trim();
945
+ if (/^\/bin\/(ba)?sh -c /.test(s))
946
+ s = `RUN ${s.replace(/^\/bin\/(ba)?sh -c /, "")}`;
947
+ else if (!/^[A-Z]+\s/.test(s))
948
+ s = `RUN ${s}`;
949
+ lines.push(s);
950
+ }
951
+ // The environment, unless the history already set it the same way.
952
+ for (const e of c.env)
953
+ if (!lines.some((l) => l === `ENV ${e}` || l.startsWith(`ENV ${e} `)))
954
+ lines.push(`ENV ${e}`);
955
+ return lines.join("\n") + "\n";
956
+ }
957
+ /** Turn a loaded image into the files, libraries and facts the scan reports on. */
958
+ export function imageScanInput(img, label) {
959
+ const fs = img.fs;
960
+ const files = [];
961
+ const libraries = [];
962
+ const system = [];
963
+ const os = osName(fs);
964
+ const distro = (os.id ?? (fs.files.has("lib/apk/db/installed") ? "alpine" : "debian")).toLowerCase();
965
+ // System packages.
966
+ const pkgs = [];
967
+ for (const [path, data] of fs.files) {
968
+ if (/^var\/lib\/dpkg\/status(\.d\/.*)?$/.test(path))
969
+ pkgs.push(...dpkgPackages(data.toString("utf8"), path));
970
+ else if (path === "lib/apk/db/installed")
971
+ pkgs.push(...apkPackages(data.toString("utf8"), path));
972
+ }
973
+ const eco = fs.files.has("lib/apk/db/installed") ? "apk" : "deb";
974
+ const seenPkg = new Set();
975
+ for (const p of pkgs) {
976
+ const j = judgePackage(p.name, p.version);
977
+ if (!j || seenPkg.has(p.name))
978
+ continue;
979
+ seenPkg.add(p.name);
980
+ libraries.push({ name: p.name, version: p.version, ecosystem: eco, namespace: distro, file: p.file, line: p.line, provides: `${j.product}: ${j.provides}`, risk: j.risk });
981
+ system.push({ product: j.product, package: p.name, version: p.version, risk: j.risk, provides: j.provides });
982
+ }
983
+ if (!pkgs.length && [...fs.files.keys()].some((k) => k.startsWith("var/lib/rpm/") || k.startsWith("usr/lib/sysimage/rpm/")))
984
+ img.notes.push("This image uses RPM packages, whose database isn't read yet; system packages aren't listed.");
985
+ // Go programs.
986
+ const goPrograms = [];
987
+ for (const [path, go] of fs.goBinaries) {
988
+ const j = judgeGo(go.goVersion);
989
+ goPrograms.push({ path, goVersion: go.goVersion, risk: j.risk });
990
+ libraries.push({ name: "stdlib", version: go.goVersion.replace(/^go/, ""), ecosystem: "golang", file: path, line: 0, provides: `${j.product}: ${j.provides}`, risk: j.risk });
991
+ for (const d of go.deps) {
992
+ const k = knownLibrary("golang", d.name);
993
+ if (k)
994
+ libraries.push({ name: d.name, version: d.version, ecosystem: "golang", file: path, line: 0, provides: k.provides, risk: k.risk });
995
+ }
996
+ }
997
+ // Encryption libraries compiled into programs, which no package list shows.
998
+ const builtIn = [];
999
+ for (const [path, libs] of fs.embedded) {
1000
+ for (const l of libs) {
1001
+ const j = judgePackage(l.package, l.version ?? "");
1002
+ if (!j)
1003
+ continue;
1004
+ builtIn.push({ path, product: j.product, ...(l.version ? { version: l.version } : {}), risk: j.risk, provides: j.provides });
1005
+ libraries.push({ name: l.package, ...(l.version ? { version: l.version } : {}), ecosystem: "generic", file: path, line: 0, provides: `${j.product}, built into the program: ${j.provides}`, risk: j.risk });
1006
+ }
1007
+ }
1008
+ // Java keystores: private keys stored in the image, and the certificates kept in the clear with them.
1009
+ const keystores = [];
1010
+ const storeFindings = [];
1011
+ for (const [path, data] of fs.files) {
1012
+ if (!KEYSTORE.test(path))
1013
+ continue;
1014
+ const ks = readKeystore(data);
1015
+ if (!ks)
1016
+ continue;
1017
+ const keys = ks.entries.filter((e) => e.kind !== "trusted-certificate");
1018
+ keystores.push({ path, format: ks.format, privateKeys: keys.length, certificates: ks.entries.reduce((n, e) => n + e.certificates.length, 0), sealed: ks.sealed });
1019
+ if (keys.length || ks.format === "PKCS12") {
1020
+ const what = keys.length ? `${keys.length} private or secret key${keys.length === 1 ? "" : "s"}` : "keys behind its password";
1021
+ storeFindings.push({
1022
+ kind: "secret",
1023
+ ruleId: "image-keystore",
1024
+ title: `${ks.format} keystore with ${what} stored in the image`,
1025
+ algorithm: `${ks.format} keystore`,
1026
+ primitive: "credential",
1027
+ risk: "secret",
1028
+ severity: "high",
1029
+ file: path,
1030
+ line: 1,
1031
+ snippet: keys.length ? `${ks.format}: ${keys.map((k) => k.alias).slice(0, 5).join(", ")}${keys.length > 5 ? ", ..." : ""}` : `${ks.format} keystore`,
1032
+ fix: "Anyone who pulls the image has the keystore, and its password is often in the image too. Mount it at run time from a secret store, and replace the keys it held.",
1033
+ });
1034
+ }
1035
+ // Each certificate once, judged like a PEM certificate.
1036
+ const seen = new Set();
1037
+ for (const e of ks.entries) {
1038
+ for (const c of e.certificates) {
1039
+ const id = `${c.material.subject}|${c.material.notAfter}|${c.key?.algorithm}`;
1040
+ if (seen.has(id))
1041
+ continue;
1042
+ seen.add(id);
1043
+ storeFindings.push(...materialFindings(path, 1, "CERTIFICATE", c).findings.map((f) => ({ ...f, snippet: `${ks.format} entry "${e.alias}": ${f.snippet.replace(/^-----BEGIN CERTIFICATE-----\s*/, "")}`.slice(0, 160) })));
1044
+ }
1045
+ }
1046
+ }
1047
+ // Node and Python packages that came with the image.
1048
+ for (const [path, data] of fs.files) {
1049
+ if (NODE_PKG.test(path)) {
1050
+ try {
1051
+ const j = JSON.parse(data.toString("utf8"));
1052
+ const k = j.name ? knownLibrary("npm", j.name) : undefined;
1053
+ if (k && j.name)
1054
+ libraries.push({ name: j.name, ...(j.version ? { version: j.version } : {}), ecosystem: "npm", file: path, line: 1, provides: k.provides, risk: k.risk });
1055
+ }
1056
+ catch {
1057
+ // not a package file after all
1058
+ }
1059
+ }
1060
+ else if (PY_META.test(path)) {
1061
+ const t = data.toString("utf8", 0, Math.min(data.length, 8192));
1062
+ const name = t.match(/^Name:\s*(.+)$/m)?.[1]?.trim();
1063
+ const version = t.match(/^Version:\s*(.+)$/m)?.[1]?.trim();
1064
+ const k = name ? knownLibrary("pypi", name) : undefined;
1065
+ if (k && name)
1066
+ libraries.push({ name, ...(version ? { version } : {}), ecosystem: "pypi", file: path, line: 1, provides: k.provides, risk: k.risk });
1067
+ }
1068
+ }
1069
+ // Trusted authorities: counted only.
1070
+ let trustedAuthorities = 0;
1071
+ for (const b of CA_BUNDLES) {
1072
+ const t = fs.read(b);
1073
+ if (t) {
1074
+ trustedAuthorities = (t.match(/-----BEGIN CERTIFICATE-----/g) ?? []).length;
1075
+ break;
1076
+ }
1077
+ }
1078
+ // The distribution's package signing keys: counted by type, like the trust list.
1079
+ const signingKeys = {};
1080
+ for (const [path, data] of fs.files) {
1081
+ if (!VENDOR_KEYS.test(path))
1082
+ continue;
1083
+ const types = data.includes(0) || /\.gpg$/.test(path) || data.includes("BEGIN PGP") ? pgpKeyTypes(data) : pemKeyTypes(data.toString("utf8"));
1084
+ for (const t of types)
1085
+ signingKeys[t] = (signingKeys[t] ?? 0) + 1;
1086
+ }
1087
+ // Everything else goes through the folder scan's checks.
1088
+ for (const [path, data] of fs.files) {
1089
+ if (PACKAGE_DB.test(path) || NODE_PKG.test(path) || PY_META.test(path) || CA_BUNDLES.includes(path) || VENDOR_KEYS.test(path) || path.endsWith("os-release"))
1090
+ continue;
1091
+ if (data.includes(0) || KEYSTORE.test(path))
1092
+ continue; // binary
1093
+ // SSH public keys are read by the host checks below, for their type and size.
1094
+ if (/^(etc\/ssh|root\/\.ssh)\/[^/]+\.pub$/.test(path) || path === "root/.ssh/authorized_keys")
1095
+ continue;
1096
+ files.push({ path, content: data.toString("utf8") });
1097
+ }
1098
+ if (img.config)
1099
+ files.push({ path: "image-config/Dockerfile", content: configAsDockerfile(img.config) });
1100
+ // SSH server settings and host keys, and the OpenSSL policy, as map checks them on a machine.
1101
+ const ssh = pkgs.find((p) => /^openssh(-server)?$/.test(p.name)) ?? pkgs.find((p) => /^openssh/.test(p.name));
1102
+ const host = runHost(new ActivityLog(), imageHostIO(fs, ssh?.version));
1103
+ const hostFindings = host.findings.map((f) => {
1104
+ const file = norm(f.target);
1105
+ // Point at the setting where there is one, otherwise the file's first line.
1106
+ const lines = (fs.read(file) ?? "").split(/\r?\n/);
1107
+ const at = /^ssh-/.test(f.ruleId) ? lines.findIndex((l) => /^\s*(KexAlgorithms|Ciphers|MACs|HostKeyAlgorithms)\s/i.test(l)) : -1;
1108
+ return { ...toFinding(f), file, line: at >= 0 ? at + 1 : fs.read(file) !== null ? 1 : 0 };
1109
+ });
1110
+ const findings = [...hostFindings, ...storeFindings];
1111
+ const summary = {
1112
+ image: label,
1113
+ format: img.format,
1114
+ tags: img.tags,
1115
+ ...(img.platform ? { platform: img.platform } : {}),
1116
+ ...(os.pretty ? { os: os.pretty } : {}),
1117
+ layers: img.layers,
1118
+ filesRead: files.length,
1119
+ trustedAuthorities,
1120
+ ...(Object.keys(signingKeys).length ? { signingKeys } : {}),
1121
+ system,
1122
+ goPrograms,
1123
+ builtIn,
1124
+ keystores,
1125
+ ...(img.cachedLayers ? { cachedLayers: img.cachedLayers } : {}),
1126
+ notes: [...img.notes, "Java archives (.jar) aren't opened yet. Compiled programs are read for built-in encryption libraries by their version text, so a stripped or unusual build can be missed."],
1127
+ };
1128
+ return { files, libraries, findings, summary };
1129
+ }
1130
+ /** The image part of the text report. */
1131
+ export function imageText(s) {
1132
+ const out = [];
1133
+ const name = s.tags[0] ?? s.image;
1134
+ out.push(`Image: ${name}${s.platform ? ` (${s.platform})` : ""}${s.os ? `, ${s.os}` : ""}`);
1135
+ out.push(` ${s.layers ? `${s.layers} layer${s.layers === 1 ? "" : "s"}${s.cachedLayers ? ` (${s.cachedLayers} from the cache)` : ""}, ` : ""}${s.filesRead} files checked${s.trustedAuthorities ? `, ${s.trustedAuthorities} trusted authority certificates in the system list (not listed one by one)` : ""}`);
1136
+ if (s.signingKeys) {
1137
+ const kinds = Object.entries(s.signingKeys).sort((x, y) => y[1] - x[1]);
1138
+ const total = kinds.reduce((n, [, c]) => n + c, 0);
1139
+ const list = kinds.map(([t, c]) => `${c} ${t}`);
1140
+ const said = list.length > 1 ? `${list.slice(0, -1).join(", ")} and ${list[list.length - 1]}` : list[0];
1141
+ // Post-quantum and hybrid keys (ML-DSA, SLH-DSA, ML-KEM) hold up; the classical ones don't.
1142
+ const breakable = kinds.filter(([t]) => !/ML-DSA|SLH-DSA|ML-KEM/.test(t)).reduce((n, [, c]) => n + c, 0);
1143
+ const verdict = breakable === total ? ", all quantum-breakable" : breakable ? `, ${breakable} quantum-breakable` : ", all post-quantum";
1144
+ out.push(` ${total} package signing key${total === 1 ? "" : "s"} from the distribution (${said})${verdict}; the distribution replaces them, so they're counted, not listed`);
1145
+ }
1146
+ const mark = (r) => (r === "quantum-vulnerable" ? "needs an update" : r === "mixed" ? "has post-quantum options" : r === "quantum-safe" ? "quantum-safe" : "check");
1147
+ if (s.system.length) {
1148
+ out.push("", "System encryption packages:");
1149
+ // One line per product and version: openssl and libssl3 are the same OpenSSL.
1150
+ const groups = new Map();
1151
+ for (const p of s.system)
1152
+ groups.set(`${p.product} ${p.version}`, [...(groups.get(`${p.product} ${p.version}`) ?? []), p]);
1153
+ for (const [, ps] of groups)
1154
+ out.push(` ${ps[0].product} ${ps[0].version} (${ps.map((p) => p.package).join(", ")}): ${mark(ps[0].risk)}. ${ps[0].provides}`);
1155
+ }
1156
+ if (s.goPrograms.length) {
1157
+ out.push("", "Go programs:");
1158
+ for (const g of s.goPrograms.slice(0, 10))
1159
+ out.push(` /${g.path}: built with ${g.goVersion}, ${mark(g.risk)}`);
1160
+ if (s.goPrograms.length > 10)
1161
+ out.push(` and ${s.goPrograms.length - 10} more`);
1162
+ }
1163
+ if (s.builtIn.length) {
1164
+ out.push("", "Encryption built into programs:");
1165
+ for (const b of s.builtIn.slice(0, 10))
1166
+ out.push(` /${b.path}: ${b.product}${b.version ? ` ${b.version}` : ""}, ${mark(b.risk)}. ${b.provides}`);
1167
+ if (s.builtIn.length > 10)
1168
+ out.push(` and ${s.builtIn.length - 10} more`);
1169
+ }
1170
+ if (s.keystores.length) {
1171
+ out.push("", "Java keystores:");
1172
+ for (const k of s.keystores.slice(0, 10))
1173
+ out.push(` /${k.path}: ${k.format}, ${k.privateKeys} private or secret key${k.privateKeys === 1 ? "" : "s"}, ${k.certificates} certificate${k.certificates === 1 ? "" : "s"}${k.sealed ? " (some entries are behind its password and weren't read)" : ""}`);
1174
+ }
1175
+ if (s.notes.length) {
1176
+ out.push("", "Not covered:");
1177
+ for (const n of s.notes)
1178
+ out.push(` ${n}`);
1179
+ }
1180
+ return out.join("\n");
1181
+ }
1182
+ /** For tests: write a tar archive from a list of entries. */
1183
+ export function makeTar(entries) {
1184
+ const parts = [];
1185
+ for (const e of entries) {
1186
+ const data = e.data === undefined ? Buffer.alloc(0) : Buffer.isBuffer(e.data) ? e.data : Buffer.from(e.data);
1187
+ const h = Buffer.alloc(BLOCK);
1188
+ let name = e.name;
1189
+ if (Buffer.byteLength(name) > 99) {
1190
+ // PAX record for a long name.
1191
+ const rec = (k, v) => {
1192
+ const body = ` ${k}=${v}\n`;
1193
+ let len = body.length + 1;
1194
+ while (String(len).length + body.length !== len)
1195
+ len = String(len).length + body.length;
1196
+ return `${len}${body}`;
1197
+ };
1198
+ const pax = Buffer.from(rec("path", name));
1199
+ parts.push(...tarBlock("PaxHeader", pax, "x", 0o644, ""));
1200
+ name = name.slice(-99);
1201
+ }
1202
+ h.write(name, 0, 100, "utf8");
1203
+ h.write((e.mode ?? 0o644).toString(8).padStart(7, "0") + "\0", 100, 8, "latin1");
1204
+ h.write("0000000\0", 108, 8, "latin1");
1205
+ h.write("0000000\0", 116, 8, "latin1");
1206
+ h.write(data.length.toString(8).padStart(11, "0") + "\0", 124, 12, "latin1");
1207
+ h.write("00000000000\0", 136, 12, "latin1");
1208
+ h.write(e.type ?? "0", 156, 1, "latin1");
1209
+ h.write(e.linkname ?? "", 157, 100, "utf8");
1210
+ h.write("ustar\u000000", 257, 8, "latin1");
1211
+ h.fill(0x20, 148, 156);
1212
+ let sum = 0;
1213
+ for (const x of h)
1214
+ sum += x;
1215
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "latin1");
1216
+ parts.push(h, data, Buffer.alloc((BLOCK - (data.length % BLOCK)) % BLOCK));
1217
+ }
1218
+ parts.push(Buffer.alloc(BLOCK * 2));
1219
+ return Buffer.concat(parts);
1220
+ }
1221
+ function tarBlock(name, data, type, mode, linkname) {
1222
+ const t = makeTar([{ name, data, type, mode, linkname }]);
1223
+ return [t.subarray(0, t.length - BLOCK * 2)];
1224
+ }