@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
@@ -0,0 +1,327 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // benthic map: asks before each area, runs only what was approved, and writes the encryption map.
4
+ // Unattended runs use a scope file, which records what was approved. Nothing outside it is touched.
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { applyIgnore, applyIgnoreTargets, ignoreFileIn, parseIgnore } from "./ignore.js";
10
+ import { buildCbom } from "./cbom.js";
11
+ import { buildMapSarif } from "./map-sarif.js";
12
+ import { ActivityLog } from "./map-activity.js";
13
+ import { CARDS, cardText } from "./map-areas.js";
14
+ import { runHost } from "./map-host.js";
15
+ import { fromCodeFinding, rank, toFinding } from "./map-rank.js";
16
+ import { buildMapReport, mapHtml, mapText } from "./map-report.js";
17
+ import { emptyResult } from "./map-types.js";
18
+ import { cloudKeyAdvice } from "./map-cloud-keys.js";
19
+ import { parseCloudScope, PROVIDERS, runCloud } from "./map-cloud.js";
20
+ import { isPrivateRange, machineRanges, parseRange, realNetIO, runNetwork, suggestedRanges } from "./map-network.js";
21
+ import { askPeople, parseAnswers, QUESTIONS, scorePeople } from "./map-people.js";
22
+ import { proofRecord, runWeb } from "./map-web.js";
23
+ import { scanFiles } from "./scan.js";
24
+ import { INDUSTRIES, SIZES } from "./share-config.js";
25
+ import { walkFolder } from "./walk.js";
26
+ export const SCOPE_FILE = "benthic.scope.json";
27
+ /** The saved answers' name before the scanner was called Benthic. Still read by prove. */
28
+ export const OLD_SCOPE_FILE = "quantum-scan.scope.json";
29
+ export function parseScope(text) {
30
+ let v;
31
+ try {
32
+ v = JSON.parse(text);
33
+ }
34
+ catch {
35
+ return { error: "the scope file isn't valid JSON" };
36
+ }
37
+ if (!v || v.version !== 1 || typeof v.areas !== "object")
38
+ return { error: "the scope file needs version 1 and an areas object" };
39
+ const s = { version: 1, created: String(v.created ?? ""), areas: {} };
40
+ if (typeof v.ownershipToken === "string" && /^[a-f0-9]{24}$/.test(v.ownershipToken))
41
+ s.ownershipToken = v.ownershipToken;
42
+ const strings = (x) => (Array.isArray(x) ? x.filter((y) => typeof y === "string" && y.length > 0 && y.length < 300) : []);
43
+ if (v.areas.code)
44
+ s.areas.code = { folders: strings(v.areas.code.folders) };
45
+ if (v.areas.web)
46
+ s.areas.web = { targets: strings(v.areas.web.targets) };
47
+ if (v.areas.host)
48
+ s.areas.host = {};
49
+ if (v.areas.network) {
50
+ const n = v.areas.network;
51
+ s.areas.network = { ranges: strings(n.ranges).slice(0, 16), routed: strings(n.routed).slice(0, 16), exclude: strings(n.exclude).slice(0, 256) };
52
+ }
53
+ if (v.areas.cloud !== undefined) {
54
+ const c = parseCloudScope(v.areas.cloud);
55
+ if ("error" in c)
56
+ return { error: c.error };
57
+ s.areas.cloud = c;
58
+ }
59
+ if (v.people?.answers)
60
+ s.people = { answers: parseAnswers(v.people.answers) };
61
+ const known = new Set(["code", "web", "host", "network", "cloud"]);
62
+ const unknown = Object.keys(v.areas).filter((k) => !known.has(k));
63
+ if (unknown.length)
64
+ return { error: `this version can't check: ${unknown.join(", ")}` };
65
+ return s;
66
+ }
67
+ export function terminalPrompter() {
68
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
69
+ return { ask: (q) => rl.question(q), close: () => rl.close() };
70
+ }
71
+ /** Opens a file with the system's default app. Best effort: a failure leaves the path printed above. */
72
+ export function openFile(path) {
73
+ const [cmd, args] = process.platform === "win32" ? ["explorer.exe", [path]] : process.platform === "darwin" ? ["open", [path]] : ["xdg-open", [path]];
74
+ try {
75
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
76
+ child.on("error", () => { });
77
+ child.unref();
78
+ }
79
+ catch {
80
+ // Nothing to do: the path is already on screen.
81
+ }
82
+ }
83
+ const yes = (a) => /^\s*y(es)?\s*$/i.test(a);
84
+ /** Walks through each area with its card. The answer is no unless the person types yes. */
85
+ export async function askScope(p, cwd, write, netIO = realNetIO) {
86
+ const scope = { version: 1, created: new Date().toISOString().slice(0, 10), areas: {} };
87
+ write("\nI'll go through each area, say what it does, and ask first. Press Enter to skip any of them.\n\n");
88
+ write(cardText(CARDS.code, [cwd]) + "\n");
89
+ if (yes(await p.ask("Scan the code and config in this folder? (y/N) ")))
90
+ scope.areas.code = { folders: ["."] };
91
+ write("\n");
92
+ const raw = await p.ask("Websites and public services: list addresses to check, separated by spaces (e.g. example.com api.example.com:8443 ssh://git.example.com), or press Enter to skip:\n> ");
93
+ const targets = raw.split(/[\s,]+/).filter(Boolean);
94
+ if (targets.length) {
95
+ write("\n" + cardText(CARDS.web, targets) + "\n");
96
+ if (yes(await p.ask("Check these addresses? (y/N) ")))
97
+ scope.areas.web = { targets };
98
+ }
99
+ write("\n");
100
+ const sugg = suggestedRanges(netIO);
101
+ const rawNet = await p.ask(`Network and connected equipment: list your private address ranges${sugg.length ? ` (this computer is on ${sugg.join(", ")})` : " (e.g. 192.168.1.0/24)"}, or press Enter to skip:\n> `);
102
+ const asked = rawNet.split(/[\s,]+/).filter(Boolean);
103
+ if (asked.length) {
104
+ const mine = machineRanges(netIO);
105
+ const ranges = [];
106
+ const routed = [];
107
+ for (const raw of asked) {
108
+ const r = parseRange(raw);
109
+ if ("error" in r || !isPrivateRange(r)) {
110
+ write(` Skipping ${raw}: ${"error" in r ? r.error : "only private address ranges can be checked"}.\n`);
111
+ continue;
112
+ }
113
+ if (mine.some((m) => r.start >= m.start && r.end <= m.end))
114
+ ranges.push(raw);
115
+ else if (yes(await p.ask(` This computer isn't on ${raw}. Is it another part of your own network, reached through your router? (y/N) `)))
116
+ routed.push(raw);
117
+ }
118
+ const all = [...ranges, ...routed];
119
+ if (all.length) {
120
+ write("\n" + cardText(CARDS.network, all) + "\n");
121
+ if (yes(await p.ask("Check these networks? (y/N) ")))
122
+ scope.areas.network = { ranges, routed, exclude: [] };
123
+ }
124
+ }
125
+ write("\n" + cardText(CARDS.host, []) + "\n");
126
+ if (yes(await p.ask("Check this machine? (y/N) ")))
127
+ scope.areas.host = {};
128
+ write("\n");
129
+ const rawCloud = await p.ask("Cloud accounts: which to check (aws, azure, gcp), separated by spaces, using the sign-in already on this machine, or press Enter to skip:\n> ");
130
+ const providers = [...new Set(rawCloud.toLowerCase().split(/[\s,]+/).filter((x) => PROVIDERS.includes(x)))];
131
+ if (providers.length) {
132
+ const names = providers.map((x) => ({ aws: "AWS", azure: "Azure", gcp: "Google Cloud" })[x]);
133
+ write("\n" + cardText(CARDS.cloud, names) + "\n");
134
+ if (yes(await p.ask("Check these cloud accounts? (y/N) ")))
135
+ scope.areas.cloud = Object.fromEntries(providers.map((x) => [x, {}]));
136
+ }
137
+ return scope;
138
+ }
139
+ /** Optional, asked once: lets the anonymized counts be grouped by industry and size. */
140
+ export async function askProfile(p, s, write) {
141
+ write(`\nOptional: your industry and company size help us group the stats. Press Enter to skip.\n Industries: ${INDUSTRIES.join(", ")}\n`);
142
+ const ind = (await p.ask("Industry: ")).trim().toLowerCase();
143
+ if (INDUSTRIES.includes(ind))
144
+ s.industry = ind;
145
+ const size = (await p.ask(`Company size (${SIZES.join(", ")}): `)).trim();
146
+ if (SIZES.includes(size))
147
+ s.size = size;
148
+ s.profileAsked = true;
149
+ }
150
+ export const PEOPLE_FILE = "people.json";
151
+ function loadPeople(outDir) {
152
+ try {
153
+ const v = JSON.parse(readFileSync(join(outDir, PEOPLE_FILE), "utf8"));
154
+ const answers = parseAnswers(v?.answers);
155
+ return Object.keys(answers).length ? { answeredAt: String(v.answeredAt ?? "").slice(0, 10), answers } : null;
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ export async function runMap(o) {
162
+ const write = o.write ?? ((t) => process.stderr.write(t));
163
+ let scope;
164
+ if (o.scopePath) {
165
+ if (!existsSync(o.scopePath)) {
166
+ write(`No scope file at ${o.scopePath}.\n`);
167
+ return { code: 2 };
168
+ }
169
+ const parsed = parseScope(readFileSync(o.scopePath, "utf8"));
170
+ if ("error" in parsed) {
171
+ write(`Can't use ${o.scopePath}: ${parsed.error}.\n`);
172
+ return { code: 2 };
173
+ }
174
+ scope = parsed;
175
+ }
176
+ else if (o.interactive) {
177
+ const p = (o.prompter ?? terminalPrompter)();
178
+ try {
179
+ scope = await askScope(p, o.cwd, write, o.network?.io);
180
+ const before = loadPeople(o.outDir);
181
+ write(`\nPeople and process: ${QUESTIONS.length} short yes/no questions about what no scan can see, like phishing training, backups and who to call in a breach. About 3 minutes. Answers stay on this machine and are never shared.\n`);
182
+ if (yes(await p.ask(`Answer them now?${before ? ` Enter keeps your answers from ${before.answeredAt}.` : ""} (y/N) `))) {
183
+ const answers = await askPeople((q) => p.ask(q), write);
184
+ if (Object.keys(answers).length)
185
+ scope.people = { answers };
186
+ }
187
+ if (o.sharingOn && !o.settings.profileAsked)
188
+ await askProfile(p, o.settings, write);
189
+ if (Object.keys(scope.areas).length && yes(await p.ask(`\nSave these answers to ${SCOPE_FILE} so the next run (or a pipeline) can reuse them? (y/N) `))) {
190
+ scope.ownershipToken = o.settings.ownershipToken;
191
+ // People and process answers stay out of the scope file, which often ends up in a repository.
192
+ writeFileSync(join(o.cwd, SCOPE_FILE), JSON.stringify({ ...scope, people: undefined }, null, 2) + "\n");
193
+ write(`Saved ${SCOPE_FILE}.\n`);
194
+ }
195
+ }
196
+ finally {
197
+ p.close();
198
+ }
199
+ }
200
+ else {
201
+ write(`benthic map asks before each area. Run it in a terminal, or pass --scope ${SCOPE_FILE} for unattended runs.\n`);
202
+ return { code: 2 };
203
+ }
204
+ const areas = Object.keys(scope.areas);
205
+ if (!areas.length && !scope.people) {
206
+ write("Nothing approved, so nothing was checked.\n");
207
+ return { code: 0 };
208
+ }
209
+ mkdirSync(o.outDir, { recursive: true });
210
+ const people = scope.people?.answers && Object.keys(scope.people.answers).length ? { answeredAt: new Date().toISOString().slice(0, 10), answers: scope.people.answers } : loadPeople(o.outDir);
211
+ if (scope.people?.answers && Object.keys(scope.people.answers).length)
212
+ writeFileSync(join(o.outDir, PEOPLE_FILE), JSON.stringify(people, null, 2) + "\n");
213
+ const logPath = join(o.outDir, "activity.log");
214
+ writeFileSync(logPath, "");
215
+ const log = new ActivityLog(logPath);
216
+ const results = [];
217
+ const ignored = {};
218
+ const pqcCounts = {};
219
+ const inventory = [];
220
+ const cloudKeys = [];
221
+ if (scope.areas.code) {
222
+ const res = emptyResult("code");
223
+ for (const folder of scope.areas.code.folders.length ? scope.areas.code.folders : ["."]) {
224
+ const dir = resolve(o.cwd, folder);
225
+ log.record("code", dir, "read source and config files");
226
+ try {
227
+ const walked = walkFolder(dir);
228
+ for (const u of walked.unreadable)
229
+ res.errors.push({ area: "code", target: `${folder}/${u.path}`.replace(/^\.\//, ""), kind: u.reason === "permission denied" ? "permission" : "read", message: `couldn't read (${u.reason})` });
230
+ const { findings, pqc, filesScanned, inventory: inv } = scanFiles(walked.files);
231
+ inventory.push(...inv);
232
+ for (const f of walked.files)
233
+ for (const a of cloudKeyAdvice(f.path, f.content))
234
+ cloudKeys.push({ ...a, target: `${folder}/${a.target}`.replace(/^\.\//, "") });
235
+ const ign = ignoreFileIn(dir, existsSync);
236
+ const { kept, ignored: ig } = applyIgnore(findings, existsSync(ign) ? parseIgnore(readFileSync(ign, "utf8")) : []);
237
+ for (const [k, n] of Object.entries(ig))
238
+ ignored[k] = (ignored[k] ?? 0) + n;
239
+ res.findings.push(...kept.map(fromCodeFinding));
240
+ for (const s of pqc)
241
+ pqcCounts[s.algorithm] = (pqcCounts[s.algorithm] ?? 0) + 1;
242
+ res.checked.push(`${folder} (${filesScanned} files)`);
243
+ }
244
+ catch (e) {
245
+ res.errors.push({ area: "code", target: folder, kind: "read", message: e instanceof Error ? e.message : String(e) });
246
+ }
247
+ }
248
+ results.push(res);
249
+ }
250
+ if (scope.areas.web) {
251
+ const token = scope.ownershipToken ?? o.settings.ownershipToken;
252
+ const res = await runWeb(scope.areas.web.targets, log, { version: o.version, ...o.web, token });
253
+ results.push(res);
254
+ if (res.unproved.length) {
255
+ write("\nSome addresses were skipped because their domain isn't proved yet. To prove one, add this DNS record, then run again:\n");
256
+ for (const d of res.unproved) {
257
+ const r = proofRecord(d, token);
258
+ write(` ${r.name} TXT "${r.value}"\n`);
259
+ }
260
+ write("One record covers the domain and everything under it.\n");
261
+ }
262
+ if (res.dnsFailed.length) {
263
+ write(`\nCouldn't look up the ownership record for ${res.dnsFailed.join(", ")} because DNS didn't answer, so ${res.dnsFailed.length === 1 ? "it was" : "they were"} skipped. Check this machine's DNS settings, then run again.\n`);
264
+ }
265
+ }
266
+ if (scope.areas.network)
267
+ results.push(await runNetwork(scope.areas.network, log, o.network));
268
+ if (scope.areas.host)
269
+ results.push(runHost(log, o.hostIO));
270
+ if (scope.areas.cloud) {
271
+ write("\nReading cloud account settings, read-only. This can take a few minutes.\n");
272
+ const c = await runCloud(scope.areas.cloud, log, o.cloud);
273
+ for (const n of c.notes)
274
+ write(` Checked ${n}\n`);
275
+ results.push(c.result);
276
+ inventory.push(...c.inventory);
277
+ }
278
+ // Known leftovers the person accepted in .benthic-ignore (websites and this machine; code was handled per folder).
279
+ const ignorePath = ignoreFileIn(o.cwd, existsSync);
280
+ const entries = existsSync(ignorePath) ? parseIgnore(readFileSync(ignorePath, "utf8")) : [];
281
+ const accepted = [];
282
+ for (const r of results) {
283
+ if (r.area === "code" || !entries.length)
284
+ continue;
285
+ const a = applyIgnoreTargets(r.findings, entries);
286
+ r.findings = a.kept;
287
+ accepted.push(...a.accepted);
288
+ for (const f of a.accepted)
289
+ ignored[f.ruleId] = (ignored[f.ruleId] ?? 0) + 1;
290
+ }
291
+ const ranked = rank(results.flatMap((r) => r.findings));
292
+ const report = buildMapReport(results, ranked, o.version, new Date(), accepted, { cloudKeys, people: people ? { answeredAt: people.answeredAt, ...scorePeople(people.answers) } : null });
293
+ writeFileSync(join(o.outDir, "map.json"), JSON.stringify(report, null, 2) + "\n");
294
+ writeFileSync(join(o.outDir, "map.html"), mapHtml(report, log.entries));
295
+ writeFileSync(join(o.outDir, "map.cbom.json"), JSON.stringify(buildCbom(ranked.map(toFinding), { repo: "encryption map", toolVersion: o.version }, inventory), null, 2) + "\n");
296
+ writeFileSync(join(o.outDir, "map.sarif.json"), JSON.stringify(buildMapSarif(ranked, o.version), null, 2) + "\n");
297
+ const reportPath = resolve(o.outDir, "map.html");
298
+ process.stdout.write(mapText(report) + `\n\nYour report: ${reportPath}\nOpen it in a browser. For a PDF, choose Print, then Save as PDF.\nAlso wrote map.json, map.cbom.json (CycloneDX inventory), map.sarif.json (SARIF findings) and activity.log. They stay on this machine.\n`);
299
+ if (o.offerOpen ?? (o.interactive && Boolean(process.stdout.isTTY) && !process.env.CI)) {
300
+ const p = (o.prompter ?? terminalPrompter)();
301
+ try {
302
+ if (yes(await p.ask("\nOpen the report now? (y/N) ")))
303
+ (o.opener ?? openFile)(reportPath);
304
+ }
305
+ finally {
306
+ p.close();
307
+ }
308
+ }
309
+ // Counts for the anonymized summary. Targets never leave this function.
310
+ const rules = {};
311
+ const algorithms = {};
312
+ for (const f of ranked) {
313
+ rules[f.ruleId] = (rules[f.ruleId] ?? 0) + 1;
314
+ const a = (algorithms[f.algorithm] ??= { count: 0, quantumVulnerable: 0 });
315
+ a.count++;
316
+ if (f.risk === "quantum-vulnerable")
317
+ a.quantumVulnerable++;
318
+ }
319
+ for (const s of report.strengths)
320
+ pqcCounts[s.algorithm] = (pqcCounts[s.algorithm] ?? 0) + 1;
321
+ // Cloud key custody counts by rule only. People and process answers are never part of the summary.
322
+ for (const a of cloudKeys)
323
+ rules[a.ruleId] = (rules[a.ruleId] ?? 0) + 1;
324
+ const errors = [...new Set(results.flatMap((r) => r.errors.map((e) => e.kind)))];
325
+ const facts = { command: "map", areas, rules, algorithms, quantumSafe: pqcCounts, fixed: {}, ignored, replacements: {}, errors };
326
+ return { code: 0, report, facts, stateKey: `map:${resolve(o.cwd)}`, state: { rules, pqc: pqcCounts } };
327
+ }
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // SARIF 2.1.0 for the security map, so the map's findings can go into security tools that read SARIF.
4
+ // Code findings point at their file and line. Websites, network, equipment and this machine have no
5
+ // file, so they carry the place they were found as a logical location. GitHub code scanning only
6
+ // shows results with a file, so for GitHub upload the code scan's own --format sarif output.
7
+ import { HELP_URI, fingerprints, securitySeverity, worstOf } from "./sarif-common.js";
8
+ const BY_RATING = { high: "error", medium: "warning", low: "note" };
9
+ const BY_RISK = { secret: "error", "weak-now": "error", exposed: "error", "quantum-vulnerable": "warning" };
10
+ function location(f) {
11
+ const m = f.area === "code" ? /^(.*):(\d+)$/.exec(f.target) : null;
12
+ if (m) {
13
+ const line = Number(m[2]);
14
+ return { physicalLocation: { artifactLocation: { uri: m[1], uriBaseId: "%SRCROOT%" }, ...(line > 0 ? { region: { startLine: line } } : {}) } };
15
+ }
16
+ return { logicalLocations: [{ fullyQualifiedName: f.target, kind: "resource" }] };
17
+ }
18
+ /** What to do, in the finding's own steps when a closer look wrote them, else the scanner's fix. */
19
+ const todo = (f) => [f.why, ...(f.steps?.length ? f.steps : [f.fix])].filter(Boolean).join(" ");
20
+ // One rule per kind of check ("net-admin-http"), so a router and a printer with the same problem share a rule.
21
+ // How much each one matters (its risk and rating) is on the result, where it can differ by device.
22
+ export function buildMapSarif(findings, toolVersion) {
23
+ const worst = new Map();
24
+ const risk = new Map();
25
+ for (const f of findings) {
26
+ worst.set(f.ruleId, worstOf(worst.get(f.ruleId), f.severity));
27
+ // A rule is capped as quantum-only when every finding under it is.
28
+ risk.set(f.ruleId, risk.get(f.ruleId) && risk.get(f.ruleId) !== f.risk ? "mixed" : f.risk);
29
+ }
30
+ const rules = new Map();
31
+ for (const f of findings)
32
+ if (!rules.has(f.ruleId))
33
+ rules.set(f.ruleId, {
34
+ id: f.ruleId,
35
+ name: f.algorithm,
36
+ shortDescription: { text: f.algorithm },
37
+ help: { text: f.fix },
38
+ helpUri: HELP_URI,
39
+ properties: { tags: ["security", f.area], "security-severity": securitySeverity(risk.get(f.ruleId), worst.get(f.ruleId)) },
40
+ });
41
+ const ruleIndex = new Map([...rules.keys()].map((id, i) => [id, i]));
42
+ const prints = fingerprints(findings, (f) => `${f.ruleId}|${f.target}`);
43
+ return {
44
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
45
+ version: "2.1.0",
46
+ runs: [
47
+ {
48
+ tool: { driver: { name: "Hard Keel Benthic map", version: toolVersion, informationUri: HELP_URI, rules: [...rules.values()] } },
49
+ results: findings.map((f, i) => ({
50
+ ruleId: f.ruleId,
51
+ ruleIndex: ruleIndex.get(f.ruleId),
52
+ level: f.rating ? BY_RATING[f.rating] : BY_RISK[f.risk] ?? "note",
53
+ message: { text: `${f.title}. ${todo(f)}` },
54
+ locations: [location(f)],
55
+ partialFingerprints: prints[i],
56
+ properties: { area: f.area, risk: f.risk, "security-severity": securitySeverity(f.risk, f.severity), ...(f.rating ? { rating: f.rating } : {}), ...(f.tier ? { tier: f.tier } : {}), internetFacing: f.internetFacing },
57
+ })),
58
+ },
59
+ ],
60
+ };
61
+ }
@@ -0,0 +1,247 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Sign-in setup on a proved website: the signing algorithm of OAuth, OpenID Connect and SAML.
4
+ // Sign-in tokens and assertions are signed with RSA or elliptic curves almost everywhere, and a
5
+ // quantum computer that can forge them can sign in as anyone. This reads the public setup a sign-in
6
+ // client reads, nothing else: one GET for the OpenID Connect discovery document, one for its key set
7
+ // when that's on a proved domain, or one for a SAML metadata URL the person lists. No logins.
8
+ import { X509Certificate } from "node:crypto";
9
+ import { coveringDomain } from "./map-web.js";
10
+ const MAX_BODY = 512 * 1024;
11
+ const TIMEOUT_MS = 8000;
12
+ /** A plain GET: no cookies, no redirects followed, a short timeout, and at most 512 KB read. */
13
+ export function httpGet(version) {
14
+ return async (url) => {
15
+ const ctl = new AbortController();
16
+ const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
17
+ try {
18
+ const res = await fetch(url, { redirect: "manual", signal: ctl.signal, headers: { accept: "application/json, application/samlmetadata+xml, application/xml;q=0.9, */*;q=0.1", "user-agent": `hardkeel-benthic/${version}` } });
19
+ if (res.status !== 200)
20
+ return { status: res.status, body: "" };
21
+ const reader = res.body?.getReader();
22
+ let body = "";
23
+ const dec = new TextDecoder();
24
+ if (reader) {
25
+ for (;;) {
26
+ const { done, value } = await reader.read();
27
+ if (done)
28
+ break;
29
+ body += dec.decode(value, { stream: true });
30
+ if (body.length > MAX_BODY) {
31
+ await reader.cancel();
32
+ return { error: "response too large" };
33
+ }
34
+ }
35
+ }
36
+ return { status: 200, body };
37
+ }
38
+ catch (e) {
39
+ return { error: ctl.signal.aborted ? "timed out" : (e.cause?.code ?? (e instanceof Error ? e.message : String(e))) };
40
+ }
41
+ finally {
42
+ clearTimeout(timer);
43
+ }
44
+ };
45
+ }
46
+ /** What a JOSE "alg" name means here. */
47
+ export function joseAlg(alg) {
48
+ const a = alg.trim();
49
+ if (/^none$/i.test(a))
50
+ return { algorithm: "Unsigned sign-in tokens", unsigned: true };
51
+ if (/^(RS|PS)(256|384|512)$/.test(a))
52
+ return { algorithm: "RSA signature" };
53
+ if (/^ES(256|384|512|256K)$/.test(a))
54
+ return { algorithm: "ECDSA" };
55
+ if (/^(EdDSA|Ed25519|Ed448)$/.test(a))
56
+ return { algorithm: a === "Ed448" ? "Ed448" : "Ed25519" };
57
+ if (/^HS(256|384|512)$/.test(a))
58
+ return { algorithm: "HMAC", symmetric: true };
59
+ if (/^ML-DSA-(44|65|87)$/.test(a))
60
+ return { algorithm: "ML-DSA", quantumSafe: true };
61
+ if (/^SLH-DSA/i.test(a))
62
+ return { algorithm: "SLH-DSA", quantumSafe: true };
63
+ return null;
64
+ }
65
+ const SIG_FIX = "Plan to move sign-in signing to ML-DSA (FIPS 204) once your identity provider and its clients support it, and keep signing keys short-lived so they're easy to rotate.";
66
+ /** Bits in an RSA modulus given as base64url. */
67
+ function rsaBits(n) {
68
+ try {
69
+ const b = Buffer.from(n, "base64url");
70
+ let i = 0;
71
+ while (i < b.length && b[i] === 0)
72
+ i++;
73
+ return (b.length - i) * 8;
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /** Findings from an OpenID Connect or OAuth discovery document and, when given, its key set. */
80
+ export function signinFindings(label, discovery, jwks) {
81
+ const base = { area: "web", target: label, internetFacing: true };
82
+ const findings = [];
83
+ const strengths = [];
84
+ const algs = new Set();
85
+ for (const k of ["id_token_signing_alg_values_supported", "userinfo_signing_alg_values_supported", "request_object_signing_alg_values_supported", "token_endpoint_auth_signing_alg_values_supported", "authorization_signing_alg_values_supported", "introspection_signing_alg_values_supported"]) {
86
+ const v = discovery[k];
87
+ if (Array.isArray(v))
88
+ for (const a of v)
89
+ if (typeof a === "string")
90
+ algs.add(a);
91
+ }
92
+ for (const k of jwks?.keys ?? [])
93
+ if (typeof k.alg === "string")
94
+ algs.add(k.alg);
95
+ const vulnerable = new Map();
96
+ for (const a of algs) {
97
+ const m = joseAlg(a);
98
+ if (!m)
99
+ continue;
100
+ if (m.unsigned) {
101
+ findings.push({ ...base, ruleId: "web-signin-unsigned", title: "Sign-in setup allows unsigned tokens (alg none)", algorithm: m.algorithm, primitive: "signature", risk: "weak-now", severity: "high", fix: "Remove \"none\" from the allowed signing algorithms. Anyone can forge an unsigned token." });
102
+ }
103
+ else if (m.quantumSafe) {
104
+ if (!strengths.some((s) => s.algorithm === m.algorithm))
105
+ strengths.push({ algorithm: m.algorithm, title: `Sign-in tokens can be signed with ${m.algorithm}` });
106
+ }
107
+ else if (!m.symmetric) {
108
+ vulnerable.set(m.algorithm, [...(vulnerable.get(m.algorithm) ?? []), a]);
109
+ }
110
+ }
111
+ for (const [algorithm, names] of vulnerable) {
112
+ findings.push({ ...base, ruleId: "web-signin-signature", title: `Sign-in tokens are signed with ${names.sort().join(", ")}`, algorithm, primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: SIG_FIX });
113
+ }
114
+ for (const k of jwks?.keys ?? []) {
115
+ if (k.kty !== "RSA" || !k.n)
116
+ continue;
117
+ const bits = rsaBits(k.n);
118
+ if (bits && bits < 2048) {
119
+ findings.push({ ...base, ruleId: "web-signin-small-rsa", title: `Sign-in signing key is RSA ${bits}`, algorithm: "RSA signature", primitive: "signature", risk: "weak-now", severity: "high", keySize: bits, fix: "Rotate to a key of at least RSA 2048 (3072 for keys meant to last), then plan the move to ML-DSA." });
120
+ break;
121
+ }
122
+ }
123
+ return { findings, strengths };
124
+ }
125
+ const SAML_SIG = /SignatureMethod\s+Algorithm\s*=\s*["']([^"']+)["']/g;
126
+ const SAML_CERT = /<(?:[A-Za-z0-9_]+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]{100,}?)\s*<\/(?:[A-Za-z0-9_]+:)?X509Certificate>/g;
127
+ /** Findings from SAML metadata: the signing certificates' keys and any signature method it names. */
128
+ export function samlFindings(label, xml) {
129
+ const base = { area: "web", target: label, internetFacing: true };
130
+ const findings = [];
131
+ const strengths = [];
132
+ const keys = new Map();
133
+ for (const m of xml.matchAll(SAML_CERT)) {
134
+ try {
135
+ const c = new X509Certificate(Buffer.from(m[1].replace(/\s+/g, ""), "base64"));
136
+ const k = c.publicKey;
137
+ const type = k.asymmetricKeyType ?? "unknown";
138
+ const bits = k.asymmetricKeyDetails?.modulusLength;
139
+ const had = keys.get(type);
140
+ keys.set(type, bits === undefined ? had : had === undefined ? bits : Math.min(had, bits)); // the weakest key counts
141
+ }
142
+ catch {
143
+ // Not a certificate we can read; leave it out.
144
+ }
145
+ }
146
+ for (const [type, bits] of keys) {
147
+ if (/^ml-dsa/i.test(type)) {
148
+ strengths.push({ algorithm: "ML-DSA", title: "SAML signing certificate uses ML-DSA" });
149
+ continue;
150
+ }
151
+ const algorithm = type === "rsa" || type === "rsa-pss" ? "RSA signature" : type === "ec" ? "ECDSA" : type === "ed25519" ? "Ed25519" : null;
152
+ if (!algorithm)
153
+ continue;
154
+ if (algorithm === "RSA signature" && bits && bits < 2048) {
155
+ findings.push({ ...base, ruleId: "web-saml-small-rsa", title: `SAML signing certificate is RSA ${bits}`, algorithm, primitive: "signature", risk: "weak-now", severity: "high", keySize: bits, fix: "Replace the signing certificate with at least RSA 2048 (3072 for long-lived), then plan the move to ML-DSA." });
156
+ }
157
+ else {
158
+ findings.push({ ...base, ruleId: "web-saml-signature", title: `SAML assertions are signed with ${algorithm === "RSA signature" ? `RSA${bits ? ` ${bits}` : ""}` : algorithm}`, algorithm, primitive: "signature", risk: "quantum-vulnerable", severity: "medium", longLived: true, ...(bits ? { keySize: bits } : {}), fix: SIG_FIX });
159
+ }
160
+ }
161
+ const methods = new Set([...xml.matchAll(SAML_SIG)].map((m) => m[1]));
162
+ if ([...methods].some((u) => /(rsa|dsa|ecdsa)-sha1$/i.test(u))) {
163
+ findings.push({ ...base, ruleId: "web-saml-sha1", title: "SAML metadata is signed with SHA-1", algorithm: "SHA-1", primitive: "hash", risk: "weak-now", severity: "high", fix: "Sign with SHA-256 (rsa-sha256 or ecdsa-sha256)." });
164
+ }
165
+ return { findings, strengths };
166
+ }
167
+ /**
168
+ * The sign-in check for one website. With no path: the OpenID Connect discovery document, if the
169
+ * site has one (most don't, and that's fine). With a path the person listed: that URL, read as
170
+ * OpenID Connect discovery or SAML metadata, whichever it is.
171
+ */
172
+ export async function checkSignin(t, paths, proved, log, res, get) {
173
+ const origin = `https://${t.host}${t.port === 443 ? "" : `:${t.port}`}`;
174
+ const asked = paths.length > 0;
175
+ for (const path of asked ? paths : ["/.well-known/openid-configuration"]) {
176
+ const url = origin + path;
177
+ log.record("web", t.label, `HTTPS GET ${path} (public sign-in setup)`);
178
+ const r = await get(url);
179
+ if ("error" in r) {
180
+ if (asked)
181
+ res.errors.push({ area: "web", target: `${t.label}${path}`, kind: /timed out/.test(r.error) ? "timeout" : "other", message: `couldn't read the sign-in setup: ${r.error}` });
182
+ continue;
183
+ }
184
+ if (r.status !== 200) {
185
+ if (asked)
186
+ res.skipped.push({ target: `${t.label}${path}`, reason: `sign-in setup not found (HTTP ${r.status})` });
187
+ continue;
188
+ }
189
+ const body = r.body.trim();
190
+ let out = null;
191
+ if (body.startsWith("{")) {
192
+ let doc;
193
+ try {
194
+ doc = JSON.parse(body);
195
+ }
196
+ catch {
197
+ if (asked)
198
+ res.skipped.push({ target: `${t.label}${path}`, reason: "not a sign-in setup document" });
199
+ continue;
200
+ }
201
+ if (typeof doc.issuer !== "string") {
202
+ if (asked)
203
+ res.skipped.push({ target: `${t.label}${path}`, reason: "not a sign-in setup document" });
204
+ continue;
205
+ }
206
+ let jwks;
207
+ const ju = typeof doc.jwks_uri === "string" ? doc.jwks_uri : null;
208
+ if (ju) {
209
+ let host = null;
210
+ try {
211
+ const u = new URL(ju);
212
+ host = u.protocol === "https:" ? u.hostname.toLowerCase() : null;
213
+ }
214
+ catch {
215
+ host = null;
216
+ }
217
+ if (host && coveringDomain(host, proved)) {
218
+ log.record("web", t.label, `HTTPS GET ${new URL(ju).pathname} (public sign-in keys)`);
219
+ const k = await get(ju);
220
+ if (!("error" in k) && k.status === 200) {
221
+ try {
222
+ jwks = JSON.parse(k.body);
223
+ }
224
+ catch {
225
+ jwks = undefined;
226
+ }
227
+ }
228
+ }
229
+ else if (host) {
230
+ res.skipped.push({ target: t.label, reason: `sign-in keys are on ${host}, which isn't a proved domain, so they weren't read. The listed algorithms were still checked.` });
231
+ }
232
+ }
233
+ out = signinFindings(`${t.label} (sign-in)`, doc, jwks);
234
+ }
235
+ else if (/<(?:[A-Za-z0-9_]+:)?EntityDescriptor\b|<(?:[A-Za-z0-9_]+:)?EntitiesDescriptor\b/.test(body)) {
236
+ out = samlFindings(`${t.label}${path} (SAML)`, body);
237
+ }
238
+ else if (asked) {
239
+ res.skipped.push({ target: `${t.label}${path}`, reason: "not OpenID Connect discovery or SAML metadata" });
240
+ }
241
+ if (out) {
242
+ res.findings.push(...out.findings);
243
+ for (const s of out.strengths)
244
+ res.strengths.push({ area: "web", target: t.label, ...s });
245
+ }
246
+ }
247
+ }
@@ -0,0 +1,19 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Types for the encryption map: one picture of encryption across code, websites and machines.
4
+ export const TIER_TITLES = {
5
+ 1: "Broken now",
6
+ 2: "Recorded now, read later",
7
+ 3: "Long-lived signatures",
8
+ 4: "Everything else",
9
+ };
10
+ export const TIER_NOTES = {
11
+ 1: "Weak today, without any quantum computer. Fix these first.",
12
+ 2: "Internet-facing key exchange with no quantum-safe option. Traffic recorded today can be decrypted once quantum computers arrive.",
13
+ 3: "Signatures that must stay trusted for years. NIST deprecates these methods after 2030.",
14
+ 4: "Uses RSA or elliptic-curve encryption. NIST disallows these after 2035.",
15
+ };
16
+ export const RATING_TITLES = { high: "High", medium: "Medium", low: "Low" };
17
+ export function emptyResult(area) {
18
+ return { area, findings: [], strengths: [], errors: [], checked: [], skipped: [] };
19
+ }