@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.
package/dist/infra.js ADDED
@@ -0,0 +1,557 @@
1
+ // Infrastructure config checks: Terraform/OpenTofu, CloudFormation, Kubernetes, Dockerfiles,
2
+ // and nginx/Apache/HAProxy configs. Finds weak TLS, non-quantum-safe key settings, encryption
3
+ // turned off, storage or ports open to the internet, and secrets written into config.
4
+ import { ALGORITHMS } from "./rules.js";
5
+ import { mask } from "./secrets.js";
6
+ /**
7
+ * Whether a pull request should read the whole file, not just the diff, for infrastructure checks.
8
+ * Settings like a security group's direction or ports sit a few lines away from the line that changed.
9
+ */
10
+ export function wantsFullFile(path, patch) {
11
+ const p = path.toLowerCase();
12
+ if (/(\.tf|\.tfvars|\.hcl|\.template)$/.test(p))
13
+ return true;
14
+ if (/(^|\/)(dockerfile|containerfile)[^/]*$|\.dockerfile$/.test(p))
15
+ return true;
16
+ if (/\.ya?ml$|\.json$/.test(p))
17
+ return /AWS::|AWSTemplateFormatVersion|SecurityGroup|apiVersion:|kind:\s*Secret|cert-manager/.test(patch);
18
+ return false;
19
+ }
20
+ export function infraType(path, lines) {
21
+ const p = path.toLowerCase();
22
+ const name = p.split("/").pop() ?? p;
23
+ if (/\.(tf|tfvars|hcl)$/.test(p))
24
+ return "terraform";
25
+ if (/^(dockerfile|containerfile)([.-].*)?$/.test(name) || /\.(dockerfile|containerfile)$/.test(name))
26
+ return "docker";
27
+ if (/\.(ya?ml|json|template)$/.test(p)) {
28
+ if (lines.some((l) => /AWSTemplateFormatVersion|["']?Type["']?\s*:\s*["']?AWS::/.test(l.text)))
29
+ return "cloudformation";
30
+ return /\.json$/.test(p) ? "json" : "yaml";
31
+ }
32
+ if (/\.(conf|cfg)$/.test(p) || /(^|\/)(nginx|apache2?|httpd|haproxy)[^/]*$/.test(p) || name === ".htaccess" || /(^|\/)sites-(available|enabled)\//.test(p))
33
+ return "webserver";
34
+ if (/\.(sh|bash)$/.test(p))
35
+ return "shell";
36
+ if (/\.(ini|toml|properties|env|cnf)$/.test(p))
37
+ return "config";
38
+ return null;
39
+ }
40
+ // ---------- shared helpers ----------
41
+ const SENSITIVE_PORTS = [21, 22, 23, 445, 1433, 1521, 2375, 2376, 2379, 3306, 3389, 5432, 5601, 5900, 5984, 6379, 7001, 8020, 9042, 9092, 9200, 9300, 11211, 27017];
42
+ const PORT_NAMES = { 22: "SSH", 3389: "remote desktop", 3306: "MySQL", 5432: "PostgreSQL", 1433: "SQL Server", 1521: "Oracle", 6379: "Redis", 27017: "MongoDB", 9200: "Elasticsearch", 2375: "Docker", 2376: "Docker", 2379: "etcd", 23: "Telnet", 21: "FTP", 445: "SMB", 5900: "VNC", 11211: "Memcached", 5601: "Kibana" };
43
+ const PLACEHOLDER = /(example|sample|dummy|changeme|change_me|placeholder|your[_-]|xxxx|\*\*\*\*|<[^>]+>|\$\{|\{\{|redacted|test|password|secret|var\.|local\.|module\.|data\.|todo|replace)/i;
44
+ function trim(t) {
45
+ const s = t.trim();
46
+ return s.length > 160 ? `${s.slice(0, 157)}...` : s;
47
+ }
48
+ /** Ports covered by a range, by name. Null when nothing sensitive is in range. */
49
+ function exposedPorts(from, to, allProtocols) {
50
+ if (allProtocols || (from === 0 && (to === 65535 || to === 0)))
51
+ return "all ports";
52
+ if (from === null || to === null || Number.isNaN(from) || Number.isNaN(to))
53
+ return null;
54
+ if (to - from >= 1000)
55
+ return "a wide port range";
56
+ const hit = SENSITIVE_PORTS.filter((p) => p >= from && p <= to);
57
+ if (!hit.length)
58
+ return null;
59
+ const names = hit.map((p) => (PORT_NAMES[p] ? `${PORT_NAMES[p]} (${p})` : `port ${p}`));
60
+ return names.slice(0, 2).join(" and ");
61
+ }
62
+ function portRange(s) {
63
+ const t = s.trim().replace(/["']/g, "");
64
+ if (t === "*" || t === "Any")
65
+ return [0, 65535];
66
+ const m = t.match(/^(\d{1,5})(?:\s*-\s*(\d{1,5}))?$/);
67
+ return m ? [Number(m[1]), Number(m[2] ?? m[1])] : null;
68
+ }
69
+ /** Innermost { } block around lines[idx], for HCL. Returns line indexes, inclusive. */
70
+ function hclBlock(lines, idx) {
71
+ let depth = 0;
72
+ let start = -1;
73
+ outer: for (let j = idx - 1; j >= 0; j--) {
74
+ const t = stripStrings(lines[j].text);
75
+ for (let k = t.length - 1; k >= 0; k--) {
76
+ if (t[k] === "}")
77
+ depth++;
78
+ else if (t[k] === "{") {
79
+ if (depth === 0) {
80
+ start = j;
81
+ break outer;
82
+ }
83
+ depth--;
84
+ }
85
+ }
86
+ }
87
+ if (start < 0)
88
+ return null;
89
+ depth = 0;
90
+ for (let j = start; j < lines.length; j++) {
91
+ for (const ch of stripStrings(lines[j].text)) {
92
+ if (ch === "{")
93
+ depth++;
94
+ else if (ch === "}") {
95
+ depth--;
96
+ if (depth === 0)
97
+ return { start, end: j };
98
+ }
99
+ }
100
+ }
101
+ return { start, end: lines.length - 1 };
102
+ }
103
+ /** The resource-level block (first line starts with resource/data/module) around lines[idx]. */
104
+ function hclResource(lines, idx) {
105
+ let b = hclBlock(lines, idx);
106
+ while (b && !/^\s*(resource|data|module)\b/.test(lines[b.start].text)) {
107
+ b = hclBlock(lines, b.start);
108
+ }
109
+ return b;
110
+ }
111
+ function stripStrings(s) {
112
+ return s.replace(/"(?:[^"\\]|\\.)*"/g, '""').replace(/#.*$|\/\/.*$/, "");
113
+ }
114
+ function textOf(lines, b) {
115
+ return lines.slice(b.start, b.end + 1).map((l) => l.text).join("\n");
116
+ }
117
+ function hclValue(block, key) {
118
+ const m = block.match(new RegExp(`^\\s*${key}\\s*=\\s*("?)([^"\\n]*)\\1\\s*(?:#.*)?$`, "m"));
119
+ return m ? m[2].trim() : null;
120
+ }
121
+ // ---------- TLS versions and ciphers ----------
122
+ /** TLS minor version named in a value like "TLSv1.2_2021", "TLS1_0", "Policy-Min-TLS-1-0-2019-07". */
123
+ export function tlsMinVersionIsWeak(value) {
124
+ const v = value.trim();
125
+ if (/^SSLv?[23]$/i.test(v))
126
+ return true;
127
+ if (/^ELBSecurityPolicy-20(1[56])-\d\d$/i.test(v))
128
+ return true; // old ALB defaults that allow TLS 1.0
129
+ const m = v.match(/TLS[-_ v]?1(?:[-._]?([0-3])(?!\d))?/i);
130
+ if (m)
131
+ return Number(m[1] ?? 0) < 2;
132
+ if (/^1[._]([01])$/.test(v))
133
+ return true;
134
+ return false;
135
+ }
136
+ const MIN_TLS_KEY = /(?:^|[\s"'{,.])(min_?tls_?version|minimum_tls_version|tls_min_version|min_tls|minimum_protocol_version|MinimumProtocolVersion|MinTlsVersion|MinimumTlsVersion|minimalTlsVersion|minTlsVersion|ssl_minimum_version|tls_security_policy|TLSSecurityPolicy|ssl_policy|SslPolicy|security_policy|SecurityPolicy|ssl-min-ver)["']?\s*[:=\s]\s*["']?([A-Za-z0-9._-]+)/i;
137
+ const PROTOCOL_LIST = /(?:^|[\s"'/])(ssl_protocols|SSLProtocol|ssl-protocols)["']?\s*[:=\s]\s*["']?([^;"'#\n]+)/i;
138
+ const CIPHER_LIST = /(?:^|[\s"'/])(ssl_ciphers|SSLCipherSuite|ssl-default-bind-ciphers|ssl-default-server-ciphers|ssl-ciphers)["']?\s*[:=\s]\s*["']?([^;"'#\n]+)/i;
139
+ function weakProtocols(directive, list) {
140
+ const tokens = list.split(/[\s,]+/).filter(Boolean);
141
+ const on = new Set();
142
+ const norm = (t) => t.replace(/^[+-]/, "").replace(/^TLSv1\.0$/i, "TLSv1").toUpperCase();
143
+ for (const t of tokens) {
144
+ if (/^all$/i.test(t.replace(/^\+/, "")))
145
+ ["SSLV3", "TLSV1", "TLSV1.1", "TLSV1.2", "TLSV1.3"].forEach((x) => on.add(x));
146
+ else if (t.startsWith("-") || t.startsWith("!"))
147
+ on.delete(norm(t.slice(1)));
148
+ else
149
+ on.add(norm(t));
150
+ }
151
+ if (/SSLProtocol/i.test(directive) && !tokens.length)
152
+ return [];
153
+ return [...on].filter((t) => /^(SSLV2|SSLV3|TLSV1|TLSV1\.1)$/.test(t));
154
+ }
155
+ function weakCiphers(list) {
156
+ const out = [];
157
+ for (const raw of list.split(/[:\s,]+/)) {
158
+ if (!raw || /^[!-]/.test(raw))
159
+ continue;
160
+ const m = raw.match(/(?:^|[-_+])(RC4|3DES|DES|DES-CBC3|CBC3|MD5|NULL|EXPORT|EXP|aNULL|eNULL|ADH|AECDH)(?:[-_+]|$)/i);
161
+ if (m)
162
+ out.push(raw);
163
+ }
164
+ return out;
165
+ }
166
+ const FIX = {
167
+ atRest: "Turn on encryption at rest, ideally with a customer-managed key.",
168
+ transit: "Require HTTPS or TLS for every connection.",
169
+ verify: "Keep certificate checks on. Add the right CA certificate instead of skipping verification.",
170
+ publicStore: "Block public access. Share files through signed links or a CDN with access control.",
171
+ publicDb: "Keep the database off the public internet and reach it through a private network.",
172
+ openPort: "Limit the source to known addresses or a VPN, or put it behind a private network.",
173
+ ciphers: "Allow only AES-GCM and ChaCha20 cipher suites.",
174
+ tls: "Require TLS 1.2 or later, ideally TLS 1.3.",
175
+ secret: "Move it to a secret store and reference it from there. Deleting it from the code leaves it in git history.",
176
+ };
177
+ function cryptoHit(line, algorithm, keySize) {
178
+ const info = ALGORITHMS[algorithm];
179
+ if (!info)
180
+ return null;
181
+ let { risk, severity, fix } = info;
182
+ let title = `${algorithm} is ${risk === "weak-now" ? "weak today" : "breakable by quantum computers"}`;
183
+ if (keySize !== undefined && algorithm.startsWith("RSA") && keySize < 2048) {
184
+ risk = "weak-now";
185
+ severity = "high";
186
+ title = `RSA-${keySize} is weak today and breakable by quantum computers`;
187
+ fix = "Use 3072-bit keys or larger now, then plan the move to post-quantum methods.";
188
+ }
189
+ return { line, kind: "crypto", algorithm, risk, severity, primitive: info.primitive, title, fix, keySize };
190
+ }
191
+ function exposed(line, algorithm, title, fix, severity = "high") {
192
+ return { line, kind: "config", algorithm, risk: "exposed", severity, primitive: "setting", title, fix };
193
+ }
194
+ function secretHit(line, value, name = "Hardcoded secret") {
195
+ return {
196
+ line,
197
+ kind: "secret",
198
+ algorithm: name,
199
+ risk: "secret",
200
+ severity: "critical",
201
+ primitive: "credential",
202
+ title: `${name} committed to the repository`,
203
+ fix: FIX.secret,
204
+ snippet: trim(line.text.split(value).join(mask(value))),
205
+ };
206
+ }
207
+ function keyAlgorithm(word) {
208
+ const w = word.toUpperCase();
209
+ if (/^RSA_(SIGN)/.test(w))
210
+ return "RSA signature";
211
+ if (/^RSA_(DECRYPT)/.test(w))
212
+ return "RSA encryption";
213
+ if (/^RSA/.test(w))
214
+ return "RSA";
215
+ if (/^(EC|ECC|ECDSA|EC_SIGN|P-?\d{3})/.test(w))
216
+ return "ECDSA";
217
+ if (/^ED25519$/.test(w))
218
+ return "Ed25519";
219
+ if (/^DSA$/.test(w))
220
+ return "DSA";
221
+ return null;
222
+ }
223
+ function rsaBitsOf(word) {
224
+ const m = word.match(/RSA[_A-Z]*?_(\d{4})/i);
225
+ return m ? Number(m[1]) : undefined;
226
+ }
227
+ export function scanInfra(path, lines) {
228
+ const type = infraType(path, lines);
229
+ const hits = [];
230
+ const add = (h) => h && hits.push(h);
231
+ // Kubernetes Secret manifests: track the current YAML document's kind.
232
+ let docKind = "";
233
+ let inSecretData = -1;
234
+ for (let i = 0; i < lines.length; i++) {
235
+ const line = lines[i];
236
+ const t = line.text;
237
+ if (t.length > 2000)
238
+ continue;
239
+ if (/^\s*(#|\/\/)/.test(t)) {
240
+ continue;
241
+ }
242
+ // --- TLS settings (any infra or config file) ---
243
+ if (type) {
244
+ const mm = t.match(MIN_TLS_KEY);
245
+ if (mm && tlsMinVersionIsWeak(mm[2]) && !(/^(ssl_policy|SslPolicy|security_policy|SecurityPolicy)$/i.test(mm[1]) && !/^(ELBSecurityPolicy|Policy-Min|TLS)/i.test(mm[2]))) {
246
+ add(cryptoHit(line, "TLS 1.0/1.1"));
247
+ }
248
+ const pl = t.match(PROTOCOL_LIST);
249
+ if (pl && weakProtocols(pl[1], pl[2]).length)
250
+ add(cryptoHit(line, "TLS 1.0/1.1"));
251
+ const cl = t.match(CIPHER_LIST);
252
+ if (cl && weakCiphers(cl[2]).length)
253
+ add(cryptoHit(line, "Weak TLS ciphers"));
254
+ }
255
+ // --- Commands that run in containers or provisioning scripts ---
256
+ if (type === "docker" || type === "shell" || type === "yaml") {
257
+ if (/\bcurl\s(?:[^|;&\n]*\s)?(-[a-zA-Z]*k[a-zA-Z]*|--insecure)(\s|$)/.test(t) || /\bwget\s[^\n]*--no-check-certificate/.test(t) || /\bnpm\s+config\s+set\s+strict-ssl\s+false/.test(t) || /http\.sslVerify\s+false/i.test(t)) {
258
+ add(exposed(line, "TLS verification off", "Certificate checks turned off", FIX.verify, "medium"));
259
+ }
260
+ const kg = t.match(/\bssh-keygen\b[^\n]*\s-t\s+(rsa|dsa|ecdsa|ed25519)\b/i);
261
+ if (kg) {
262
+ const b = t.match(/\s-b\s+(\d{3,5})\b/);
263
+ add(cryptoHit(line, kg[1].toLowerCase() === "ed25519" ? "Ed25519" : kg[1].toLowerCase() === "dsa" ? "DSA" : kg[1].toLowerCase() === "ecdsa" ? "ECDSA" : "RSA", b ? Number(b[1]) : undefined));
264
+ }
265
+ const os = t.match(/\bopenssl\s+(genrsa|req\b[^\n]*-newkey\s+(rsa|ec))/i);
266
+ if (os) {
267
+ const b = t.match(/(?:genrsa\b[^\n]*?\s|rsa:)(\d{3,5})\b/);
268
+ add(cryptoHit(line, os[2]?.toLowerCase() === "ec" ? "ECDSA" : "RSA", b ? Number(b[1]) : undefined));
269
+ }
270
+ }
271
+ if (type === "docker") {
272
+ const env = t.match(/^\s*(?:ENV|ARG)\s+([A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|ACCESS_KEY|PRIVATE_KEY)[A-Za-z0-9_]*)(?:=|\s+)["']?([^\s"'$]{8,})["']?/i);
273
+ if (env && !PLACEHOLDER.test(env[2]) && !/_(FILE|PATH|URL|NAME|URI|DIR|HOME)$/i.test(env[1]) && !/^(\/|\.{1,2}\/|~\/)/.test(env[2]))
274
+ add(secretHit(line, env[2]));
275
+ }
276
+ // --- Kubernetes ---
277
+ if (type === "yaml") {
278
+ if (/^---/.test(t)) {
279
+ docKind = "";
280
+ inSecretData = -1;
281
+ }
282
+ const k = t.match(/^kind:\s*["']?(\w+)/);
283
+ if (k)
284
+ docKind = k[1];
285
+ if (/insecure-skip-tls-verify:\s*true\b/.test(t))
286
+ add(exposed(line, "TLS verification off", "Certificate checks turned off", FIX.verify, "medium"));
287
+ const alg = t.match(/^\s*algorithm:\s*["']?(RSA|ECDSA|Ed25519)["']?\s*$/);
288
+ if (alg && lines.some((l) => /^\s*(privateKey|issuerRef|secretName):/.test(l.text) || /cert-manager\.io/.test(l.text)))
289
+ add(cryptoHit(line, keyAlgorithm(alg[1])));
290
+ const top = t.match(/^(data|stringData):\s*$/);
291
+ if (top)
292
+ inSecretData = docKind === "Secret" ? 0 : -1;
293
+ else if (inSecretData >= 0 && /^\S/.test(t))
294
+ inSecretData = -1;
295
+ else if (inSecretData >= 0) {
296
+ const kv = t.match(/^\s+([A-Za-z0-9_.-]+):\s*["']?([^\s"'#]+)["']?\s*$/);
297
+ if (kv && kv[2].length >= 8 && !PLACEHOLDER.test(kv[2]) && !PLACEHOLDER.test(decode(kv[2])))
298
+ add(secretHit(line, kv[2], "Kubernetes Secret value"));
299
+ }
300
+ }
301
+ // --- Terraform / OpenTofu ---
302
+ if (type === "terraform") {
303
+ let m;
304
+ if ((m = t.match(/^\s*(algorithm|key_algorithm|customer_master_key_spec|key_spec|key_type)\s*=\s*"([A-Za-z0-9_-]+)"/))) {
305
+ const word = m[2].replace(/-HSM$/i, "");
306
+ const isKeyContext = m[1] !== "algorithm" || /^(RSA|ECDSA|ED25519|RSA_|EC_SIGN|EC_P)/i.test(word);
307
+ const a = isKeyContext ? keyAlgorithm(word) : null;
308
+ if (a && !/^(SYMMETRIC|HMAC|GOOGLE_SYMMETRIC)/i.test(word)) {
309
+ const block = hclBlock(lines, i);
310
+ const bits = rsaBitsOf(word) ?? (block ? Number(hclValue(textOf(lines, block), "(?:rsa_bits|key_size)") ?? NaN) : NaN);
311
+ add(cryptoHit(line, a, Number.isFinite(bits) ? bits : undefined));
312
+ }
313
+ }
314
+ if ((m = t.match(/^\s*(storage_encrypted|encrypted|encryption_at_rest_enabled|at_rest_encryption_enabled|kms_encrypted|enable_encryption|server_side_encryption_enabled|enable_blob_encryption|enable_file_encryption)\s*=\s*false\b/))) {
315
+ add(exposed(line, "Encryption at rest off", "Stored data is not encrypted", FIX.atRest));
316
+ }
317
+ if (/^\s*enabled\s*=\s*false\b/.test(t)) {
318
+ const b = hclBlock(lines, i);
319
+ if (b && /^\s*(encrypt_at_rest|encryption_at_rest|server_side_encryption|node_to_node_encryption)\b/.test(lines[b.start].text)) {
320
+ add(exposed(line, /node_to_node/.test(lines[b.start].text) ? "Unencrypted traffic allowed" : "Encryption at rest off", "Encryption turned off", /node_to_node/.test(lines[b.start].text) ? FIX.transit : FIX.atRest));
321
+ }
322
+ }
323
+ if (/^\s*viewer_protocol_policy\s*=\s*"allow-all"/.test(t) || /^\s*(enable_https_traffic_only|https_traffic_only_enabled|https_only|transit_encryption_enabled|require_ssl)\s*=\s*false\b/.test(t) || /^\s*ssl_mode\s*=\s*"ALLOW_UNENCRYPTED_AND_ENCRYPTED"/.test(t)) {
324
+ add(exposed(line, "Unencrypted traffic allowed", "Plain, unencrypted connections are allowed", FIX.transit));
325
+ }
326
+ if (/^\s*(insecure|skip_tls_verify|insecure_skip_verify|tls_insecure_skip_verify|skip_cert_verification)\s*=\s*true\b/.test(t)) {
327
+ add(exposed(line, "TLS verification off", "Certificate checks turned off", FIX.verify, "medium"));
328
+ }
329
+ if (/^\s*(acl|predefined_acl|canned_acl)\s*=\s*"(public-read|public-read-write|authenticated-read|publicRead|publicReadWrite)"/.test(t) || /^\s*(block_public_acls|block_public_policy|ignore_public_acls|restrict_public_buckets)\s*=\s*false\b/.test(t) || /^\s*(allow_nested_items_to_be_public|allow_blob_public_access)\s*=\s*true\b/.test(t) || /^\s*container_access_type\s*=\s*"(blob|container)"/.test(t) || /^\s*(members?|member)\s*=\s*[^\n]*"(allUsers|allAuthenticatedUsers)"/.test(t)) {
330
+ add(exposed(line, "Public storage", "Storage or a resource is open to the public", FIX.publicStore));
331
+ }
332
+ if (/^\s*publicly_accessible\s*=\s*true\b/.test(t))
333
+ add(exposed(line, "Public database", "Database reachable from the internet", FIX.publicDb));
334
+ if (/^\s*(cidr_blocks|ipv6_cidr_blocks|cidr_ipv4|cidr_ipv6)\s*=\s*[^\n]*"(0\.0\.0\.0\/0|::\/0)"/.test(t))
335
+ add(awsOpenPort(lines, i));
336
+ // A list written over several lines: cidr_blocks = [\n "0.0.0.0/0"]
337
+ if (/^\s*"(0\.0\.0\.0\/0|::\/0)"/.test(t) && listKeyAbove(lines, i, /(cidr_blocks|ipv6_cidr_blocks)\s*=\s*\[/))
338
+ add(awsOpenPort(lines, i));
339
+ if (/^\s*source_ranges\s*=\s*[^\n]*"0\.0\.0\.0\/0"/.test(t))
340
+ add(gcpOpenPort(lines, i));
341
+ if (/^\s*cidr_block\s*=\s*"0\.0\.0\.0\/0"/.test(t)) {
342
+ const r = hclResource(lines, i);
343
+ if (r && /master_authorized_networks/.test(textOf(lines, r)))
344
+ add(openPortHit(line, "The Kubernetes API"));
345
+ }
346
+ if (/^\s*value\s*=\s*"0\.0\.0\.0\/0"/.test(t)) {
347
+ const b = hclBlock(lines, i);
348
+ if (b && /^\s*authorized_networks\b/.test(lines[b.start].text))
349
+ add(exposed(line, "Public database", "Database reachable from the internet", FIX.publicDb));
350
+ }
351
+ if ((/^\s*security_ips\s*=.*"0\.0\.0\.0(\/0)?"/.test(t) || (/^\s*"0\.0\.0\.0(\/0)?"/.test(t) && listKeyAbove(lines, i, /security_ips\s*=\s*\[/)))) {
352
+ add(exposed(line, "Public database", "Database reachable from the internet", FIX.publicDb));
353
+ }
354
+ if (/^\s*source_address_prefix\s*=\s*"(\*|Internet|0\.0\.0\.0\/0|Any)"/.test(t))
355
+ add(azureOpenPort(lines, i));
356
+ if ((m = t.match(/^\s*(password|master_password|admin_password|administrator_login_password|client_secret|secret_key|access_key|api_key|token|auth_token)\s*=\s*"([^"$]{8,})"/)) && !PLACEHOLDER.test(m[2]) && !/^[a-z_.]+$/.test(m[2])) {
357
+ add(secretHit(line, m[2]));
358
+ }
359
+ }
360
+ // --- CloudFormation (YAML or JSON) ---
361
+ if (type === "cloudformation") {
362
+ const kv = (key, val) => new RegExp(`["']?(?:${key})["']?\\s*:\\s*["']?(?:${val})["']?\\s*,?\\s*$`).test(t);
363
+ if (kv("StorageEncrypted|Encrypted|AtRestEncryptionEnabled|KmsEncrypted", "false"))
364
+ add(exposed(line, "Encryption at rest off", "Stored data is not encrypted", FIX.atRest));
365
+ if (kv("ViewerProtocolPolicy", "allow-all") || kv("TransitEncryptionEnabled", "false"))
366
+ add(exposed(line, "Unencrypted traffic allowed", "Plain, unencrypted connections are allowed", FIX.transit));
367
+ if (kv("AccessControl", "PublicRead|PublicReadWrite|AuthenticatedRead") || kv("BlockPublicAcls|BlockPublicPolicy|IgnorePublicAcls|RestrictPublicBuckets", "false"))
368
+ add(exposed(line, "Public storage", "Storage is open to the public", FIX.publicStore));
369
+ if (kv("PubliclyAccessible", "true"))
370
+ add(exposed(line, "Public database", "Database reachable from the internet", FIX.publicDb));
371
+ let m;
372
+ if ((m = t.match(/["']?(KeySpec|CustomerMasterKeySpec|KeyAlgorithm)["']?\s*:\s*["']?(RSA_\d+|ECC_[A-Z0-9_]+|EC_[a-z0-9]+)/)))
373
+ add(cryptoHit(line, keyAlgorithm(m[2]), rsaBitsOf(m[2])));
374
+ if (/["']?CidrIp(v6)?["']?\s*:\s*["']?(0\.0\.0\.0\/0|::\/0)/.test(t))
375
+ add(cfnOpenPort(lines, i));
376
+ if ((m = t.match(/["']?(MasterUserPassword|DBPassword|AdminPassword)["']?\s*:\s*["']?([^"'\s!{,]{8,})/)) && !PLACEHOLDER.test(m[2]))
377
+ add(secretHit(line, m[2]));
378
+ }
379
+ }
380
+ const seen = new Set();
381
+ return hits
382
+ .filter((h) => {
383
+ const k = `${h.line.no}:${h.algorithm}`;
384
+ if (seen.has(k))
385
+ return false;
386
+ seen.add(k);
387
+ return true;
388
+ })
389
+ .map((h) => ({
390
+ kind: h.kind,
391
+ ruleId: `infra-${h.algorithm.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`,
392
+ title: h.title,
393
+ algorithm: h.algorithm,
394
+ primitive: h.primitive,
395
+ risk: h.risk,
396
+ severity: h.severity,
397
+ file: path,
398
+ line: h.line.no,
399
+ snippet: h.snippet ?? trim(h.line.text),
400
+ fix: h.fix,
401
+ keySize: h.keySize,
402
+ }));
403
+ }
404
+ function decode(v) {
405
+ try {
406
+ return /^[A-Za-z0-9+/=]+$/.test(v) && v.length % 4 === 0 ? atob(v) : v;
407
+ }
408
+ catch {
409
+ return v;
410
+ }
411
+ }
412
+ function openPortHit(line, ports) {
413
+ return exposed(line, "Open to the internet", `${ports[0].toUpperCase()}${ports.slice(1)} open to the whole internet`, FIX.openPort);
414
+ }
415
+ function num(v) {
416
+ if (v === null)
417
+ return null;
418
+ return /^-?\d+$/.test(v.trim()) ? Number(v) : NaN;
419
+ }
420
+ /** Whether line i sits inside a multi-line list opened by a key matching re. */
421
+ function listKeyAbove(lines, i, re) {
422
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
423
+ const t = lines[j].text;
424
+ if (re.test(t))
425
+ return !/\]/.test(t);
426
+ if (/\]|=/.test(t))
427
+ return false;
428
+ }
429
+ return false;
430
+ }
431
+ const ICMP = /^(icmp|icmpv6|1|58)$/i;
432
+ const LOAD_BALANCER = /load.?balancer|\b(alb|elb|nlb|lb)\b|(alb|elb|nlb|lb)(sg|_sg|-sg|securitygroup)\b/i;
433
+ /** Text that names the security group around line i: its resource name, name and description. */
434
+ function groupLabel(lines, i) {
435
+ const out = [];
436
+ for (let j = i; j >= Math.max(0, i - 80); j--) {
437
+ const t = lines[j].text;
438
+ if (/\b(description|name|GroupDescription|GroupName)\b\s*[=:]/i.test(t))
439
+ out.push(t);
440
+ const tf = t.match(/^\s*resource\s+"[^"]+"\s+"([^"]+)"/);
441
+ if (tf)
442
+ return [tf[1], ...out].join(" ");
443
+ const cfn = t.match(/^\s{2,4}"?([A-Za-z0-9]+)"?\s*:\s*\{?\s*$/);
444
+ if (cfn && /Type"?\s*:\s*"?AWS::EC2::SecurityGroup/.test(lines.slice(j, j + 4).map((l) => l.text).join(" "))) {
445
+ for (let k = j; k <= Math.min(lines.length - 1, j + 12); k++)
446
+ if (/GroupDescription/.test(lines[k].text))
447
+ out.push(lines[k].text);
448
+ return [cfn[1], ...out].join(" ");
449
+ }
450
+ }
451
+ return out.join(" ");
452
+ }
453
+ /** A load balancer's group usually opens everything because the listeners pick the ports. */
454
+ function lbAllPorts(lines, i, ports) {
455
+ return ports === "all ports" && LOAD_BALANCER.test(groupLabel(lines, i));
456
+ }
457
+ function awsOpenPort(lines, i) {
458
+ const b = hclBlock(lines, i);
459
+ if (!b)
460
+ return null;
461
+ const header = lines[b.start].text;
462
+ const body = textOf(lines, b);
463
+ const isRule = /resource\s+"aws_security_group_rule"/.test(header);
464
+ if (!(/^\s*ingress\s*\{/.test(header) || /resource\s+"aws_vpc_security_group_ingress_rule"/.test(header) || (isRule && /^\s*type\s*=\s*"ingress"/m.test(body))))
465
+ return null;
466
+ const proto = hclValue(body, "(?:protocol|ip_protocol)");
467
+ if (proto && ICMP.test(proto))
468
+ return null;
469
+ const all = proto === "-1" || proto === "all";
470
+ const ports = exposedPorts(num(hclValue(body, "from_port")), num(hclValue(body, "to_port")), all);
471
+ if (!ports || lbAllPorts(lines, i, ports))
472
+ return null;
473
+ return openPortHit(lines[i], ports);
474
+ }
475
+ function gcpOpenPort(lines, i) {
476
+ const r = hclResource(lines, i);
477
+ if (!r || !/resource\s+"google_compute_firewall"/.test(lines[r.start].text))
478
+ return null;
479
+ const body = textOf(lines, r);
480
+ if (/^\s*direction\s*=\s*"EGRESS"/m.test(body))
481
+ return null;
482
+ const allowBlocks = [...body.matchAll(/allow\s*\{([^}]*)\}/g)].map((m) => m[1]);
483
+ for (const a of allowBlocks) {
484
+ const proto = hclValue(a, "protocol");
485
+ const portsList = a.match(/ports\s*=\s*\[([^\]]*)\]/);
486
+ if (proto === "all" || ((proto === "tcp" || proto === "udp") && !portsList))
487
+ return openPortHit(lines[i], "all ports");
488
+ for (const p of portsList?.[1].split(",") ?? []) {
489
+ const pr = portRange(p);
490
+ const hit = pr && exposedPorts(pr[0], pr[1], false);
491
+ if (hit)
492
+ return openPortHit(lines[i], hit);
493
+ }
494
+ }
495
+ return null;
496
+ }
497
+ function azureOpenPort(lines, i) {
498
+ const b = hclBlock(lines, i);
499
+ if (!b)
500
+ return null;
501
+ const body = textOf(lines, b);
502
+ if (!/^\s*direction\s*=\s*"Inbound"/m.test(body) || !/^\s*access\s*=\s*"Allow"/m.test(body))
503
+ return null;
504
+ const ranges = [];
505
+ const single = hclValue(body, "destination_port_range");
506
+ if (single)
507
+ ranges.push(single);
508
+ const multi = body.match(/destination_port_ranges\s*=\s*\[([^\]]*)\]/);
509
+ if (multi)
510
+ ranges.push(...multi[1].split(","));
511
+ for (const p of ranges) {
512
+ const pr = portRange(p);
513
+ const hit = pr && exposedPorts(pr[0], pr[1], false);
514
+ if (hit)
515
+ return openPortHit(lines[i], hit);
516
+ }
517
+ return null;
518
+ }
519
+ function cfnOpenPort(lines, i) {
520
+ // Look at the list item around the CidrIp line, bounded by neighbouring CidrIp lines.
521
+ const near = [];
522
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
523
+ if (/CidrIp|^\s*-\s|\{\s*$/.test(lines[j].text) && j !== i) {
524
+ near.push(lines[j].text);
525
+ if (/CidrIp/.test(lines[j].text) || /^\s*-\s/.test(lines[j].text))
526
+ break;
527
+ continue;
528
+ }
529
+ near.push(lines[j].text);
530
+ }
531
+ for (let j = i + 1; j <= Math.min(lines.length - 1, i + 6); j++) {
532
+ if (/CidrIp|^\s*-\s/.test(lines[j].text))
533
+ break;
534
+ near.push(lines[j].text);
535
+ }
536
+ const ctx = near.join("\n") + "\n" + lines[i].text;
537
+ // The nearest section or resource type above says whether this is an inbound rule.
538
+ let dir = null;
539
+ for (let j = i; j >= Math.max(0, i - 60) && !dir; j--) {
540
+ const m = lines[j].text.match(/SecurityGroup(Ingress|Egress)/);
541
+ if (m)
542
+ dir = m[1];
543
+ }
544
+ if (dir !== "Ingress")
545
+ return null;
546
+ const val = (k) => {
547
+ const m = ctx.match(new RegExp(`["']?${k}["']?\\s*:\\s*["']?(-?\\w+)`));
548
+ return m ? m[1] : null;
549
+ };
550
+ const proto = val("IpProtocol");
551
+ if (proto && ICMP.test(proto))
552
+ return null;
553
+ const ports = exposedPorts(num(val("FromPort")), num(val("ToPort")), proto === "-1" || proto === "all");
554
+ if (!ports || lbAllPorts(lines, i, ports))
555
+ return null;
556
+ return openPortHit(lines[i], ports);
557
+ }
@@ -0,0 +1,22 @@
1
+ // Activity log: every connection and every file the encryption map reads, with time, target and reason.
2
+ // Written next to the report, so a customer can hand it to their security team.
3
+ import { appendFileSync } from "node:fs";
4
+ export class ActivityLog {
5
+ entries = [];
6
+ file;
7
+ constructor(file) {
8
+ this.file = file;
9
+ }
10
+ record(area, target, what) {
11
+ const line = `${new Date().toISOString()} ${area.padEnd(5)} ${target} ${what}`;
12
+ this.entries.push(line);
13
+ if (this.file) {
14
+ try {
15
+ appendFileSync(this.file, line + "\n");
16
+ }
17
+ catch {
18
+ // the log in memory still goes into the report
19
+ }
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,50 @@
1
+ // The permission card for each area: what it touches, what it reads, what it never does.
2
+ // Shown before an area runs. The answer is no unless the person says yes.
3
+ const list = (t) => (t.length <= 4 ? t.join(", ") : `${t.slice(0, 3).join(", ")} and ${t.length - 3} more`);
4
+ export const CARDS = {
5
+ code: {
6
+ area: "code",
7
+ title: "Code and config",
8
+ touch: (t) => `the files in ${list(t)}.`,
9
+ read: "source code and infrastructure config, in memory, to find encryption, leaked keys and exposed settings.",
10
+ never: "change a file, run any code, or send code anywhere.",
11
+ cost: "Reads files only. No network connections.",
12
+ },
13
+ web: {
14
+ area: "web",
15
+ title: "Websites and public services",
16
+ touch: (t) => `${t.length} address${t.length === 1 ? "" : "es"} (${list(t)}), each under a domain you proved you own with a DNS record.`,
17
+ read: "the encryption each one offers when connecting, the same handshake a browser makes, and its certificate. For SSH addresses, the settings the server announces before any login.",
18
+ never: "log in, test for vulnerabilities, send attack traffic, or touch any address you haven't proved.",
19
+ cost: "About 6 connections per address, one at a time.",
20
+ },
21
+ network: {
22
+ area: "network",
23
+ title: "Network and connected equipment",
24
+ touch: (t) => `the addresses in ${list(t)}: private ranges on your own network only, at most 1,024 addresses.`,
25
+ read: "which of about 30 common ports answer on each device, the title of any web page they serve, the certificate on secure admin pages, and the router's list of automatic port forwards (UPnP), if it publishes one.",
26
+ never: "log in, try a password, send commands to equipment, change a setting, or touch any address outside these ranges.",
27
+ cost: "One connection at a time per device, a few a second. Usually a few minutes.",
28
+ warning: "Some older industrial, medical or building controllers can misbehave even when gently connected to. List any under exclude in the scope file, or answer no and skip this area.",
29
+ },
30
+ host: {
31
+ area: "host",
32
+ title: "This machine",
33
+ touch: () => "this computer only.",
34
+ read: "SSH and TLS settings, Windows encryption settings, the machine's own certificates, and the type and size of public key files.",
35
+ never: "change a setting, read a private key, or connect to anything.",
36
+ cost: "Reads local settings only. No network connections.",
37
+ },
38
+ };
39
+ export function cardText(card, targets) {
40
+ const lines = [
41
+ card.title,
42
+ ` What I'll touch: ${card.touch(targets)}`,
43
+ ` What I read: ${card.read}`,
44
+ ` What I never do: ${card.never}`,
45
+ ` ${card.cost}`,
46
+ ];
47
+ if (card.warning)
48
+ lines.push(` ${card.warning}`);
49
+ return lines.join("\n");
50
+ }