@hardkeel/quantum-scan 0.0.0-stage → 0.2.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.
@@ -0,0 +1,640 @@
1
+ // Websites and public services: proof of ownership, then look-only checks.
2
+ // Every check is a normal connection: the TLS handshake a browser makes, or the settings an SSH
3
+ // server announces before any login. No logins, no vulnerability tests, no attack traffic.
4
+ import { promises as dns } from "node:dns";
5
+ import { isIP, connect as netConnect } from "node:net";
6
+ import { connect as tlsConnect } from "node:tls";
7
+ import { randomBytes } from "node:crypto";
8
+ import { ALGORITHMS } from "./rules.js";
9
+ import { emptyResult } from "./map-types.js";
10
+ const HOSTNAME = /^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/;
11
+ /** "example.com", "api.example.com:8443", "git.example.com:22", "ssh://git.example.com". IP addresses are refused. */
12
+ export function parseTarget(raw) {
13
+ let s = raw.trim().toLowerCase();
14
+ let kind = null;
15
+ const scheme = s.match(/^([a-z]+):\/\//);
16
+ if (scheme) {
17
+ if (scheme[1] === "ssh")
18
+ kind = "ssh";
19
+ else if (scheme[1] !== "https")
20
+ return { error: `${raw}: use a hostname, https:// or ssh://` };
21
+ s = s.slice(scheme[0].length);
22
+ }
23
+ s = s.replace(/\/.*$/, "");
24
+ let port = kind === "ssh" ? 22 : 443;
25
+ const pm = s.match(/^(.*):(\d{1,5})$/);
26
+ if (pm) {
27
+ s = pm[1];
28
+ port = Number(pm[2]);
29
+ }
30
+ if (isIP(s) || /^\[.*\]$/.test(s))
31
+ return { error: `${raw}: use a hostname under a domain you proved, not an IP address` };
32
+ if (!HOSTNAME.test(s))
33
+ return { error: `${raw}: not a hostname` };
34
+ if (port < 1 || port > 65535)
35
+ return { error: `${raw}: bad port` };
36
+ kind ??= port === 22 ? "ssh" : "tls";
37
+ return { host: s, port, kind, label: `${s}:${port}` };
38
+ }
39
+ export const PROOF_PREFIX = "_hardkeel-scan";
40
+ export function proofRecord(domain, token) {
41
+ return { name: `${PROOF_PREFIX}.${domain}`, value: `hardkeel-scan-verify=${token}` };
42
+ }
43
+ /** The proved domain that covers a host: the host itself or any parent of it. */
44
+ export function coveringDomain(host, proved) {
45
+ for (const d of proved)
46
+ if (host === d || host.endsWith(`.${d}`))
47
+ return d;
48
+ return null;
49
+ }
50
+ /** Candidate domains to look for proof on, nearest first: api.eu.example.com -> api.eu.example.com, eu.example.com, example.com. */
51
+ export function parentDomains(host) {
52
+ const parts = host.split(".");
53
+ const out = [];
54
+ for (let i = 0; i <= parts.length - 2; i++)
55
+ out.push(parts.slice(i).join("."));
56
+ return out;
57
+ }
58
+ /** Public resolvers tried only when this machine's own DNS doesn't answer (for example a local stub that is down). */
59
+ export const PUBLIC_RESOLVERS = ["1.1.1.1", "8.8.8.8"];
60
+ export function publicLookup(servers = PUBLIC_RESOLVERS) {
61
+ return (name) => {
62
+ const r = new dns.Resolver({ timeout: 3000, tries: 2 });
63
+ r.setServers(servers);
64
+ return r.resolveTxt(name);
65
+ };
66
+ }
67
+ /** DNS answered, and the name has no such record. Anything else means DNS itself didn't answer. */
68
+ const DNS_NO_RECORD = new Set(["ENOTFOUND", "ENODATA", "ENONAME"]);
69
+ /**
70
+ * Checks the DNS record that proves a domain is yours. Uses this machine's DNS first. If that DNS
71
+ * doesn't answer at all, asks a public resolver for this one record, and says so in the activity log.
72
+ */
73
+ export async function checkProof(domain, token, log, lookup = (n) => dns.resolveTxt(n), fallback) {
74
+ const { name, value } = proofRecord(domain, token);
75
+ const match = (records) => records.some((chunks) => chunks.join("").trim() === value);
76
+ log.record("web", name, "DNS lookup of the ownership record");
77
+ let firstError;
78
+ try {
79
+ return { status: match(await lookup(name)) ? "found" : "missing" };
80
+ }
81
+ catch (e) {
82
+ const code = String(e?.code ?? "");
83
+ if (DNS_NO_RECORD.has(code))
84
+ return { status: "missing" };
85
+ firstError = code || (e instanceof Error ? e.message : String(e));
86
+ }
87
+ if (!fallback)
88
+ return { status: "lookup-failed", detail: `this machine's DNS didn't answer (${firstError})` };
89
+ log.record("web", name, `DNS lookup of the ownership record via a public resolver, because this machine's DNS didn't answer (${firstError})`);
90
+ try {
91
+ return { status: match(await fallback(name)) ? "found" : "missing" };
92
+ }
93
+ catch (e) {
94
+ const code = String(e?.code ?? "");
95
+ if (DNS_NO_RECORD.has(code))
96
+ return { status: "missing" };
97
+ return { status: "lookup-failed", detail: `this machine's DNS didn't answer (${firstError}), and neither did a public resolver (${code || "error"})` };
98
+ }
99
+ }
100
+ /** Whether a domain is proved. Kept for callers that only need yes or no. */
101
+ export async function hasProof(domain, token, log, lookup, fallback) {
102
+ return (await checkProof(domain, token, log, lookup, fallback)).status === "found";
103
+ }
104
+ const TIMEOUT_MS = 8000;
105
+ export function errorKind(e) {
106
+ const code = String(e?.code ?? "");
107
+ if (code === "ETIMEDOUT" || code === "TIMEOUT")
108
+ return "timeout";
109
+ if (code === "ECONNREFUSED" || code === "ECONNRESET")
110
+ return "refused";
111
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN")
112
+ return "dns";
113
+ if (code.startsWith("ERR_SSL") || code.startsWith("ERR_TLS") || /SSL|TLS/i.test(code))
114
+ return "tls";
115
+ return "other";
116
+ }
117
+ export function handshake(host, port, opts) {
118
+ return new Promise((resolveP) => {
119
+ let done = false;
120
+ const finish = (h, s) => {
121
+ if (done)
122
+ return;
123
+ done = true;
124
+ s?.destroy();
125
+ resolveP(h);
126
+ };
127
+ let sock;
128
+ try {
129
+ sock = tlsConnect({ host, port, servername: isIP(host) ? undefined : host, rejectUnauthorized: false, ...opts }, () => {
130
+ let cert;
131
+ try {
132
+ cert = sock.getPeerX509Certificate() ?? undefined;
133
+ }
134
+ catch {
135
+ cert = undefined;
136
+ }
137
+ const eph = sock.getEphemeralKeyInfo();
138
+ finish({
139
+ ok: true,
140
+ protocol: sock.getProtocol(),
141
+ cipher: sock.getCipher()?.name,
142
+ keyExchange: eph && "name" in eph ? eph.name : undefined,
143
+ cert,
144
+ authorized: sock.authorized,
145
+ authError: sock.authorizationError ? String(sock.authorizationError) : undefined,
146
+ }, sock);
147
+ });
148
+ }
149
+ catch (e) {
150
+ finish({ ok: false, error: errorKind(e), message: e instanceof Error ? e.message : String(e) });
151
+ return;
152
+ }
153
+ sock.setTimeout(TIMEOUT_MS, () => finish({ ok: false, error: "timeout", message: "timed out" }, sock));
154
+ sock.on("error", (e) => finish({ ok: false, error: errorKind(e), message: e.message }, sock));
155
+ });
156
+ }
157
+ /** Whether this Node.js can offer the hybrid X25519 + ML-KEM-768 key exchange (OpenSSL 3.5 or later). */
158
+ export function canTestHybrid(openssl = process.versions.openssl ?? "") {
159
+ const m = openssl.match(/^(\d+)\.(\d+)/);
160
+ return Boolean(m && (Number(m[1]) > 3 || (Number(m[1]) === 3 && Number(m[2]) >= 5)));
161
+ }
162
+ // Signature algorithm OIDs a certificate can be signed with.
163
+ const SIG_OIDS = {
164
+ "1.2.840.113549.1.1.4": { name: "RSA with MD5", weak: true },
165
+ "1.2.840.113549.1.1.5": { name: "RSA with SHA-1", weak: true },
166
+ "1.2.840.113549.1.1.11": { name: "RSA with SHA-256" },
167
+ "1.2.840.113549.1.1.12": { name: "RSA with SHA-384" },
168
+ "1.2.840.113549.1.1.13": { name: "RSA with SHA-512" },
169
+ "1.2.840.113549.1.1.10": { name: "RSA-PSS" },
170
+ "1.2.840.10045.4.1": { name: "ECDSA with SHA-1", weak: true },
171
+ "1.2.840.10045.4.3.2": { name: "ECDSA with SHA-256" },
172
+ "1.2.840.10045.4.3.3": { name: "ECDSA with SHA-384" },
173
+ "1.2.840.10045.4.3.4": { name: "ECDSA with SHA-512" },
174
+ "1.3.101.112": { name: "Ed25519" },
175
+ "1.3.101.113": { name: "Ed448" },
176
+ "2.16.840.1.101.3.4.3.17": { name: "ML-DSA-44", pqc: true },
177
+ "2.16.840.1.101.3.4.3.18": { name: "ML-DSA-65", pqc: true },
178
+ "2.16.840.1.101.3.4.3.19": { name: "ML-DSA-87", pqc: true },
179
+ };
180
+ function readLen(b, i) {
181
+ const first = b[i];
182
+ if (first < 0x80)
183
+ return [first, i + 1];
184
+ const n = first & 0x7f;
185
+ let len = 0;
186
+ for (let k = 0; k < n; k++)
187
+ len = len * 256 + b[i + 1 + k];
188
+ return [len, i + 1 + n];
189
+ }
190
+ function oidString(b) {
191
+ const parts = [Math.floor(b[0] / 40), b[0] % 40];
192
+ let v = 0;
193
+ for (let i = 1; i < b.length; i++) {
194
+ v = v * 128 + (b[i] & 0x7f);
195
+ if (!(b[i] & 0x80)) {
196
+ parts.push(v);
197
+ v = 0;
198
+ }
199
+ }
200
+ return parts.join(".");
201
+ }
202
+ /** The OID of the algorithm a DER certificate is signed with: Certificate ::= SEQUENCE { tbs, signatureAlgorithm, signature }. */
203
+ export function certSignatureOid(der) {
204
+ try {
205
+ if (der[0] !== 0x30)
206
+ return null;
207
+ let [, i] = readLen(der, 1); // into Certificate
208
+ if (der[i] !== 0x30)
209
+ return null;
210
+ const [tbsLen, tbsStart] = readLen(der, i + 1);
211
+ i = tbsStart + tbsLen; // skip tbsCertificate
212
+ if (der[i] !== 0x30)
213
+ return null;
214
+ [, i] = readLen(der, i + 1); // into AlgorithmIdentifier
215
+ if (der[i] !== 0x06)
216
+ return null;
217
+ const [oidLen, oidStart] = readLen(der, i + 1);
218
+ return oidString(der.subarray(oidStart, oidStart + oidLen));
219
+ }
220
+ catch {
221
+ return null;
222
+ }
223
+ }
224
+ export function certSignature(der) {
225
+ const oid = certSignatureOid(der);
226
+ return oid ? (SIG_OIDS[oid] ?? { name: `other (${oid})` }) : null;
227
+ }
228
+ export function certKey(cert) {
229
+ try {
230
+ const k = cert.publicKey;
231
+ const t = k.asymmetricKeyType ?? "";
232
+ const d = (k.asymmetricKeyDetails ?? {});
233
+ if (t === "rsa" || t === "rsa-pss")
234
+ return { type: "RSA", bits: d.modulusLength };
235
+ if (t === "ec")
236
+ return { type: "ECDSA", curve: d.namedCurve };
237
+ if (t === "ed25519")
238
+ return { type: "Ed25519" };
239
+ if (t === "ed448")
240
+ return { type: "Ed448" };
241
+ if (t.startsWith("ml-dsa"))
242
+ return { type: "ML-DSA" };
243
+ return { type: "other" };
244
+ }
245
+ catch {
246
+ return { type: "other" };
247
+ }
248
+ }
249
+ /** Turns a certificate into findings: expiry, weak signing, small keys, and its quantum status. */
250
+ export function certFindings(cert, host, label, authorized, authError, now = Date.now()) {
251
+ const out = [];
252
+ const base = { area: "web", target: label, internetFacing: true };
253
+ const sig = certSignature(Buffer.from(cert.raw));
254
+ const key = certKey(cert);
255
+ if (Date.parse(cert.validTo) < now) {
256
+ out.push({ ...base, ruleId: "web-cert-expired", title: "Certificate has expired", algorithm: "Expired certificate", primitive: "protocol", risk: "weak-now", severity: "high", fix: "Renew the certificate. Browsers and clients refuse expired ones." });
257
+ }
258
+ if (!cert.checkHost(host)) {
259
+ out.push({ ...base, ruleId: "web-cert-name", title: "Certificate doesn't match this hostname", algorithm: "Certificate name mismatch", primitive: "protocol", risk: "exposed", severity: "medium", fix: "Use a certificate that names this hostname." });
260
+ }
261
+ else if (authorized === false && authError && !/CERT_HAS_EXPIRED/i.test(authError)) {
262
+ const self = /SELF_SIGNED|self.signed/i.test(authError);
263
+ out.push({
264
+ ...base,
265
+ ruleId: self ? "web-cert-self-signed" : "web-cert-untrusted",
266
+ title: self ? "Certificate is self-signed" : "Certificate isn't trusted by standard clients",
267
+ algorithm: self ? "Self-signed certificate" : "Untrusted certificate",
268
+ primitive: "protocol",
269
+ risk: "exposed",
270
+ severity: "medium",
271
+ fix: "Use a certificate from a public certificate authority, or serve the full chain.",
272
+ });
273
+ }
274
+ if (sig?.weak) {
275
+ out.push({ ...base, ruleId: "web-cert-weak-signature", title: `Certificate signed with ${sig.name}`, algorithm: /MD5/.test(sig.name) ? "MD5" : "SHA-1", primitive: "hash", risk: "weak-now", severity: "high", fix: "Reissue the certificate signed with SHA-256 or stronger." });
276
+ }
277
+ if (key.type === "RSA" && key.bits && key.bits < 2048) {
278
+ out.push({ ...base, ruleId: "web-cert-small-rsa", title: `Certificate uses a ${key.bits}-bit RSA key`, algorithm: "RSA", primitive: "signature", risk: "weak-now", severity: "high", keySize: key.bits, fix: "Reissue with at least a 2048-bit RSA key, or ECDSA P-256." });
279
+ }
280
+ else if (key.type === "RSA" || key.type === "ECDSA" || key.type === "Ed25519" || key.type === "Ed448") {
281
+ const alg = key.type === "RSA" ? "RSA signature" : key.type;
282
+ out.push({
283
+ ...base,
284
+ ruleId: "web-cert-quantum",
285
+ title: `Certificate uses ${key.type === "RSA" ? `${key.bits ?? ""}-bit RSA`.trim() : key.type}${sig ? `, signed with ${sig.name}` : ""}`,
286
+ algorithm: alg,
287
+ primitive: "signature",
288
+ risk: "quantum-vulnerable",
289
+ severity: "medium",
290
+ keySize: key.bits,
291
+ fix: "Plan to move to ML-DSA certificates once your certificate authority offers them. Short-lived certificates make the switch easy.",
292
+ });
293
+ }
294
+ return { findings: out, pqc: key.type === "ML-DSA" || Boolean(sig?.pqc) };
295
+ }
296
+ // ---------- raw cipher suite probe ----------
297
+ // Recent OpenSSL builds (Node.js 22 and later) can't offer 3DES at all, so a normal handshake can't test it.
298
+ // This sends one ordinary TLS 1.2 ClientHello listing only the given cipher suites, reads the server's
299
+ // answer (ServerHello or an alert) and hangs up. No keys are exchanged.
300
+ export const SUITES_3DES = [0x000a, 0xc012, 0xc008, 0x0016, 0x0013];
301
+ function u16(n) {
302
+ const b = Buffer.alloc(2);
303
+ b.writeUInt16BE(n);
304
+ return b;
305
+ }
306
+ const vec16 = (b) => Buffer.concat([u16(b.length), b]);
307
+ const ext = (type, body) => Buffer.concat([u16(type), vec16(body)]);
308
+ export function clientHello(host, suites) {
309
+ const name = Buffer.from(host, "ascii");
310
+ const sni = vec16(Buffer.concat([Buffer.from([0]), vec16(name)]));
311
+ const exts = Buffer.concat([
312
+ isIP(host) ? Buffer.alloc(0) : ext(0x0000, sni),
313
+ ext(0x000a, vec16(Buffer.concat([0x001d, 0x0017, 0x0018].map(u16)))), // groups: x25519, P-256, P-384
314
+ ext(0x000b, Buffer.from([1, 0])), // uncompressed points
315
+ ext(0x000d, vec16(Buffer.concat([0x0401, 0x0501, 0x0201, 0x0403, 0x0503, 0x0203, 0x0804].map(u16)))),
316
+ ext(0xff01, Buffer.from([0])), // renegotiation info
317
+ ]);
318
+ const body = Buffer.concat([
319
+ Buffer.from([0x03, 0x03]), // TLS 1.2
320
+ randomBytes(32),
321
+ Buffer.from([0]), // no session id
322
+ vec16(Buffer.concat(suites.map(u16))),
323
+ Buffer.from([1, 0]), // no compression
324
+ vec16(exts),
325
+ ]);
326
+ const hs = Buffer.concat([Buffer.from([1, (body.length >> 16) & 255, (body.length >> 8) & 255, body.length & 255]), body]);
327
+ return Buffer.concat([Buffer.from([0x16, 0x03, 0x01]), vec16(hs)]);
328
+ }
329
+ /** The cipher suite a ServerHello picked, null for an alert, undefined while more bytes are needed. */
330
+ export function serverHelloSuite(buf) {
331
+ if (buf.length < 5)
332
+ return undefined;
333
+ if (buf[0] === 0x15)
334
+ return null; // alert: the server refused every suite offered
335
+ if (buf[0] !== 0x16)
336
+ return null;
337
+ if (buf.length < 5 + 4 + 2 + 32 + 1)
338
+ return undefined;
339
+ if (buf[5] !== 0x02)
340
+ return null;
341
+ const sidLen = buf[5 + 4 + 2 + 32];
342
+ const at = 5 + 4 + 2 + 32 + 1 + sidLen;
343
+ if (buf.length < at + 2)
344
+ return undefined;
345
+ return buf.readUInt16BE(at);
346
+ }
347
+ /** Whether the server accepts one of these TLS 1.2 cipher suites. */
348
+ export const acceptsSuites = (host, port, suites, servername) => new Promise((resolveP) => {
349
+ let buf = Buffer.alloc(0);
350
+ let done = false;
351
+ const sock = netConnect({ host, port });
352
+ const finish = (v) => {
353
+ if (done)
354
+ return;
355
+ done = true;
356
+ sock.destroy();
357
+ resolveP(v);
358
+ };
359
+ sock.setTimeout(TIMEOUT_MS, () => finish(false));
360
+ sock.on("error", () => finish(false));
361
+ sock.on("close", () => finish(false));
362
+ sock.on("connect", () => sock.write(clientHello(servername ?? host, suites)));
363
+ sock.on("data", (d) => {
364
+ buf = Buffer.concat([buf, d]);
365
+ const suite = serverHelloSuite(buf);
366
+ if (suite === undefined && buf.length < 16384)
367
+ return;
368
+ finish(typeof suite === "number" && suites.includes(suite));
369
+ });
370
+ });
371
+ const GAP_MS = 250;
372
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
373
+ /** About 6 handshakes, one at a time: normal, hybrid ML-KEM, TLS 1.0, TLS 1.1, 3DES, static RSA key exchange. */
374
+ export async function checkTls(t, log, res, hs = handshake, gap = GAP_MS, probe = acceptsSuites) {
375
+ log.record("web", t.label, "TLS handshake, normal settings");
376
+ const main = await hs(t.host, t.port, { minVersion: "TLSv1.2" });
377
+ if (!main.ok) {
378
+ // Can't reach it at all: don't try again.
379
+ if (main.error === "dns" || main.error === "refused" || main.error === "timeout") {
380
+ res.errors.push({ area: "web", target: t.label, kind: main.error, message: main.message ?? "couldn't connect" });
381
+ return;
382
+ }
383
+ // Maybe it only speaks old TLS: try once more allowing it before giving up.
384
+ await sleep(gap);
385
+ log.record("web", t.label, "TLS handshake allowing TLS 1.0");
386
+ const old = await hs(t.host, t.port, { minVersion: "TLSv1", ciphers: "DEFAULT:@SECLEVEL=0" });
387
+ if (!old.ok) {
388
+ res.errors.push({ area: "web", target: t.label, kind: main.error ?? "other", message: main.message ?? "couldn't connect" });
389
+ return;
390
+ }
391
+ Object.assign(main, old);
392
+ }
393
+ res.checked.push(t.label);
394
+ const base = { area: "web", target: t.label, internetFacing: true };
395
+ // Key exchange: does it offer the quantum-safe hybrid?
396
+ let hybrid = null;
397
+ if (main.protocol === "TLSv1.3" && canTestHybrid()) {
398
+ await sleep(gap);
399
+ log.record("web", t.label, "TLS handshake offering only hybrid X25519 + ML-KEM-768");
400
+ const h = await hs(t.host, t.port, { minVersion: "TLSv1.3", ecdhCurve: "X25519MLKEM768" });
401
+ hybrid = h.ok;
402
+ }
403
+ if (hybrid) {
404
+ res.strengths.push({ area: "web", target: t.label, algorithm: "Hybrid ML-KEM key exchange", title: "Offers quantum-safe hybrid key exchange (X25519 + ML-KEM-768)" });
405
+ }
406
+ else {
407
+ const kx = main.keyExchange ?? "ECDH";
408
+ res.findings.push({
409
+ ...base,
410
+ ruleId: "web-tls-kex",
411
+ title: `Key exchange uses ${kx}${hybrid === null ? "" : " with no quantum-safe option"}${main.protocol !== "TLSv1.3" ? `, over ${main.protocol ?? "an old TLS version"}` : ""}`,
412
+ algorithm: "TLS key exchange",
413
+ primitive: "key-agreement",
414
+ risk: "quantum-vulnerable",
415
+ severity: "high",
416
+ fix: main.protocol === "TLSv1.3"
417
+ ? "Turn on hybrid X25519MLKEM768 key exchange. Recent OpenSSL (3.5+), BoringSSL, nginx, Caddy and most CDNs support it."
418
+ : "Move to TLS 1.3 first, then turn on hybrid X25519MLKEM768 key exchange.",
419
+ });
420
+ if (hybrid === null && main.protocol === "TLSv1.3")
421
+ res.skipped.push({ target: t.label, reason: "this Node.js can't test hybrid ML-KEM key exchange (needs OpenSSL 3.5 or later)" });
422
+ }
423
+ if (main.cert) {
424
+ const c = certFindings(main.cert, t.host, t.label, main.authorized, main.authError);
425
+ res.findings.push(...c.findings);
426
+ if (c.pqc)
427
+ res.strengths.push({ area: "web", target: t.label, algorithm: "ML-DSA", title: "Certificate uses ML-DSA" });
428
+ }
429
+ // Old TLS versions.
430
+ const old = [];
431
+ for (const v of ["TLSv1", "TLSv1.1"]) {
432
+ await sleep(gap);
433
+ log.record("web", t.label, `TLS handshake allowing only ${v === "TLSv1" ? "TLS 1.0" : "TLS 1.1"}`);
434
+ const r = await hs(t.host, t.port, { minVersion: v, maxVersion: v, ciphers: "DEFAULT:@SECLEVEL=0" });
435
+ if (r.ok)
436
+ old.push(v === "TLSv1" ? "TLS 1.0" : "TLS 1.1");
437
+ }
438
+ if (old.length) {
439
+ const a = ALGORITHMS["TLS 1.0/1.1"];
440
+ res.findings.push({ ...base, ruleId: "web-tls-old", title: `Accepts ${old.join(" and ")}`, algorithm: "TLS 1.0/1.1", primitive: a.primitive, risk: a.risk, severity: a.severity, fix: a.fix });
441
+ }
442
+ // Weak TLS 1.2 cipher suites.
443
+ await sleep(gap);
444
+ log.record("web", t.label, "TLS 1.2 hello offering only 3DES cipher suites (reads the server's answer, then disconnects)");
445
+ if (await probe(t.host, t.port, SUITES_3DES))
446
+ res.findings.push({ ...base, ruleId: "web-tls-3des", title: "Accepts 3DES cipher suites", algorithm: "3DES", primitive: "block-cipher", risk: "weak-now", severity: "high", fix: ALGORITHMS["Weak TLS ciphers"].fix });
447
+ await sleep(gap);
448
+ log.record("web", t.label, "TLS 1.2 handshake offering only static RSA key exchange");
449
+ const rsa = await hs(t.host, t.port, { minVersion: "TLSv1", maxVersion: "TLSv1.2", ciphers: "AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:@SECLEVEL=0" });
450
+ if (rsa.ok) {
451
+ // With TLS 1.3 on offer, current browsers and clients never pick static RSA (TLS 1.3 also blocks
452
+ // downgrades), so only old clients are exposed. Still worth fixing, but not an emergency.
453
+ const modern = main.protocol === "TLSv1.3";
454
+ res.findings.push({
455
+ ...base,
456
+ ruleId: "web-tls-static-rsa",
457
+ title: modern ? "Still accepts static RSA key exchange from old clients (no forward secrecy for them)" : "Accepts static RSA key exchange (no forward secrecy)",
458
+ algorithm: "Static RSA key exchange",
459
+ primitive: "key-agreement",
460
+ risk: modern ? "exposed" : "weak-now",
461
+ severity: modern ? "low" : "medium",
462
+ fix: modern
463
+ ? "Allow only ECDHE cipher suites for TLS 1.2. Some hosts charge for this (on Cloudflare, custom cipher suites need Advanced Certificate Manager). If you can't change it now, accept it as a known leftover in .quantum-scan-ignore."
464
+ : "Allow only ECDHE cipher suites. With static RSA, anyone who later gets the key can read every recorded session.",
465
+ });
466
+ }
467
+ }
468
+ function nameList(buf, off) {
469
+ const len = buf.readUInt32BE(off);
470
+ const s = buf.subarray(off + 4, off + 4 + len).toString("latin1");
471
+ return [s ? s.split(",") : [], off + 4 + len];
472
+ }
473
+ /** Parses the server's SSH_MSG_KEXINIT packet (RFC 4253, section 7.1). */
474
+ export function parseKexInit(packet) {
475
+ try {
476
+ const len = packet.readUInt32BE(0);
477
+ const pad = packet[4];
478
+ const payload = packet.subarray(5, 4 + len - pad);
479
+ if (payload[0] !== 20)
480
+ return null;
481
+ let off = 17; // message byte + 16-byte cookie
482
+ const lists = [];
483
+ for (let i = 0; i < 6; i++) {
484
+ const [l, next] = nameList(payload, off);
485
+ lists.push(l);
486
+ off = next;
487
+ }
488
+ return { kex: lists[0], hostKeys: lists[1], ciphers: lists[2], macs: lists[4] };
489
+ }
490
+ catch {
491
+ return null;
492
+ }
493
+ }
494
+ export const CLIENT_BANNER = "SSH-2.0-HardKeelQuantumScan_1.0";
495
+ /** Reads the server's banner and the settings it announces, then hangs up. No keys are exchanged and no login is tried. */
496
+ export function sshKexInit(host, port) {
497
+ return new Promise((resolveP) => {
498
+ let buf = Buffer.alloc(0);
499
+ let banner = null;
500
+ let done = false;
501
+ const sock = netConnect({ host, port });
502
+ const finish = (v) => {
503
+ if (done)
504
+ return;
505
+ done = true;
506
+ sock.destroy();
507
+ resolveP(v);
508
+ };
509
+ sock.setTimeout(TIMEOUT_MS, () => finish({ error: "timeout", message: "timed out" }));
510
+ sock.on("error", (e) => finish({ error: errorKind(e), message: e.message }));
511
+ sock.on("connect", () => sock.write(`${CLIENT_BANNER}\r\n`));
512
+ sock.on("data", (d) => {
513
+ buf = Buffer.concat([buf, d]);
514
+ if (buf.length > 65536)
515
+ return finish({ error: "ssh", message: "server sent too much data" });
516
+ while (banner === null) {
517
+ const nl = buf.indexOf(0x0a);
518
+ if (nl < 0)
519
+ return;
520
+ const line = buf.subarray(0, nl).toString("latin1").replace(/\r$/, "");
521
+ buf = buf.subarray(nl + 1);
522
+ if (line.startsWith("SSH-"))
523
+ banner = line;
524
+ else if (buf.length === 0)
525
+ return;
526
+ }
527
+ if (buf.length < 5)
528
+ return;
529
+ const len = buf.readUInt32BE(0);
530
+ if (len > 35000)
531
+ return finish({ error: "ssh", message: "unexpected packet" });
532
+ if (buf.length < 4 + len)
533
+ return;
534
+ const k = parseKexInit(buf.subarray(0, 4 + len));
535
+ finish(k ? { banner, ...k } : { error: "ssh", message: "couldn't read the server's settings" });
536
+ });
537
+ });
538
+ }
539
+ const SSH_PQC_KEX = /^(mlkem768x25519-sha256|sntrup761x25519-sha512(@openssh\.com)?|mlkem768nistp256-sha256|mlkem1024nistp384-sha384)$/;
540
+ const SSH_WEAK_KEX = /^(diffie-hellman-group1-sha1|diffie-hellman-group14-sha1|diffie-hellman-group-exchange-sha1)$/;
541
+ const SSH_WEAK_CIPHER = /(^3des|^arcfour|^blowfish|^cast128|-cbc$|^des)/;
542
+ const SSH_WEAK_MAC = /^(hmac-md5|hmac-sha1|hmac-md5-96|hmac-sha1-96|umac-64)(-etm@openssh\.com)?$/;
543
+ export function sshFindings(k, area, target, internetFacing) {
544
+ const out = [];
545
+ const base = { area, target, internetFacing };
546
+ const pqc = k.kex.some((x) => SSH_PQC_KEX.test(x));
547
+ if (!pqc) {
548
+ out.push({ ...base, ruleId: "ssh-kex", title: `SSH key exchange has no quantum-safe option (offers ${k.kex.filter((x) => !x.startsWith("ext-info") && !x.startsWith("kex-strict")).slice(0, 2).join(", ")})`, algorithm: "SSH key exchange", primitive: "key-agreement", risk: "quantum-vulnerable", severity: "high", fix: "Upgrade to OpenSSH 9.9 or later and allow mlkem768x25519-sha256 (or sntrup761x25519-sha512) key exchange." });
549
+ }
550
+ const weak = [...k.kex.filter((x) => SSH_WEAK_KEX.test(x)), ...k.ciphers.filter((x) => SSH_WEAK_CIPHER.test(x)), ...k.macs.filter((x) => SSH_WEAK_MAC.test(x)), ...k.hostKeys.filter((x) => x === "ssh-dss" || x === "ssh-rsa")];
551
+ if (weak.length) {
552
+ out.push({ ...base, ruleId: "ssh-weak", title: `SSH allows weak settings: ${[...new Set(weak)].slice(0, 4).join(", ")}`, algorithm: "SSH weak settings", primitive: "protocol", risk: "weak-now", severity: "medium", fix: "Remove SHA-1, CBC, 3DES and arcfour options from KexAlgorithms, Ciphers, MACs and HostKeyAlgorithms." });
553
+ }
554
+ const hk = k.hostKeys.filter((x) => x !== "ssh-dss");
555
+ if (hk.length) {
556
+ out.push({ ...base, ruleId: "ssh-host-key", title: `SSH host keys use ${[...new Set(hk.map(hostKeyFamily))].join(", ")}`, algorithm: "SSH host key", primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: "Plan to move host keys to post-quantum signatures once OpenSSH supports them; keep Ed25519 until then." });
557
+ }
558
+ return { findings: out, pqc };
559
+ }
560
+ function hostKeyFamily(x) {
561
+ if (x.includes("ed25519"))
562
+ return "Ed25519";
563
+ if (x.includes("ecdsa"))
564
+ return "ECDSA";
565
+ if (x.includes("rsa"))
566
+ return "RSA";
567
+ return x;
568
+ }
569
+ export async function checkSsh(t, log, res, ssh = sshKexInit) {
570
+ log.record("web", t.label, "SSH connection: read the server's announced settings, then disconnect (no login)");
571
+ const k = await ssh(t.host, t.port);
572
+ if ("error" in k) {
573
+ res.errors.push({ area: "web", target: t.label, kind: k.error, message: k.message });
574
+ return;
575
+ }
576
+ res.checked.push(t.label);
577
+ const r = sshFindings(k, "web", t.label, true);
578
+ res.findings.push(...r.findings);
579
+ if (r.pqc)
580
+ res.strengths.push({ area: "web", target: t.label, algorithm: "Hybrid SSH key exchange", title: "SSH offers quantum-safe hybrid key exchange" });
581
+ }
582
+ export const MAX_WEB_TARGETS = 200;
583
+ /** Runs the website area: proves each domain, then checks only addresses under a proved domain. */
584
+ export async function runWeb(targets, log, o) {
585
+ const res = { ...emptyResult("web"), unproved: [], dnsFailed: [] };
586
+ const fallback = o.fallbackLookup !== undefined ? o.fallbackLookup : o.lookup ? null : publicLookup();
587
+ const parsed = [];
588
+ for (const raw of targets.slice(0, MAX_WEB_TARGETS)) {
589
+ const p = parseTarget(raw);
590
+ if ("error" in p)
591
+ res.skipped.push({ target: raw, reason: p.error });
592
+ else if (!parsed.some((x) => x.label === p.label))
593
+ parsed.push(p);
594
+ }
595
+ if (targets.length > MAX_WEB_TARGETS)
596
+ res.skipped.push({ target: `${targets.length - MAX_WEB_TARGETS} more`, reason: `at most ${MAX_WEB_TARGETS} addresses per run` });
597
+ const proved = [];
598
+ const tried = new Map();
599
+ for (const t of parsed) {
600
+ if (coveringDomain(t.host, proved))
601
+ continue;
602
+ let found = null;
603
+ for (const d of parentDomains(t.host)) {
604
+ if (tried.has(d))
605
+ continue;
606
+ const r = await checkProof(d, o.token, log, o.lookup, fallback);
607
+ tried.set(d, r);
608
+ if (r.status === "found") {
609
+ found = d;
610
+ break;
611
+ }
612
+ }
613
+ if (found)
614
+ proved.push(found);
615
+ }
616
+ for (const t of parsed) {
617
+ if (!coveringDomain(t.host, proved)) {
618
+ const failed = parentDomains(t.host).map((d) => tried.get(d)).find((r) => r?.status === "lookup-failed");
619
+ if (failed) {
620
+ res.errors.push({ area: "web", target: t.label, kind: "dns", message: `couldn't look up the ownership record: ${failed.detail ?? "DNS didn't answer"}` });
621
+ if (!res.dnsFailed.includes(t.label))
622
+ res.dnsFailed.push(t.label);
623
+ continue;
624
+ }
625
+ res.skipped.push({ target: t.label, reason: "no ownership record found for this domain" });
626
+ if (!res.unproved.includes(registrable(t.host)))
627
+ res.unproved.push(registrable(t.host));
628
+ continue;
629
+ }
630
+ if (t.kind === "ssh")
631
+ await checkSsh(t, log, res, o.ssh);
632
+ else
633
+ await checkTls(t, log, res, o.handshake, o.gapMs, o.cipherProbe);
634
+ }
635
+ return res;
636
+ }
637
+ /** A best guess at the domain someone would put the record on: the last two labels. */
638
+ export function registrable(host) {
639
+ return host.split(".").slice(-2).join(".");
640
+ }
package/dist/pqc.js ADDED
@@ -0,0 +1,32 @@
1
+ // Detects post-quantum encryption already in use (ML-KEM, ML-DSA, SLH-DSA, FN-DSA, hybrids).
2
+ // Used only by the readiness score, to credit migration work. Never reported as a problem.
3
+ // Order matters: the first rule that matches a line wins, so hybrids come before plain ML-KEM.
4
+ const PQC_RULES = [
5
+ { pattern: /\b(?:X25519|SecP256r1|SecP384r1)[-_]?MLKEM[-_]?(?:768|1024)\b|\bX25519Kyber768\b/i, algorithm: "Hybrid ML-KEM key exchange", use: "key-establishment" },
6
+ { pattern: /\b(?:ML[-_]?KEM|MLKEM)(?:[-_]?(?:512|768|1024))?\b|\bcrypto\/mlkem\b/i, algorithm: "ML-KEM", use: "key-establishment" },
7
+ { pattern: /\bKyber(?:512|768|1024)\b/, algorithm: "ML-KEM", use: "key-establishment" },
8
+ { pattern: /\b(?:ML[-_]?DSA|MLDSA)(?:[-_]?(?:44|65|87))?\b/i, algorithm: "ML-DSA", use: "signature" },
9
+ { pattern: /\bDilithium[2-5]\b/, algorithm: "ML-DSA", use: "signature" },
10
+ { pattern: /\bSLH[-_]?DSA\b|\bSPHINCS\+/i, algorithm: "SLH-DSA", use: "signature" },
11
+ { pattern: /\bFN[-_]?DSA\b|\bFalcon[-_]?(?:512|1024)\b/, algorithm: "FN-DSA", use: "signature" },
12
+ ];
13
+ const CODE_OR_CONFIG = /\.(py|pyw|js|mjs|cjs|jsx|ts|mts|cts|tsx|go|java|kt|kts|scala|rs|c|cc|cpp|h|hpp|cs|rb|php|swift|conf|cfg|ini|ya?ml|toml|tf|hcl|json|properties)$|(^|\/)(nginx|httpd)[^/]*$/i;
14
+ /** Post-quantum algorithms used in one source or config file. Documentation is ignored. */
15
+ export function findPqc(path, content) {
16
+ if (!CODE_OR_CONFIG.test(path) || content.includes("\u0000"))
17
+ return [];
18
+ const out = [];
19
+ const lines = content.split(/\r?\n/);
20
+ for (let i = 0; i < lines.length; i++) {
21
+ const text = lines[i];
22
+ if (text.length > 2000)
23
+ continue;
24
+ for (const r of PQC_RULES) {
25
+ if (r.pattern.test(text)) {
26
+ out.push({ algorithm: r.algorithm, use: r.use, file: path, line: i + 1 });
27
+ break;
28
+ }
29
+ }
30
+ }
31
+ return out;
32
+ }