@hardkeel/quantum-scan 0.0.0-stage → 0.3.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,518 @@
1
+ // Network and connected equipment: finds what on your own network is exposed or left at its
2
+ // defaults. Routers, switches, printers, cameras, storage boxes and smart devices.
3
+ //
4
+ // Look only. For each address in the approved ranges it checks whether about 30 common ports
5
+ // answer, reads the title of any web page they serve and the certificate on secure admin pages,
6
+ // and reads the router's list of automatic port forwards (UPnP) if it publishes one.
7
+ // It never logs in, tries a password, sends commands to equipment or changes a setting.
8
+ //
9
+ // Ownership: only private address ranges. A range must be one this computer is connected to,
10
+ // unless the person lists it separately as another segment of their own network.
11
+ // At most 1,024 addresses per run, one connection at a time per device.
12
+ import { createSocket } from "node:dgram";
13
+ import { request as httpRequest } from "node:http";
14
+ import { request as httpsRequest } from "node:https";
15
+ import { connect as netConnect } from "node:net";
16
+ import { networkInterfaces } from "node:os";
17
+ import { connect as tlsConnect } from "node:tls";
18
+ import { emptyResult } from "./map-types.js";
19
+ export const MAX_NETWORK_ADDRESSES = 1024;
20
+ // ---------- addresses ----------
21
+ export function ipToInt(ip) {
22
+ const m = ip.trim().match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
23
+ if (!m)
24
+ return null;
25
+ const o = m.slice(1).map(Number);
26
+ if (o.some((x) => x > 255))
27
+ return null;
28
+ return ((o[0] << 24) >>> 0) + (o[1] << 16) + (o[2] << 8) + o[3];
29
+ }
30
+ export const intToIp = (n) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join(".");
31
+ /** A network this computer is on, as its interface reports it (any size, e.g. 10.0.0.0/8). */
32
+ export function parseCidr(raw) {
33
+ const [ip, bitsRaw] = raw.trim().split("/");
34
+ const base = ipToInt(ip);
35
+ const bits = bitsRaw === undefined ? 32 : Number(bitsRaw);
36
+ if (base === null || !Number.isInteger(bits) || bits < 0 || bits > 32)
37
+ return null;
38
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
39
+ const start = (base & mask) >>> 0;
40
+ return { label: raw.trim(), start, end: (start | (~mask >>> 0)) >>> 0 };
41
+ }
42
+ /** The networks this computer is on. Larger than the /20 limit is fine here: it only decides what counts as "on this network". */
43
+ export const machineRanges = (io) => io.interfaces().map((i) => parseCidr(i.cidr)).filter((r) => r !== null);
44
+ /** "192.168.1.0/24" or a single address. Only /20 or smaller. */
45
+ export function parseRange(raw) {
46
+ const t = raw.trim();
47
+ const [ip, bitsRaw] = t.split("/");
48
+ const base = ipToInt(ip);
49
+ if (base === null)
50
+ return { error: "not an IPv4 address or range" };
51
+ const bits = bitsRaw === undefined ? 32 : Number(bitsRaw);
52
+ if (!Number.isInteger(bits) || bits < 0 || bits > 32)
53
+ return { error: "not a valid range" };
54
+ if (bits < 20)
55
+ return { error: "too large; list ranges of /20 (4,096 addresses) or smaller" };
56
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
57
+ const start = (base & mask) >>> 0;
58
+ const end = (start | (~mask >>> 0)) >>> 0;
59
+ return { label: t, start, end };
60
+ }
61
+ const PRIVATE = [
62
+ [ipToInt("10.0.0.0"), ipToInt("10.255.255.255")],
63
+ [ipToInt("172.16.0.0"), ipToInt("172.31.255.255")],
64
+ [ipToInt("192.168.0.0"), ipToInt("192.168.255.255")],
65
+ ];
66
+ export const isPrivateRange = (r) => PRIVATE.some(([a, b]) => r.start >= a && r.end <= b);
67
+ /** Addresses in a range, leaving out the network and broadcast addresses of a /30 or larger. */
68
+ export function hostsOf(r) {
69
+ const out = [];
70
+ const size = r.end - r.start + 1;
71
+ const from = size > 2 ? r.start + 1 : r.start;
72
+ const to = size > 2 ? r.end - 1 : r.end;
73
+ for (let n = from; n <= to; n++)
74
+ out.push(n);
75
+ return out;
76
+ }
77
+ /** About 30 ports. Chosen for what they reveal about equipment, not to sweep everything. */
78
+ export const PORTS = [
79
+ { port: 21, name: "FTP", role: "plain" },
80
+ { port: 22, name: "SSH", role: "remote" },
81
+ { port: 23, name: "Telnet", role: "plain" },
82
+ { port: 80, name: "HTTP", role: "web" },
83
+ { port: 443, name: "HTTPS", role: "web-tls" },
84
+ { port: 515, name: "LPD printing", role: "printer" },
85
+ { port: 554, name: "RTSP video stream", role: "camera" },
86
+ { port: 631, name: "IPP printing", role: "printer" },
87
+ { port: 1883, name: "MQTT", role: "iot" },
88
+ { port: 2375, name: "Docker API", role: "service" },
89
+ { port: 3389, name: "Remote Desktop", role: "remote" },
90
+ { port: 4443, name: "HTTPS (alt)", role: "web-tls" },
91
+ { port: 5000, name: "HTTP (alt)", role: "web" },
92
+ { port: 5001, name: "HTTPS (alt)", role: "web-tls" },
93
+ { port: 5900, name: "VNC", role: "remote" },
94
+ { port: 5901, name: "VNC", role: "remote" },
95
+ { port: 5938, name: "TeamViewer", role: "remote" },
96
+ { port: 6379, name: "Redis", role: "service" },
97
+ { port: 7070, name: "AnyDesk", role: "remote" },
98
+ { port: 8000, name: "HTTP (alt)", role: "web" },
99
+ { port: 8040, name: "ScreenConnect", role: "remote" },
100
+ { port: 8080, name: "HTTP (alt)", role: "web" },
101
+ { port: 8081, name: "HTTP (alt)", role: "web" },
102
+ { port: 8443, name: "HTTPS (alt)", role: "web-tls" },
103
+ { port: 8888, name: "HTTP (alt)", role: "web" },
104
+ { port: 9100, name: "Raw printing", role: "printer" },
105
+ { port: 9200, name: "Elasticsearch", role: "service" },
106
+ { port: 27017, name: "MongoDB", role: "service" },
107
+ { port: 34567, name: "DVR service", role: "camera" },
108
+ { port: 37777, name: "DVR service", role: "camera" },
109
+ ];
110
+ /** Ports tried first to see whether anything is at an address. A refused connection counts as there. */
111
+ export const LIVE_PORTS = [80, 443, 22, 445, 139, 3389, 9100, 554, 8080, 5000];
112
+ const CLASS_PATTERNS = [
113
+ ["printer", /printer|laserjet|officejet|deskjet|pagewide|embedded web server|\bews\b|brother|epson|canon|xerox|ricoh|kyocera|lexmark|konica|bizhub|sharp mx|cups/i],
114
+ ["camera", /camera|ipcam|ip cam|hikvision|dahua|amcrest|reolink|foscam|\bnvr\b|\bdvr\b|netsurveillance|xmeye|axis communications|lorex|swann/i],
115
+ ["storage", /synology|diskstation|qnap|truenas|freenas|unraid|readynas|\bnas\b|my cloud/i],
116
+ ["router", /router|gateway|switch|access point|ubiquiti|unifi|edgeos|edgerouter|mikrotik|routeros|netgear|tp-?link|linksys|\basus\b|d-link|zyxel|draytek|fortigate|fortinet|sonicwall|pfsense|opnsense|openwrt|dd-wrt|cisco|aruba|meraki|juniper|eero|orbi|arris|technicolor|sagemcom|xfinity|airport|omada|ruckus/i],
117
+ ["smart device", /home assistant|philips hue|hue bridge|sonos|shelly|tasmota|esphome|smartthings|homebridge|ecobee|nest|tuya|roku|chromecast/i],
118
+ ];
119
+ export function classify(text, ports) {
120
+ for (const [c, re] of CLASS_PATTERNS)
121
+ if (re.test(text))
122
+ return c;
123
+ if (ports.some((p) => p === 9100 || p === 631 || p === 515))
124
+ return "printer";
125
+ if (ports.some((p) => p === 554 || p === 37777 || p === 34567))
126
+ return "camera";
127
+ return null;
128
+ }
129
+ const SETUP_PAGE = /setup wizard|first[- ]?time setup|initial (setup|configuration)|quick setup|getting started|welcome to (the )?setup|create (an )?admin|set (the |an )?admin(istrator)? password|device activation|activate (your )?device|out of box/i;
130
+ const VENDOR_CERT = /ubiquiti|unifi|fortinet|fortigate|sonicwall|synology|qnap|hikvision|dahua|tp-?link|netgear|linksys|asus|d-link|zyxel|draytek|mikrotik|pfsense|opnsense|cisco|aruba|meraki|juniper|hewlett|\bhp\b|brother|epson|canon|xerox|ricoh|kyocera|lexmark|axis|router|default|localhost|self-?signed|example/i;
131
+ const UA = "HardKeelQuantumScan/1 (look-only; https://hardkeel.com/quantum-scan/)";
132
+ function readBody(res, max = 65536) {
133
+ return new Promise((resolve) => {
134
+ let buf = "";
135
+ res.setEncoding?.("utf8");
136
+ res.on("data", (c) => {
137
+ buf += c;
138
+ if (buf.length > max)
139
+ res.destroy();
140
+ });
141
+ res.on("end", () => resolve(buf));
142
+ res.on("close", () => resolve(buf));
143
+ res.on("error", () => resolve(buf));
144
+ });
145
+ }
146
+ export function pageTitle(html) {
147
+ const m = html.match(/<title[^>]*>([\s\S]{0,300}?)<\/title>/i);
148
+ const t = m?.[1]
149
+ .replace(/<[^>]+>/g, "")
150
+ .replace(/&amp;/g, "&")
151
+ .replace(/&nbsp;|&#160;/g, " ")
152
+ .replace(/\s+/g, " ")
153
+ .trim();
154
+ return t ? t.slice(0, 80) : undefined;
155
+ }
156
+ function getText(url, timeoutMs = 3000, method = "GET", body, headers = {}) {
157
+ return new Promise((resolve) => {
158
+ let u;
159
+ try {
160
+ u = new URL(url);
161
+ }
162
+ catch {
163
+ return resolve(null);
164
+ }
165
+ const req = (u.protocol === "https:" ? httpsRequest : httpRequest)(u, { method, headers: { "user-agent": UA, ...headers }, timeout: timeoutMs, rejectUnauthorized: false }, async (res) => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: await readBody(res) }));
166
+ req.on("timeout", () => req.destroy());
167
+ req.on("error", () => resolve(null));
168
+ if (body)
169
+ req.write(body);
170
+ req.end();
171
+ });
172
+ }
173
+ export const realNetIO = {
174
+ interfaces() {
175
+ const out = [];
176
+ for (const list of Object.values(networkInterfaces()))
177
+ for (const i of list ?? [])
178
+ if (i.family === "IPv4" && !i.internal && i.cidr)
179
+ out.push({ address: i.address, cidr: i.cidr });
180
+ return out;
181
+ },
182
+ probe(host, port, timeoutMs) {
183
+ return new Promise((resolve) => {
184
+ const s = netConnect({ host, port });
185
+ const done = (r) => {
186
+ s.removeAllListeners();
187
+ s.destroy();
188
+ resolve(r);
189
+ };
190
+ s.setTimeout(timeoutMs, () => done("timeout"));
191
+ s.once("connect", () => done("open"));
192
+ s.once("error", (e) => done(e.code === "ECONNREFUSED" ? "closed" : "error"));
193
+ });
194
+ },
195
+ async http(host, port, tls) {
196
+ const r = await getText(`${tls ? "https" : "http"}://${host}:${port}/`);
197
+ if (!r)
198
+ return null;
199
+ const one = (v) => (Array.isArray(v) ? v[0] : v);
200
+ return { status: r.status, location: one(r.headers.location), server: one(r.headers.server)?.slice(0, 80), title: pageTitle(r.body) };
201
+ },
202
+ cert(host, port) {
203
+ return new Promise((resolve) => {
204
+ const s = tlsConnect({ host, port, rejectUnauthorized: false, timeout: 3000 });
205
+ const done = (v) => {
206
+ s.removeAllListeners();
207
+ s.destroy();
208
+ resolve(v);
209
+ };
210
+ s.once("secureConnect", () => {
211
+ const c = s.getPeerX509Certificate();
212
+ done(c ? { subject: c.subject.replace(/\n/g, ", "), issuer: c.issuer.replace(/\n/g, ", "), selfSigned: c.checkIssued(c) } : null);
213
+ });
214
+ s.once("timeout", () => done(null));
215
+ s.once("error", () => done(null));
216
+ });
217
+ },
218
+ async upnp(allowed) {
219
+ const location = await ssdpLocation();
220
+ if (!location)
221
+ return null;
222
+ return readUpnp(location, allowed);
223
+ },
224
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
225
+ };
226
+ /**
227
+ * Reads the port-forward list from the router that answered. The answer names its own address, and any
228
+ * device on the network can answer, so the address must be a plain IPv4 address inside the approved ranges
229
+ * before anything is fetched from it.
230
+ */
231
+ export async function readUpnp(location, allowed) {
232
+ let host;
233
+ try {
234
+ host = new URL(location).hostname;
235
+ }
236
+ catch {
237
+ return { host: "unknown", mappings: [], outside: true };
238
+ }
239
+ if (ipToInt(host) === null || !allowed(host))
240
+ return { host, mappings: [], outside: true };
241
+ const desc = await getText(location);
242
+ if (!desc)
243
+ return { host, mappings: [] };
244
+ const svc = upnpService(desc.body, location);
245
+ if (!svc)
246
+ return { host, mappings: [] };
247
+ const mappings = [];
248
+ for (let i = 0; i < 64; i++) {
249
+ const body = `<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetGenericPortMappingEntry xmlns:u="${svc.type}"><NewPortMappingIndex>${i}</NewPortMappingIndex></u:GetGenericPortMappingEntry></s:Body></s:Envelope>`;
250
+ const r = await getText(svc.control, 3000, "POST", body, { "content-type": 'text/xml; charset="utf-8"', soapaction: `"${svc.type}#GetGenericPortMappingEntry"` });
251
+ if (!r || r.status !== 200)
252
+ break;
253
+ const m = parseMapping(r.body);
254
+ if (!m)
255
+ break;
256
+ mappings.push(m);
257
+ }
258
+ return { host, mappings };
259
+ }
260
+ /** Asks the local network, once, whether a router offers UPnP. Read only: M-SEARCH is a question. */
261
+ function ssdpLocation(timeoutMs = 2500) {
262
+ return new Promise((resolve) => {
263
+ const sock = createSocket({ type: "udp4", reuseAddr: true });
264
+ const done = (v) => {
265
+ clearTimeout(timer);
266
+ try {
267
+ sock.close();
268
+ }
269
+ catch {
270
+ // already closed
271
+ }
272
+ resolve(v);
273
+ };
274
+ const timer = setTimeout(() => done(null), timeoutMs);
275
+ sock.on("error", () => done(null));
276
+ sock.on("message", (msg) => {
277
+ const loc = msg.toString("utf8").match(/^location:\s*(\S+)/im)?.[1];
278
+ if (loc && /^http:\/\//i.test(loc))
279
+ done(loc);
280
+ });
281
+ const q = ["M-SEARCH * HTTP/1.1", "HOST: 239.255.255.250:1900", 'MAN: "ssdp:discover"', "MX: 2", "ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1", "", ""].join("\r\n");
282
+ sock.send(q, 1900, "239.255.255.250", (e) => e && done(null));
283
+ });
284
+ }
285
+ export function upnpService(xml, location) {
286
+ const services = xml.match(/<service>[\s\S]*?<\/service>/gi) ?? [];
287
+ for (const s of services) {
288
+ const type = s.match(/<serviceType>\s*([^<]+?)\s*<\/serviceType>/i)?.[1];
289
+ const control = s.match(/<controlURL>\s*([^<]+?)\s*<\/controlURL>/i)?.[1];
290
+ if (type && control && /WAN(IP|PPP)Connection/i.test(type)) {
291
+ try {
292
+ const url = new URL(control, location);
293
+ // Only ever talk to the router that answered.
294
+ if (url.hostname !== new URL(location).hostname)
295
+ return null;
296
+ return { type, control: url.toString() };
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
302
+ }
303
+ return null;
304
+ }
305
+ export function parseMapping(xml) {
306
+ const v = (tag) => xml.match(new RegExp(`<${tag}>\\s*([^<]*?)\\s*</${tag}>`, "i"))?.[1];
307
+ const ext = Number(v("NewExternalPort"));
308
+ const int = Number(v("NewInternalPort"));
309
+ const client = v("NewInternalClient");
310
+ if (!Number.isInteger(ext) || !client)
311
+ return null;
312
+ return { externalPort: ext, internalClient: client, internalPort: Number.isInteger(int) ? int : ext, protocol: (v("NewProtocol") ?? "").toUpperCase().slice(0, 4), description: (v("NewPortMappingDescription") ?? "").slice(0, 60), enabled: v("NewEnabled") !== "0" };
313
+ }
314
+ export const NET_RULES = {
315
+ telnet: { ruleId: "net-telnet", algorithm: "Telnet", severity: "high", primitive: "protocol", title: "Telnet is open: logins cross the network in plain text", fix: "Turn Telnet off and use SSH instead." },
316
+ ftp: { ruleId: "net-ftp", algorithm: "Plain FTP", severity: "medium", primitive: "protocol", title: "FTP is open: files and passwords cross the network unencrypted", fix: "Turn FTP off, or switch to SFTP." },
317
+ rdp: { ruleId: "net-rdp", algorithm: "Remote Desktop open", severity: "high", title: "Remote Desktop is open on the network", fix: "Allow Remote Desktop only through a VPN or a gateway with multi-factor sign-in, and only from admin machines." },
318
+ vnc: { ruleId: "net-vnc", algorithm: "VNC open", severity: "high", title: "VNC screen sharing is open", fix: "Turn VNC off, or limit it to admin machines with a strong password and encryption." },
319
+ remoteTool: { ruleId: "net-remote-tool", algorithm: "Remote support tool", severity: "medium", title: "A remote support tool is listening", fix: "Check who installed it. Remove it if it isn't in use, and require multi-factor sign-in on its account." },
320
+ setupPage: { ruleId: "net-setup-page", algorithm: "Setup page open", severity: "critical", title: "A device is still on its first-time setup page", fix: "Finish setup and set a strong admin password now. Until then, anyone on the network can take this device over." },
321
+ adminHttp: { ruleId: "net-admin-http", algorithm: "Admin page over plain HTTP", severity: "medium", title: "Admin page served without encryption", fix: "Use only the HTTPS admin page and turn off HTTP admin access. Keep admin pages reachable from an admin network only." },
322
+ vendorCert: { ruleId: "net-vendor-cert", algorithm: "Vendor default certificate", severity: "low", title: "Admin page uses the factory certificate", fix: "Replace the factory certificate with one from your own certificate authority, so staff can tell the real admin page from a fake." },
323
+ printRaw: { ruleId: "net-printer-raw", algorithm: "Open print port", severity: "medium", title: "Anyone on the network can send jobs to this printer, and many printers keep copies of past jobs", fix: "Route printing through a print server, close raw port 9100 if it isn't needed, and turn off stored jobs or set them to wipe automatically." },
324
+ printLpd: { ruleId: "net-printer-lpd", algorithm: "LPD printing", severity: "low", title: "Old LPD printing is turned on", fix: "Turn off LPD and use IPP over TLS or a print server." },
325
+ rtsp: { ruleId: "net-camera-stream", algorithm: "Camera stream port", severity: "medium", title: "A video stream port is open", fix: "Put cameras on their own network, change any default password, and turn off streams you don't use." },
326
+ dvr: { ruleId: "net-camera-dvr", algorithm: "DVR service port", severity: "high", title: "A camera recorder's service port is open. These ports have a long record of break-ins", fix: "Update the recorder's firmware, put it on its own network, and block this port from staff and guest networks." },
327
+ mqtt: { ruleId: "net-mqtt", algorithm: "MQTT without encryption", severity: "medium", primitive: "protocol", title: "Smart-device messages (MQTT) travel unencrypted", fix: "Use MQTT over TLS (port 8883) with a password for each device." },
328
+ dockerPort: { ruleId: "net-docker-port", algorithm: "Docker API port open", severity: "medium", title: "Something answers on the Docker API port (2375). If it's Docker, anyone who reaches it controls the machine", fix: "Check what listens on port 2375. If it's Docker, bind it to the local socket only, or require TLS with client certificates." },
329
+ docker: { ruleId: "net-docker-api", algorithm: "Docker API open", severity: "critical", title: "The Docker API is open without encryption: anyone who reaches it controls the machine", fix: "Bind Docker to the local socket only, or require TLS with client certificates." },
330
+ database: { ruleId: "net-database-open", algorithm: "Database open on the network", severity: "high", title: "A database answers on the network", fix: "Bind it to localhost or a private app network, and require a password and TLS." },
331
+ upnpOn: { ruleId: "net-upnp-on", algorithm: "UPnP on the router", severity: "low", title: "The router lets any device open ports to the internet (UPnP)", fix: "Turn UPnP off on the router unless a device truly needs it." },
332
+ upnpForward: { ruleId: "net-upnp-forward", algorithm: "Router forward from the internet", severity: "high", internetFacing: true, title: "The router forwards a port from the internet to a device", fix: "Remove forwards you don't need. If a device must be reachable from outside, use a VPN instead." },
333
+ };
334
+ export const NET_ALGORITHMS = Object.values(NET_RULES).map((r) => r.algorithm);
335
+ function finding(rule, target, extraTitle = "") {
336
+ return {
337
+ area: "network",
338
+ target,
339
+ ruleId: rule.ruleId,
340
+ title: rule.title + extraTitle,
341
+ algorithm: rule.algorithm,
342
+ primitive: rule.primitive ?? "setting",
343
+ risk: "exposed",
344
+ severity: rule.severity,
345
+ fix: rule.fix,
346
+ internetFacing: rule.internetFacing ?? false,
347
+ };
348
+ }
349
+ /** What one device's open ports and pages say, as findings. Pure, so it can be tested. */
350
+ export function deviceFindings(d) {
351
+ const text = d.pages.filter((p) => p.port !== 2375).map((p) => `${p.page?.title ?? ""} ${p.page?.server ?? ""} ${p.cert?.subject ?? ""}`).join(" ");
352
+ const cls = classify(text, d.open);
353
+ const title = d.pages.map((p) => p.page?.title).find(Boolean);
354
+ const label = cls ? `${cls}${title ? `: ${title}` : ""}` : (title ?? "");
355
+ const at = (port) => `${d.ip}:${port}${label ? ` (${label})` : ""}`;
356
+ const out = [];
357
+ const has = (p) => d.open.includes(p);
358
+ if (has(23))
359
+ out.push(finding(NET_RULES.telnet, at(23)));
360
+ if (has(21))
361
+ out.push(finding(NET_RULES.ftp, at(21)));
362
+ if (has(3389))
363
+ out.push(finding(NET_RULES.rdp, at(3389)));
364
+ for (const p of [5900, 5901])
365
+ if (has(p))
366
+ out.push(finding(NET_RULES.vnc, at(p)));
367
+ for (const p of [5938, 7070, 8040])
368
+ if (has(p))
369
+ out.push(finding(NET_RULES.remoteTool, at(p), ` (${PORTS.find((x) => x.port === p).name})`));
370
+ if (has(9100))
371
+ out.push(finding(NET_RULES.printRaw, at(9100)));
372
+ if (has(515))
373
+ out.push(finding(NET_RULES.printLpd, at(515)));
374
+ if (has(554))
375
+ out.push(finding(NET_RULES.rtsp, at(554)));
376
+ for (const p of [34567, 37777])
377
+ if (has(p))
378
+ out.push(finding(NET_RULES.dvr, at(p)));
379
+ if (has(1883))
380
+ out.push(finding(NET_RULES.mqtt, at(1883)));
381
+ if (has(2375)) {
382
+ const peek = d.pages.find((p) => p.port === 2375)?.page;
383
+ out.push(finding(peek && /docker/i.test(`${peek.server ?? ""}`) ? NET_RULES.docker : NET_RULES.dockerPort, at(2375)));
384
+ }
385
+ for (const p of [6379, 9200, 27017])
386
+ if (has(p))
387
+ out.push(finding(NET_RULES.database, at(p), ` (${PORTS.find((x) => x.port === p).name})`));
388
+ let setup = false;
389
+ for (const pg of d.pages.filter((x) => x.port !== 2375)) {
390
+ const t = `${pg.page?.title ?? ""}`;
391
+ if (!setup && SETUP_PAGE.test(t)) {
392
+ setup = true;
393
+ out.push(finding(NET_RULES.setupPage, at(pg.port)));
394
+ }
395
+ const redirectsToTls = pg.page && pg.page.status >= 300 && pg.page.status < 400 && /^https:/i.test(pg.page.location ?? "");
396
+ if (!pg.tls && pg.page && !redirectsToTls && cls && cls !== "smart device")
397
+ out.push(finding(NET_RULES.adminHttp, at(pg.port)));
398
+ if (pg.tls && pg.cert && pg.cert.selfSigned && (VENDOR_CERT.test(pg.cert.subject) || /CN=(\d{1,3}\.){3}\d{1,3}\b/.test(pg.cert.subject) || !/CN=/.test(pg.cert.subject)))
399
+ out.push(finding(NET_RULES.vendorCert, at(pg.port)));
400
+ }
401
+ // One plain-HTTP admin finding per device is enough.
402
+ const firstHttp = out.findIndex((f) => f.ruleId === NET_RULES.adminHttp.ruleId);
403
+ return { findings: out.filter((f, i) => f.ruleId !== NET_RULES.adminHttp.ruleId || i === firstHttp), label };
404
+ }
405
+ export function upnpFindings(host, mappings) {
406
+ const out = [finding(NET_RULES.upnpOn, `${host} (router)`)];
407
+ for (const m of mappings.filter((x) => x.enabled)) {
408
+ out.push(finding(NET_RULES.upnpForward, `internet port ${m.externalPort}/${m.protocol || "TCP"} -> ${m.internalClient}:${m.internalPort}${m.description ? ` (${m.description})` : ""}`));
409
+ }
410
+ return out;
411
+ }
412
+ // ---------- the run ----------
413
+ async function pool(items, n, fn) {
414
+ let i = 0;
415
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
416
+ while (i < items.length)
417
+ await fn(items[i++]);
418
+ }));
419
+ }
420
+ export async function runNetwork(scope, log, o = {}) {
421
+ const io = o.io ?? realNetIO;
422
+ const gap = o.gapMs ?? 250;
423
+ const res = emptyResult("network");
424
+ const mine = machineRanges(io);
425
+ const onThisMachine = (r) => mine.some((m) => r.start >= m.start && r.end <= m.end);
426
+ const ranges = [];
427
+ for (const [raw, routed] of [...(scope.ranges ?? []).map((r) => [r, false]), ...(scope.routed ?? []).map((r) => [r, true])]) {
428
+ const r = parseRange(raw);
429
+ if ("error" in r)
430
+ res.skipped.push({ target: raw, reason: r.error });
431
+ else if (!isPrivateRange(r))
432
+ res.skipped.push({ target: raw, reason: "not a private address range, so it can't be your own internal network" });
433
+ else if (!routed && !onThisMachine(r))
434
+ res.skipped.push({ target: raw, reason: "this computer isn't connected to that network. If it's another segment of your own network, list it under routed" });
435
+ else
436
+ ranges.push(r);
437
+ }
438
+ const excluded = (scope.exclude ?? []).map(parseRange).filter((r) => !("error" in r));
439
+ const isExcluded = (n) => excluded.some((r) => n >= r.start && n <= r.end);
440
+ let hosts = [...new Set(ranges.flatMap(hostsOf))].filter((n) => !isExcluded(n));
441
+ if (hosts.length > MAX_NETWORK_ADDRESSES) {
442
+ res.skipped.push({ target: `${(hosts.length - MAX_NETWORK_ADDRESSES).toLocaleString("en-US")} addresses from ${intToIp(hosts[MAX_NETWORK_ADDRESSES])} on`, reason: `one run checks the first ${MAX_NETWORK_ADDRESSES.toLocaleString("en-US")} addresses. Run again with the rest listed as their own ranges` });
443
+ hosts = hosts.slice(0, MAX_NETWORK_ADDRESSES);
444
+ }
445
+ if (excluded.length)
446
+ res.skipped.push({ target: (scope.exclude ?? []).join(", "), reason: "excluded in the scope file" });
447
+ if (!hosts.length)
448
+ return res;
449
+ const allowed = new Set(hosts.map(intToIp));
450
+ // 1. Which addresses have something at them.
451
+ const live = [];
452
+ await pool(hosts.map(intToIp), 32, async (ip) => {
453
+ log.record("network", ip, "checked whether anything answers");
454
+ for (const port of LIVE_PORTS) {
455
+ const s = await io.probe(ip, port, o.liveTimeoutMs ?? 400);
456
+ if (s === "open" || s === "closed") {
457
+ live.push(ip);
458
+ return;
459
+ }
460
+ }
461
+ });
462
+ live.sort((a, b) => ipToInt(a) - ipToInt(b));
463
+ // 2. Each device, one connection at a time.
464
+ await pool(live, 8, async (ip) => {
465
+ const open = [];
466
+ log.record("network", ip, `checked whether ${PORTS.length} common ports answer`);
467
+ for (const p of PORTS) {
468
+ if ((await io.probe(ip, p.port, o.portTimeoutMs ?? 800)) === "open")
469
+ open.push(p.port);
470
+ await io.sleep(gap);
471
+ }
472
+ const pages = [];
473
+ for (const p of PORTS.filter((x) => open.includes(x.port) && (x.role === "web" || x.role === "web-tls"))) {
474
+ const tls = p.role === "web-tls";
475
+ log.record("network", `${ip}:${p.port}`, tls ? "read the page title and certificate" : "read the page title");
476
+ const page = await io.http(ip, p.port, tls);
477
+ const cert = tls ? await io.cert(ip, p.port) : undefined;
478
+ pages.push({ port: p.port, tls, page, cert });
479
+ await io.sleep(gap);
480
+ }
481
+ if (open.includes(2375)) {
482
+ // Docker names itself in a response header. One plain GET of the front page, nothing else.
483
+ log.record("network", `${ip}:2375`, "read the response headers to see whether it's Docker");
484
+ pages.push({ port: 2375, tls: false, page: await io.http(ip, 2375, false) });
485
+ }
486
+ const { findings, label } = deviceFindings({ ip, open, pages });
487
+ res.findings.push(...findings);
488
+ res.checked.push(`${ip}${label ? ` (${label})` : ""}: ${open.length ? open.map((p) => PORTS.find((x) => x.port === p).name).filter((v, i, a) => a.indexOf(v) === i).join(", ") : "no common ports open"}`);
489
+ });
490
+ // 3. The router's automatic port forwards, only when the router is inside the approved ranges.
491
+ log.record("network", "local network", "asked whether a router offers UPnP");
492
+ const u = await io.upnp((h) => allowed.has(h));
493
+ if (u && !u.outside && allowed.has(u.host)) {
494
+ log.record("network", u.host, `read the router's port-forward list (${u.mappings.length})`);
495
+ res.findings.push(...upnpFindings(u.host, u.mappings));
496
+ }
497
+ else if (u) {
498
+ res.skipped.push({ target: u.host, reason: "a router answered for UPnP, but it's outside the approved ranges" });
499
+ }
500
+ res.checked.sort((a, b) => ipToInt(a.split(/[ :]/)[0]) - ipToInt(b.split(/[ :]/)[0]));
501
+ return res;
502
+ }
503
+ /** The /24 networks this computer is on, to suggest when asking. */
504
+ export function suggestedRanges(io = realNetIO) {
505
+ const out = new Set();
506
+ for (const i of io.interfaces()) {
507
+ const r = parseCidr(i.cidr);
508
+ const n = ipToInt(i.address);
509
+ if (!r || n === null)
510
+ continue;
511
+ // On a big network (a /16, say), suggest the /24 around this computer.
512
+ const around = r.end - r.start + 1 >= 256 ? { label: "", start: (n & 0xffffff00) >>> 0, end: ((n & 0xffffff00) >>> 0) + 255 } : r;
513
+ if (!isPrivateRange(around))
514
+ continue;
515
+ out.add(around === r ? `${intToIp(r.start)}/${32 - Math.log2(r.end - r.start + 1)}` : `${intToIp(around.start)}/24`);
516
+ }
517
+ return [...out];
518
+ }
@@ -0,0 +1,77 @@
1
+ // People and process: a short, optional checklist about the parts of security no scan can see,
2
+ // such as phishing, admin habits, separation, backups and what happens on a bad day.
3
+ // Answers stay on this machine. They are scored on their own, next to the technical findings,
4
+ // and are never part of the anonymized summary.
5
+ export const QUESTIONS = [
6
+ { id: "phishing-training", group: "People", text: "Do staff get phishing and social-engineering training at least once a year?", severity: "medium", fix: "Run short phishing training each year, with a practice email or two. Most break-ins start with someone being tricked." },
7
+ { id: "verify-requests", group: "People", text: "Are requests to change bank details, send money or reset a password confirmed by calling back on a known number?", severity: "high", fix: "Require a call back on a number you already have before changing payment details, paying a new account or resetting a password." },
8
+ { id: "report-path", group: "People", text: "Do staff know who to tell, right away, if they clicked something odd?", severity: "medium", fix: "Name one person or address for 'I think I clicked something', and thank people for using it." },
9
+ { id: "mfa", group: "Accounts", text: "Does every email and admin account use multi-factor sign-in?", severity: "high", fix: "Turn on multi-factor sign-in for every email and admin account, ideally with an app or security key, not text messages." },
10
+ { id: "separate-admin", group: "Accounts", text: "Do admins use a separate account for admin work, not their everyday account?", severity: "medium", fix: "Give admins a second account used only for admin work, so a phished everyday account can't change settings." },
11
+ { id: "offboarding", group: "Accounts", text: "Are accounts and access removed the same day someone leaves?", severity: "medium", fix: "Keep a leaving checklist: accounts, shared passwords, door codes, remote tools and devices, done on the last day." },
12
+ { id: "vendor-access", group: "Accounts", text: "Is outside vendors' remote access limited, logged and turned off when not in use?", severity: "high", fix: "Give vendors their own accounts, turn their access on only when needed, and keep a log." },
13
+ { id: "default-passwords", group: "Equipment", text: "Have default passwords been changed on routers, switches, printers, cameras and other equipment?", severity: "high", fix: "Change every default password on network equipment, printers and cameras, and keep the new ones in a password manager." },
14
+ { id: "firmware-updates", group: "Equipment", text: "Do routers, printers, cameras and other equipment get firmware updates at least every quarter?", severity: "medium", fix: "Check equipment firmware every quarter, and replace devices the maker no longer updates." },
15
+ { id: "printer-jobs", group: "Equipment", text: "Do your printers avoid keeping copies of past jobs, or wipe them automatically?", severity: "medium", fix: "Turn off stored jobs on printers, or set them to wipe automatically, and wipe the drive before a printer leaves." },
16
+ { id: "guest-network", group: "Separation", text: "Are guest Wi-Fi, cameras and smart devices on a separate network from staff computers?", severity: "high", fix: "Put guests, cameras and smart devices on their own network, so a hacked camera can't reach staff computers." },
17
+ { id: "payments-separate", group: "Separation", text: "Are card payment systems on their own network, apart from everything else?", severity: "high", fix: "Keep card terminals and payment systems on their own network segment, reachable only from what needs them." },
18
+ { id: "containment", group: "Separation", text: "If one computer were taken over, could it be kept from reaching everything else (staff aren't local admins, file shares are limited)?", severity: "high", fix: "Remove local admin rights from everyday accounts and limit each file share to the people who need it, so one bad click stays small." },
19
+ { id: "sandbox", group: "Separation", text: "Are unknown attachments and new software opened in a sandbox or a separate machine first?", severity: "medium", fix: "Open unknown attachments and try new software in a sandbox (like Windows Sandbox) or a spare machine first." },
20
+ { id: "cloud-keys", group: "Data", text: "Is sensitive data in cloud storage, databases and backups encrypted with keys you hold, so the provider can't read it?", severity: "medium", fix: "Encrypt sensitive data before it goes to the cloud, or keep the keys yourself in an external key store, so no third party holds data it can decrypt." },
21
+ { id: "backups", group: "Data", text: "Are backups kept offline or locked against changes, and was a restore tested in the last six months?", severity: "high", fix: "Keep at least one backup offline or locked against changes, and test a restore twice a year." },
22
+ { id: "incident-plan", group: "Bad day", text: "Is there a written plan for a breach or ransomware attack, including who to call?", severity: "high", fix: "Write a one-page plan: who decides, who to call (IT, insurer, lawyer, bank), how to cut off the network, and where backups are." },
23
+ { id: "logs", group: "Bad day", text: "Are sign-in and admin logs kept long enough to look back at least 90 days?", severity: "low", fix: "Keep sign-in and admin logs for at least 90 days, so you can tell what happened after the fact." },
24
+ ];
25
+ const WEIGHT = { critical: 4, high: 3, medium: 2, low: 1 };
26
+ export function parseAnswers(v) {
27
+ const out = {};
28
+ if (!v || typeof v !== "object" || Array.isArray(v))
29
+ return out;
30
+ const ids = new Set(QUESTIONS.map((q) => q.id));
31
+ for (const [k, a] of Object.entries(v))
32
+ if (ids.has(k) && (a === "yes" || a === "no" || a === "unsure"))
33
+ out[k] = a;
34
+ return out;
35
+ }
36
+ export function scorePeople(answers) {
37
+ const asked = QUESTIONS.filter((q) => answers[q.id]);
38
+ if (!asked.length)
39
+ return null;
40
+ let got = 0;
41
+ let max = 0;
42
+ const gaps = [];
43
+ for (const q of asked) {
44
+ const a = answers[q.id];
45
+ max += WEIGHT[q.severity];
46
+ if (a === "yes")
47
+ got += WEIGHT[q.severity];
48
+ else
49
+ gaps.push({ id: q.id, group: q.group, question: q.text, answer: a, severity: q.severity, fix: q.fix });
50
+ }
51
+ // Most important first; at the same weight a "no" comes before a "not sure", then checklist order.
52
+ gaps.sort((x, y) => WEIGHT[y.severity] - WEIGHT[x.severity] || Number(x.answer !== "no") - Number(y.answer !== "no"));
53
+ return { answered: asked.length, total: QUESTIONS.length, inPlace: asked.length - gaps.length, score: Math.round((100 * got) / max), gaps };
54
+ }
55
+ export function readAnswer(raw) {
56
+ const t = raw.trim().toLowerCase();
57
+ if (/^y(es)?$/.test(t))
58
+ return "yes";
59
+ if (/^no?$/.test(t))
60
+ return "no";
61
+ if (t === "?" || /^(u|unsure|not sure|dk|don'?t know)$/.test(t))
62
+ return "unsure";
63
+ return null; // Enter skips the question
64
+ }
65
+ export async function askPeople(ask, write) {
66
+ write(`\nPeople and process: ${QUESTIONS.length} short questions about what no scan can see. Answer y, n or ? (not sure). Press Enter to skip one. Answers stay on this machine.\n`);
67
+ const out = {};
68
+ let group = "";
69
+ for (const q of QUESTIONS) {
70
+ if (q.group !== group)
71
+ write(`\n${(group = q.group)}\n`);
72
+ const a = readAnswer(await ask(` ${q.text} (y/n/?) `));
73
+ if (a)
74
+ out[q.id] = a;
75
+ }
76
+ return out;
77
+ }
@@ -0,0 +1,48 @@
1
+ // Ranks every finding by what breaks first, and turns code findings into map findings.
2
+ export function tierOf(f) {
3
+ if (f.risk !== "quantum-vulnerable")
4
+ return 1;
5
+ if ((f.primitive === "key-agreement" || f.primitive === "public-key-encryption") && f.internetFacing)
6
+ return 2;
7
+ if (f.primitive === "signature" && f.longLived)
8
+ return 3;
9
+ return 4;
10
+ }
11
+ const SEV = { critical: 0, high: 1, medium: 2, low: 3 };
12
+ export function rank(findings) {
13
+ return findings
14
+ .map((f) => ({ ...f, tier: tierOf(f) }))
15
+ .sort((a, b) => a.tier - b.tier || SEV[a.severity] - SEV[b.severity] || a.area.localeCompare(b.area) || a.target.localeCompare(b.target));
16
+ }
17
+ export function fromCodeFinding(f) {
18
+ return {
19
+ area: "code",
20
+ target: `${f.file}:${f.line}`,
21
+ ruleId: f.ruleId,
22
+ title: f.title,
23
+ algorithm: f.algorithm,
24
+ primitive: f.primitive,
25
+ risk: f.risk,
26
+ severity: f.severity,
27
+ fix: f.fix,
28
+ internetFacing: false,
29
+ keySize: f.keySize,
30
+ };
31
+ }
32
+ /** Back to the code scanner's shape, so the CycloneDX inventory builder can be reused. */
33
+ export function toFinding(f) {
34
+ return {
35
+ kind: f.risk === "secret" ? "secret" : f.risk === "exposed" || f.primitive === "setting" ? "config" : "crypto",
36
+ ruleId: f.ruleId,
37
+ title: f.title,
38
+ algorithm: f.algorithm,
39
+ primitive: f.primitive,
40
+ risk: f.risk,
41
+ severity: f.severity,
42
+ file: f.target,
43
+ line: 0,
44
+ snippet: "",
45
+ fix: f.fix,
46
+ keySize: f.keySize,
47
+ };
48
+ }