@hardkeel/benthic 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/LICENSE +92 -0
- package/NOTICE +16 -0
- package/README.md +424 -2
- package/action.yml +54 -0
- package/dist/agility.js +80 -0
- package/dist/badge.js +62 -0
- package/dist/baseline.js +81 -0
- package/dist/cbom-diff.js +273 -0
- package/dist/cbom.js +418 -0
- package/dist/cli.js +834 -0
- package/dist/cloud-aws-services.js +375 -0
- package/dist/cloud-aws.js +354 -0
- package/dist/cloud-azure-services.js +73 -0
- package/dist/cloud-azure.js +144 -0
- package/dist/cloud-common.js +242 -0
- package/dist/cloud-gcp-services.js +90 -0
- package/dist/cloud-gcp.js +150 -0
- package/dist/comments.js +138 -0
- package/dist/community-rules.js +37 -0
- package/dist/community.js +30 -0
- package/dist/deps.js +406 -0
- package/dist/der.js +571 -0
- package/dist/evidence-cli.js +235 -0
- package/dist/evidence-live.js +109 -0
- package/dist/evidence.js +512 -0
- package/dist/ignore.js +90 -0
- package/dist/image.js +1224 -0
- package/dist/infra.js +635 -0
- package/dist/inventory.js +277 -0
- package/dist/map-activity.js +24 -0
- package/dist/map-areas.js +60 -0
- package/dist/map-cloud-keys.js +110 -0
- package/dist/map-cloud.js +34 -0
- package/dist/map-ct.js +107 -0
- package/dist/map-host.js +335 -0
- package/dist/map-network.js +520 -0
- package/dist/map-people.js +79 -0
- package/dist/map-rank.js +70 -0
- package/dist/map-report.js +304 -0
- package/dist/map-run.js +327 -0
- package/dist/map-sarif.js +61 -0
- package/dist/map-signin.js +247 -0
- package/dist/map-types.js +19 -0
- package/dist/map-web.js +666 -0
- package/dist/native.js +168 -0
- package/dist/policy.js +221 -0
- package/dist/pqc.js +46 -0
- package/dist/profile.js +65 -0
- package/dist/project.js +928 -0
- package/dist/prose.js +159 -0
- package/dist/protocols.js +207 -0
- package/dist/registry.js +326 -0
- package/dist/report.js +190 -0
- package/dist/rules.js +230 -0
- package/dist/sarif-common.js +30 -0
- package/dist/sarif.js +114 -0
- package/dist/scan.js +601 -0
- package/dist/score.js +124 -0
- package/dist/secrets.js +192 -0
- package/dist/share-config.js +129 -0
- package/dist/share-lists.js +19 -0
- package/dist/share.js +125 -0
- package/dist/sonar.js +83 -0
- package/dist/structure.js +218 -0
- package/dist/suites.js +402 -0
- package/dist/tls-check.js +122 -0
- package/dist/types.js +4 -0
- package/dist/walk.js +78 -0
- package/dist/yaml.js +173 -0
- package/package.json +73 -4
package/dist/scan.js
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
// SPDX-License-Identifier: PolyForm-Shield-1.0.0
|
|
2
|
+
// Copyright 2026 Hard Keel (https://hardkeel.com)
|
|
3
|
+
// Core scanner: runs crypto and secret rules over file contents.
|
|
4
|
+
import { ALGORITHMS, CRYPTO_RULES, curveIn, langFor } from "./rules.js";
|
|
5
|
+
import { findPem } from "./der.js";
|
|
6
|
+
import { findLibraries } from "./deps.js";
|
|
7
|
+
import { COMMENT_LINE, blankRegexLiterals, stripTrailingComment } from "./comments.js";
|
|
8
|
+
import { fileConstants, statementAt, substitute, unaliasPython } from "./structure.js";
|
|
9
|
+
import { goModules, projectContext } from "./project.js";
|
|
10
|
+
import { scanInfra } from "./infra.js";
|
|
11
|
+
import { entropy, findSecrets, mask, PROVIDER_RULES, redactSecrets } from "./secrets.js";
|
|
12
|
+
import { findPqc } from "./pqc.js";
|
|
13
|
+
import { findInventory } from "./inventory.js";
|
|
14
|
+
import { findProtocols } from "./protocols.js";
|
|
15
|
+
import { communityRulesFor } from "./community.js";
|
|
16
|
+
import { LOCALE_PATH, inDetectionTable, inProse, isTranslationFile } from "./prose.js";
|
|
17
|
+
const MAX_LINE = 2000;
|
|
18
|
+
const TYPES_FILE = /\.d\.[cm]?ts$/;
|
|
19
|
+
const DOC_FILE = /\.(md|mdx|rst|txt|html?|adoc)$/i;
|
|
20
|
+
// Test code is full of throwaway keys and passwords, including fakes in real token formats, so no secret counts there.
|
|
21
|
+
export const TEST_PATH = /(^|\/)(tests?|suites|__tests__|__snapshots__|testdata|test-data|testing|test[-_]?(?:utils?|helpers?|support|env|suite|fixtures?|resources?|data)|e2e[-_][a-z0-9_-]+|[a-z0-9_-]+[-_]tests?|(?!(?:la|con|at|pro|de)test\/)[a-z0-9]+test|fixtures?|spec|specs|mocks?|e2e|integration[-_]?tests?|vectors|test[-_]?vectors|[a-z0-9_]+_vectors)\/|(_test\.go|_test\.py|\.(test|spec)\.[cm]?[jt]sx?)$|(^|\/)test[-_][^/]*$|(^|\/)testing[-_]?utils?\.[a-z]+$|(^|\/)fixtures?\.[cm]?[jt]sx?$|^integration\//i;
|
|
22
|
+
// Example and tutorial code, which is documentation in code form.
|
|
23
|
+
// Translation files: "password" and "token" there are labels shown to people.
|
|
24
|
+
export { LOCALE_PATH } from "./prose.js";
|
|
25
|
+
// Example settings files (.env.example), API specs and docs-site configs (public search keys).
|
|
26
|
+
export const EXAMPLE_FILE = /\.(example|sample|template|tmpl|dist)$|(^|\/)\.env\.(example|sample|template)|(^|\/)(openapi|swagger)[^/]*\.(ya?ml|json)$|(^|\/)docusaurus\.config\.[cm]?[jt]s$|\.stories\.[cm]?[jt]sx?$|(^|\/)\.secrets\.baseline$/i;
|
|
27
|
+
export const EXAMPLE_PATH = /(^|\/)(docs?_src|docs?|examples?|samples?|tutorials?)\//i;
|
|
28
|
+
const LOOSE_SECRET_RULES = new Set(["private-key", "generic-assignment", "env-assignment", "db-url-password"]);
|
|
29
|
+
const LONG_LINE_SECRET_RULES = new Set(["private-key", ...PROVIDER_RULES]);
|
|
30
|
+
const SKIP_PATH = /(^|\/)(node_modules|vendor|dist|build|\.git|__pycache__|\.venv|venv|target)\//;
|
|
31
|
+
const SKIP_FILE = /(\.min\.js|\.map|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|go\.sum|\.lock)$/;
|
|
32
|
+
// A settings key that lists what is NOT allowed: a line there forbids an algorithm, it doesn't use it.
|
|
33
|
+
const DENY_KEY = /(^|[^a-z])(deny|denied|disallow|disallowed|forbid|forbidden|block|blocked|blocklist|blacklist|reject|rejected|exclude|excluded|ban|banned|disable|disabled|unsupported|weak|deprecated|not_allowed)([^a-z]|$)/;
|
|
34
|
+
/** Whether a config line's key (the text before its first : or =) names a deny list. */
|
|
35
|
+
export function deniesOnLine(line) {
|
|
36
|
+
const key = line.split(/[:=]/)[0].replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
|
|
37
|
+
return DENY_KEY.test(key);
|
|
38
|
+
}
|
|
39
|
+
/** CycloneDX and SARIF documents, including this tool's own output: they list algorithms, they don't use them. */
|
|
40
|
+
export function isInventoryDocument(path, content) {
|
|
41
|
+
if (!/\.(json|sarif|cdx|xml)$/i.test(path))
|
|
42
|
+
return false;
|
|
43
|
+
const head = content.slice(0, 4096);
|
|
44
|
+
return /"bomFormat"\s*:\s*"CycloneDX"|<bom\s[^>]*xmlns="http:\/\/cyclonedx\.org|"\$schema"\s*:\s*"[^"]*sarif[^"]*"|"version"\s*:\s*"2\.1\.0"[\s\S]{0,400}"runs"\s*:/.test(head);
|
|
45
|
+
}
|
|
46
|
+
export function shouldScan(path) {
|
|
47
|
+
if (SKIP_PATH.test(path) || SKIP_FILE.test(path))
|
|
48
|
+
return false;
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
/** A source line for output: secrets masked first, then shortened, so a cut can't leave part of a secret showing. */
|
|
52
|
+
export function trimSnippet(line) {
|
|
53
|
+
const t = redactSecrets(line).trim();
|
|
54
|
+
return t.length > 160 ? `${t.slice(0, 157)}...` : t;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Scan one file.
|
|
58
|
+
* @param onlyLines if given, only report findings on these 1-based line numbers
|
|
59
|
+
* (used for pull requests: only what the change added).
|
|
60
|
+
*/
|
|
61
|
+
export function scanFile(path, content, onlyLines) {
|
|
62
|
+
if (content.includes("\u0000") || isInventoryDocument(path, content))
|
|
63
|
+
return []; // binary, or a CBOM or SARIF report
|
|
64
|
+
const lines = content.split(/\r?\n/).map((text, i) => ({ no: i + 1, text }));
|
|
65
|
+
// Scan the whole file so settings see their surrounding block, then keep only the lines asked for.
|
|
66
|
+
const findings = scanLines(path, lines);
|
|
67
|
+
return onlyLines ? findings.filter((f) => onlyLines.has(f.line)) : findings;
|
|
68
|
+
}
|
|
69
|
+
/** Scan the lines a pull request added, straight from GitHub's patch text. No file download needed. */
|
|
70
|
+
export function scanPatch(path, patch) {
|
|
71
|
+
return scanLines(path, patchAddedLines(patch));
|
|
72
|
+
}
|
|
73
|
+
/** Each line as code (no comment after it, no regular expression literal in it) and the file's constants. */
|
|
74
|
+
export function prepareLines(path, lines) {
|
|
75
|
+
const lang = langFor(path);
|
|
76
|
+
let codeLines = lines.map((l) => (l.text.length > MAX_LINE || COMMENT_LINE.test(l.text) ? "" : blankRegexLiterals(stripTrailingComment(l.text, path), path)));
|
|
77
|
+
if (lang === "python")
|
|
78
|
+
codeLines = unaliasPython(codeLines);
|
|
79
|
+
const consts = TYPES_FILE.test(path) || TEST_PATH.test(path) ? new Map() : fileConstants(path, codeLines);
|
|
80
|
+
return { codeLines, consts };
|
|
81
|
+
}
|
|
82
|
+
/** Worse first: broken today before quantum-breakable, then the smaller key. */
|
|
83
|
+
function worse(a, b) {
|
|
84
|
+
const r = (f) => (f.risk === "weak-now" ? 0 : 1);
|
|
85
|
+
if (r(a) !== r(b))
|
|
86
|
+
return r(a) < r(b);
|
|
87
|
+
return (a.keySize ?? Infinity) < (b.keySize ?? Infinity);
|
|
88
|
+
}
|
|
89
|
+
function viaOf(path, used) {
|
|
90
|
+
const out = [];
|
|
91
|
+
for (const u of used) {
|
|
92
|
+
const steps = u.via ?? (u.name ? [{ file: path, line: u.line, note: `${u.name} = ${u.value}` }] : []);
|
|
93
|
+
for (const s of steps)
|
|
94
|
+
if (!out.some((o) => o.file === s.file && o.line === s.line))
|
|
95
|
+
out.push(s);
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
export function scanLines(path, lines, ctx = {}) {
|
|
100
|
+
if (!shouldScan(path))
|
|
101
|
+
return [];
|
|
102
|
+
const lang = langFor(path);
|
|
103
|
+
const rules = [...CRYPTO_RULES.filter((r) => r.langs.includes("any") || (lang !== null && r.langs.includes(lang))), ...communityRulesFor(path)];
|
|
104
|
+
const findings = [];
|
|
105
|
+
const prep = ctx.prepared ?? prepareLines(path, lines);
|
|
106
|
+
const codeLines = prep.codeLines;
|
|
107
|
+
const importBlock = importBlockLines(lang, codeLines);
|
|
108
|
+
// This file's constants, and the ones it imports from other files (its own win on a clash).
|
|
109
|
+
const consts = ctx.project?.imported.size && !TEST_PATH.test(path) && !TYPES_FILE.test(path) ? new Map([...ctx.project.imported, ...prep.consts]) : prep.consts;
|
|
110
|
+
const scopes = TEST_PATH.test(path) ? [] : (ctx.project?.params ?? []);
|
|
111
|
+
// A translation catalog is text shown to people: it names algorithms, it doesn't use them.
|
|
112
|
+
const catalog = isTranslationFile(path, lines.map((l) => l.text));
|
|
113
|
+
// Findings that came from a filled-in constant or a joined call, and what they rest on.
|
|
114
|
+
const derived = new Map();
|
|
115
|
+
/** Run the encryption rules over one piece of code, reported at lines[idx]. */
|
|
116
|
+
const matchCrypto = (code, raw, idx) => {
|
|
117
|
+
const out = [];
|
|
118
|
+
for (const rule of rules) {
|
|
119
|
+
// One line can name two algorithms through the same rule: {"default": "ES256", "legacy": "RS256"}.
|
|
120
|
+
const seen = new Set();
|
|
121
|
+
for (const m of matchesOf(code, rule.pattern)) {
|
|
122
|
+
const algorithm = typeof rule.algorithm === "string" ? rule.algorithm : rule.algorithm(m);
|
|
123
|
+
if (!algorithm || seen.has(algorithm))
|
|
124
|
+
continue;
|
|
125
|
+
// A sentence that names it ("Your files are protected with ML-KEM-768") doesn't use it.
|
|
126
|
+
if (inProse(code, m.index ?? 0, (m.index ?? 0) + m[0].length, path))
|
|
127
|
+
continue;
|
|
128
|
+
seen.add(algorithm);
|
|
129
|
+
const info = ALGORITHMS[algorithm];
|
|
130
|
+
if (!info)
|
|
131
|
+
continue;
|
|
132
|
+
// Python's usedforsecurity=False marks a hash that is only a checksum.
|
|
133
|
+
if (info.primitive === "hash" && /usedforsecurity\s*=\s*False/.test(code + raw))
|
|
134
|
+
continue;
|
|
135
|
+
// MD5 and SHA-1 are mostly used for checksums, cache keys and ETags, which are fine.
|
|
136
|
+
// Only flag them where the code around them is about passwords, signing, tokens and the like.
|
|
137
|
+
if ((algorithm === "MD5" || algorithm === "SHA-1") && !weakHashForSecurity(raw, lines, idx))
|
|
138
|
+
continue;
|
|
139
|
+
let keySize;
|
|
140
|
+
if (rule.keySize) {
|
|
141
|
+
const k = code.match(rule.keySize);
|
|
142
|
+
if (k)
|
|
143
|
+
keySize = Number(k[1]);
|
|
144
|
+
}
|
|
145
|
+
const detail = rule.detail?.(m) ?? {};
|
|
146
|
+
if (keySize === undefined && detail.keySize)
|
|
147
|
+
keySize = detail.keySize;
|
|
148
|
+
let curve = detail.curve;
|
|
149
|
+
if (!curve && /^(EC|ECDSA|ECDH)$/.test(algorithm))
|
|
150
|
+
curve = /\.(sol|vy)$/i.test(path) ? "secp256k1" : curveIn(code);
|
|
151
|
+
out.push(withKeySize({
|
|
152
|
+
kind: "crypto",
|
|
153
|
+
ruleId: rule.id,
|
|
154
|
+
title: `${algorithm} is ${info.risk === "weak-now" ? "weak today" : "breakable by quantum computers"}`,
|
|
155
|
+
algorithm,
|
|
156
|
+
primitive: info.primitive,
|
|
157
|
+
risk: info.risk,
|
|
158
|
+
severity: info.severity,
|
|
159
|
+
file: path,
|
|
160
|
+
line: lines[idx].no,
|
|
161
|
+
snippet: trimSnippet(raw),
|
|
162
|
+
fix: info.fix,
|
|
163
|
+
keySize,
|
|
164
|
+
...(curve ? { curve } : {}),
|
|
165
|
+
...(detail.hash ? { hash: detail.hash } : {}),
|
|
166
|
+
}));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
};
|
|
171
|
+
/** Keep a finding from a filled-in constant or a joined call, unless the line already says it. */
|
|
172
|
+
const addDerived = (f, how) => {
|
|
173
|
+
const same = findings.find((x) => x.kind === "crypto" && x.line === f.line && x.algorithm === f.algorithm);
|
|
174
|
+
if (same) {
|
|
175
|
+
refine(same, f);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
findings.push(f);
|
|
179
|
+
derived.set(f, how);
|
|
180
|
+
};
|
|
181
|
+
/** Findings from a filled-in line, each with what it rests on. */
|
|
182
|
+
const fromSub = (text, raw, idx, used, span) => {
|
|
183
|
+
for (const f of matchCrypto(text, raw, idx)) {
|
|
184
|
+
const via = viaOf(path, used);
|
|
185
|
+
if (via.length)
|
|
186
|
+
f.via = via;
|
|
187
|
+
addDerived(f, { from: used.filter((u) => !u.file).map((u) => u.line), ...(span ? { span } : {}), sources: via.filter((v) => v.file !== path || used.some((u) => u.file)) });
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
for (let idx = 0; idx < lines.length; idx++) {
|
|
191
|
+
const { no: lineNo, text: raw } = lines[idx];
|
|
192
|
+
// A very long line (minified code, a one-line JSON key file) is only checked for a service's own token formats and private keys.
|
|
193
|
+
const longLine = raw.length > MAX_LINE;
|
|
194
|
+
// Secrets: every text file.
|
|
195
|
+
for (const hit of findSecrets(raw, path, longLine ? LONG_LINE_SECRET_RULES : undefined)) {
|
|
196
|
+
// A private-key header only counts when real key material follows it (docs often show "XXXX").
|
|
197
|
+
if (hit.rule.id === "private-key" && !hasKeyMaterial(raw, lines[idx + 1]))
|
|
198
|
+
continue;
|
|
199
|
+
// Docs are full of example passwords; only specific token formats count there.
|
|
200
|
+
if ((hit.rule.id === "generic-assignment" || hit.rule.id === "env-assignment") && (DOC_FILE.test(path) || LOCALE_PATH.test(path) || TYPES_FILE.test(path) || COMMENT_LINE.test(raw)))
|
|
201
|
+
continue;
|
|
202
|
+
if (hit.rule.id === "db-url-password" && DOC_FILE.test(path))
|
|
203
|
+
continue;
|
|
204
|
+
// Test code is full of throwaway passwords and keys, but a service's own live token format counts there too.
|
|
205
|
+
if (TEST_PATH.test(path) && !(PROVIDER_RULES.has(hit.rule.id) && looksLive(hit.value)))
|
|
206
|
+
continue;
|
|
207
|
+
if (LOOSE_SECRET_RULES.has(hit.rule.id) && (EXAMPLE_PATH.test(path) || EXAMPLE_FILE.test(path) || DOC_FILE.test(path)))
|
|
208
|
+
continue;
|
|
209
|
+
findings.push({
|
|
210
|
+
kind: "secret",
|
|
211
|
+
ruleId: hit.rule.id,
|
|
212
|
+
title: `${hit.rule.name} committed to the repository`,
|
|
213
|
+
algorithm: hit.rule.name,
|
|
214
|
+
primitive: "credential",
|
|
215
|
+
risk: "secret",
|
|
216
|
+
severity: "critical",
|
|
217
|
+
file: path,
|
|
218
|
+
line: lineNo,
|
|
219
|
+
snippet: trimSnippet(raw.split(hit.value).join(mask(hit.value))),
|
|
220
|
+
fix: "Revoke it and issue a new one, then load it from a secret store. Deleting it from the code leaves it in git history.",
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
if (longLine)
|
|
224
|
+
continue;
|
|
225
|
+
// Crypto: language-scoped rules. Type declarations and comments describe code; they don't run it.
|
|
226
|
+
if (TYPES_FILE.test(path) || COMMENT_LINE.test(raw))
|
|
227
|
+
continue;
|
|
228
|
+
// In settings, a deny list names what is turned off.
|
|
229
|
+
if ((lang === "config" || lang === "any") && deniesOnLine(raw))
|
|
230
|
+
continue;
|
|
231
|
+
// Encryption in test code is not what ships, so it stays out of the inventory and the check.
|
|
232
|
+
if (TEST_PATH.test(path))
|
|
233
|
+
continue;
|
|
234
|
+
if (catalog)
|
|
235
|
+
continue;
|
|
236
|
+
// A comment after the code describes it, and a regular expression only names an algorithm.
|
|
237
|
+
const code = codeLines[idx];
|
|
238
|
+
if (!code.trim())
|
|
239
|
+
continue;
|
|
240
|
+
// An import names a module; the code that uses it is what counts.
|
|
241
|
+
if (importBlock.has(idx) || (lang && IMPORT_LINE[lang]?.test(code)))
|
|
242
|
+
continue;
|
|
243
|
+
// A detection rule or a finding record: { id: "ecdh", name: "ECDH", severity: "high" } looks for ECDH.
|
|
244
|
+
if (inDetectionTable(codeLines, idx))
|
|
245
|
+
continue;
|
|
246
|
+
const direct = matchCrypto(code, raw, idx);
|
|
247
|
+
findings.push(...direct);
|
|
248
|
+
// The same line with the file's constants filled in: key_size=KEY_BITS, getInstance(TRANSFORM).
|
|
249
|
+
const sub = substitute(code, consts);
|
|
250
|
+
if (sub)
|
|
251
|
+
fromSub(sub.text, raw, idx, sub.used);
|
|
252
|
+
// A call that runs over several lines, read as one.
|
|
253
|
+
const st = statementAt(codeLines, idx);
|
|
254
|
+
const span = st && lines[st.lastIdx].no - lineNo === st.lastIdx - idx ? [lineNo, lines[st.lastIdx].no] : undefined;
|
|
255
|
+
// A call over several lines is read as one, unless part of it is a detection rule or finding record.
|
|
256
|
+
if (st && span && !codeLines.slice(idx, st.lastIdx + 1).some((_, k) => inDetectionTable(codeLines, idx + k))) {
|
|
257
|
+
const s2 = substitute(st.text, consts);
|
|
258
|
+
fromSub(s2 ? s2.text : st.text, raw, idx, s2 ? s2.used : [], span);
|
|
259
|
+
}
|
|
260
|
+
// Inside a function: the values its callers pass in, worst first.
|
|
261
|
+
const scope = scopes.length ? innermost(scopes, idx) : undefined;
|
|
262
|
+
if (scope) {
|
|
263
|
+
const texts = st && span ? [code, st.text] : [code];
|
|
264
|
+
const names = [...scope.values.keys()].filter((n) => texts.some((t) => new RegExp(`(?<![\\w$.])${n.replace(/\$/g, "\\$")}(?![\\w$])`).test(t)));
|
|
265
|
+
if (names.length) {
|
|
266
|
+
const best = new Map();
|
|
267
|
+
for (const combo of combos(names.map((n) => scope.values.get(n).map((k) => ({ ...k, name: n }))))) {
|
|
268
|
+
const map = new Map(consts);
|
|
269
|
+
for (const k of combo)
|
|
270
|
+
map.set(k.name, k);
|
|
271
|
+
texts.forEach((t, ti) => {
|
|
272
|
+
const s3 = substitute(t, map);
|
|
273
|
+
if (!s3 || !s3.used.some((u) => combo.includes(u)))
|
|
274
|
+
return;
|
|
275
|
+
for (const f of matchCrypto(s3.text, raw, idx)) {
|
|
276
|
+
const was = best.get(f.algorithm);
|
|
277
|
+
if (!was || worse(f, was.f))
|
|
278
|
+
best.set(f.algorithm, { f, used: s3.used, ...(ti === 1 ? { span } : {}) });
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
for (const { f, used, span: sp } of best.values()) {
|
|
283
|
+
const via = viaOf(path, used);
|
|
284
|
+
if (via.length)
|
|
285
|
+
f.via = via;
|
|
286
|
+
addDerived(f, { from: used.filter((u) => !u.file).map((u) => u.line), ...(sp ? { span: sp } : {}), sources: via });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
settleDerived(findings, derived);
|
|
292
|
+
if (ctx.onDerived)
|
|
293
|
+
for (const [f, how] of derived)
|
|
294
|
+
if (how.sources?.length && findings.includes(f))
|
|
295
|
+
ctx.onDerived(f, how.sources);
|
|
296
|
+
// Certificates and public keys committed as PEM, read for their real algorithm and size.
|
|
297
|
+
if (!TEST_PATH.test(path) && !EXAMPLE_PATH.test(path) && !EXAMPLE_FILE.test(path) && !DOC_FILE.test(path))
|
|
298
|
+
findings.push(...findPem(path, lines).findings);
|
|
299
|
+
joinJwk(findings, lang, lines);
|
|
300
|
+
// Infrastructure config: test fixtures and examples are written to be wrong or to show options.
|
|
301
|
+
if (!TEST_PATH.test(path) && !EXAMPLE_PATH.test(path))
|
|
302
|
+
findings.push(...scanInfra(path, lines));
|
|
303
|
+
// Every snippet shown anywhere, whatever kind of finding it belongs to, has its secrets masked.
|
|
304
|
+
for (const f of findings) {
|
|
305
|
+
if (f.snippet)
|
|
306
|
+
f.snippet = redactSecrets(f.snippet);
|
|
307
|
+
if (f.via)
|
|
308
|
+
for (const v of f.via)
|
|
309
|
+
if (v.note)
|
|
310
|
+
v.note = redactSecrets(v.note);
|
|
311
|
+
}
|
|
312
|
+
return dedupe(findings);
|
|
313
|
+
}
|
|
314
|
+
const IMPORT_LINE = {
|
|
315
|
+
python: /^\s*(?:from\s+[\w.]+\s+)?import\s+[\w.*(]/,
|
|
316
|
+
java: /^\s*import\s+(?:static\s+)?[\w.*]+\s*;?\s*$/,
|
|
317
|
+
go: /^\s*import\s+(?:[\w.]+\s+)?"[\w./-]+"\s*$/,
|
|
318
|
+
};
|
|
319
|
+
/** The lines inside Go's import ( ... ) blocks and Python's from x import ( ... ). */
|
|
320
|
+
function importBlockLines(lang, code) {
|
|
321
|
+
const out = new Set();
|
|
322
|
+
const open = lang === "go" ? /^\s*import\s*\(\s*$/ : lang === "python" ? /^\s*from\s+[\w.]+\s+import\s*\(\s*$/ : null;
|
|
323
|
+
if (!open)
|
|
324
|
+
return out;
|
|
325
|
+
for (let i = 0; i < code.length; i++) {
|
|
326
|
+
if (!open.test(code[i]))
|
|
327
|
+
continue;
|
|
328
|
+
for (let j = i + 1; j < code.length && !/^\s*\)/.test(code[j]); j++)
|
|
329
|
+
out.add(j);
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
const GLOBAL = new WeakMap();
|
|
334
|
+
/** Every match of a pattern on a line, at most four. */
|
|
335
|
+
function matchesOf(text, pattern) {
|
|
336
|
+
const first = text.match(pattern);
|
|
337
|
+
if (!first)
|
|
338
|
+
return [];
|
|
339
|
+
let g = GLOBAL.get(pattern);
|
|
340
|
+
if (!g)
|
|
341
|
+
GLOBAL.set(pattern, (g = new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g")));
|
|
342
|
+
const out = [first];
|
|
343
|
+
g.lastIndex = (first.index ?? 0) + Math.max(1, first[0].length);
|
|
344
|
+
for (let m = g.exec(text); m; m = g.exec(text)) {
|
|
345
|
+
if (m[0].length === 0)
|
|
346
|
+
g.lastIndex++;
|
|
347
|
+
out.push(m);
|
|
348
|
+
if (out.length === 4)
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
return out;
|
|
352
|
+
}
|
|
353
|
+
function innermost(scopes, idx) {
|
|
354
|
+
let best;
|
|
355
|
+
for (const s of scopes)
|
|
356
|
+
if (s.start <= idx && idx <= s.end && (!best || s.end - s.start < best.end - best.start))
|
|
357
|
+
best = s;
|
|
358
|
+
return best;
|
|
359
|
+
}
|
|
360
|
+
/** Every way to pick one value per parameter, at most 16. */
|
|
361
|
+
function combos(lists) {
|
|
362
|
+
let out = [[]];
|
|
363
|
+
for (const l of lists) {
|
|
364
|
+
const next = [];
|
|
365
|
+
for (const c of out)
|
|
366
|
+
for (const k of l)
|
|
367
|
+
if (next.length < 16)
|
|
368
|
+
next.push([...c, k]);
|
|
369
|
+
out = next;
|
|
370
|
+
}
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
/** An RSA key under 2048 bits is weak today, not only later. */
|
|
374
|
+
function withKeySize(f) {
|
|
375
|
+
if (f.keySize !== undefined && f.algorithm.startsWith("RSA") && f.keySize < 2048) {
|
|
376
|
+
f.title = `RSA-${f.keySize} is weak today and breakable by quantum computers`;
|
|
377
|
+
f.severity = "high";
|
|
378
|
+
f.risk = "weak-now";
|
|
379
|
+
f.fix = "Use 3072-bit keys or larger now, then plan the move to post-quantum methods.";
|
|
380
|
+
}
|
|
381
|
+
return f;
|
|
382
|
+
}
|
|
383
|
+
/** Give a finding the key size or curve that a fuller reading of the code found. */
|
|
384
|
+
function refine(f, from) {
|
|
385
|
+
let changed = false;
|
|
386
|
+
if (f.keySize === undefined && from.keySize !== undefined) {
|
|
387
|
+
f.keySize = from.keySize;
|
|
388
|
+
withKeySize(f);
|
|
389
|
+
changed = true;
|
|
390
|
+
}
|
|
391
|
+
if (!f.curve && from.curve) {
|
|
392
|
+
f.curve = from.curve;
|
|
393
|
+
changed = true;
|
|
394
|
+
}
|
|
395
|
+
if (changed && from.via && !f.via)
|
|
396
|
+
f.via = from.via;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* One use counts once. A finding from a filled-in constant goes when the constant's own line was
|
|
400
|
+
* already reported for the same algorithm; one from a joined call goes when a line inside the call
|
|
401
|
+
* was, and hands that finding its key size or curve.
|
|
402
|
+
*/
|
|
403
|
+
function settleDerived(findings, derived) {
|
|
404
|
+
if (!derived.size)
|
|
405
|
+
return;
|
|
406
|
+
const plain = findings.filter((f) => f.kind === "crypto" && !derived.has(f));
|
|
407
|
+
const drop = new Set();
|
|
408
|
+
for (const [d, how] of derived) {
|
|
409
|
+
if (how.from.some((line) => plain.some((p) => p.line === line && p.algorithm === d.algorithm))) {
|
|
410
|
+
drop.add(d);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (how.span) {
|
|
414
|
+
const [a, b] = how.span;
|
|
415
|
+
const inside = plain.find((p) => p.line > a && p.line <= b && p.algorithm === d.algorithm);
|
|
416
|
+
if (inside) {
|
|
417
|
+
refine(inside, d);
|
|
418
|
+
drop.add(d);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
for (let i = findings.length - 1; i >= 0; i--)
|
|
423
|
+
if (drop.has(findings[i]))
|
|
424
|
+
findings.splice(i, 1);
|
|
425
|
+
}
|
|
426
|
+
// Words that say a hash is not protecting anything.
|
|
427
|
+
const HASH_NOT_SECURITY = /nosec|NOSONAR|noqa|usedforsecurity|e-?tag|cache|checksum|\bcrc|dedup|uuid|gravatar|content[-_]?md5|shard|partition|consistent.?hash|file.?hash|hash.?file|filename|file.?name|\bgit\b|identicon|colou?r/i;
|
|
428
|
+
// Words that say it is.
|
|
429
|
+
const HASH_SECURITY = /passw|passwd|\bpwd|signature|\bsign(ed|er|ing)?\b|verif|hmac|authenti|\bauth\b|token|secret|credential|certificat|\bcert\b|salt|nonce|session|encrypt|decrypt|login|\bjwt\b|\botp\b|api.?key|private|\bkdf\b|pbkdf|derive|card|\bssn\b|integrity/i;
|
|
430
|
+
/** Whether an MD5 or SHA-1 call at lines[idx] looks like it protects something. */
|
|
431
|
+
function weakHashForSecurity(raw, lines, idx) {
|
|
432
|
+
if (/hmac/i.test(raw))
|
|
433
|
+
return true;
|
|
434
|
+
if (HASH_NOT_SECURITY.test(raw))
|
|
435
|
+
return false;
|
|
436
|
+
if (HASH_SECURITY.test(raw))
|
|
437
|
+
return true;
|
|
438
|
+
// The function or block around it: a few lines up (often the function name) and a couple down.
|
|
439
|
+
const around = lines.slice(Math.max(0, idx - 6), idx + 3).map((l) => l.text).join("\n");
|
|
440
|
+
if (HASH_NOT_SECURITY.test(around))
|
|
441
|
+
return false;
|
|
442
|
+
return HASH_SECURITY.test(around);
|
|
443
|
+
}
|
|
444
|
+
const KEY_BODY = /^[A-Za-z0-9+/=]{40,}$/;
|
|
445
|
+
/** A token in test code that looks issued, not typed: random enough, with no long run of one character. */
|
|
446
|
+
function looksLive(value) {
|
|
447
|
+
const body = value.replace(/^[A-Za-z]+[_-]|^(?:AKIA|ASIA|AIza)/, "");
|
|
448
|
+
return entropy(body) >= 4 && !/(.)\1{3}/.test(body);
|
|
449
|
+
}
|
|
450
|
+
function hasKeyMaterial(line, next) {
|
|
451
|
+
const after = line.split(/PRIVATE KEY(?: BLOCK)?-----/)[1] ?? "";
|
|
452
|
+
// Escaped line breaks inside a string: "\n", "\r\n" or "\r" (Windows-style keys pasted into code).
|
|
453
|
+
if (after.split(/(?:\\r)?\\n|\\r|\s+/).some((part) => KEY_BODY.test(part)))
|
|
454
|
+
return true;
|
|
455
|
+
return next !== undefined && KEY_BODY.test(next.text.trim().replace(/^["']|["',]$/g, ""));
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* A JSON Web Key spread over several lines gives its kty and its crv on different lines. Keep the kty
|
|
459
|
+
* finding, give it the curve, and drop the crv one, so one key counts once.
|
|
460
|
+
*/
|
|
461
|
+
function joinJwk(findings, lang, lines) {
|
|
462
|
+
if (lang === null)
|
|
463
|
+
return;
|
|
464
|
+
const kty = findings.filter((f) => f.ruleId === "jwk-kty" || f.ruleId === "js-jwk-kty");
|
|
465
|
+
if (!kty.length)
|
|
466
|
+
return;
|
|
467
|
+
// "use": "enc" or an encryption alg can sit on another line of the same key object.
|
|
468
|
+
for (const k of kty) {
|
|
469
|
+
if (k.algorithm !== "RSA signature" && k.algorithm !== "EC")
|
|
470
|
+
continue;
|
|
471
|
+
const at = lines.findIndex((l) => l.no === k.line);
|
|
472
|
+
if (at < 0)
|
|
473
|
+
continue;
|
|
474
|
+
let from = at;
|
|
475
|
+
while (from > 0 && at - from < 12 && !lines[from].text.includes("{"))
|
|
476
|
+
from--;
|
|
477
|
+
let to = at;
|
|
478
|
+
while (to < lines.length - 1 && to - at < 12 && !lines[to].text.includes("}"))
|
|
479
|
+
to++;
|
|
480
|
+
const obj = lines.slice(from, to + 1).map((l) => l.text).join("\n");
|
|
481
|
+
if (!/["']?use["']?\s*:\s*["']enc["']|["']?alg["']?\s*:\s*["'](?:RSA-OAEP|RSA1_5|ECDH-ES)/.test(obj))
|
|
482
|
+
continue;
|
|
483
|
+
const algorithm = k.algorithm === "EC" ? "ECDH" : "RSA encryption";
|
|
484
|
+
const info = ALGORITHMS[algorithm];
|
|
485
|
+
Object.assign(k, { algorithm, primitive: info.primitive, severity: info.severity, fix: info.fix, title: `${algorithm} is breakable by quantum computers` });
|
|
486
|
+
}
|
|
487
|
+
for (let i = findings.length - 1; i >= 0; i--) {
|
|
488
|
+
const c = findings[i];
|
|
489
|
+
if (c.ruleId !== "jwk-crv" && c.ruleId !== "js-jwk-crv")
|
|
490
|
+
continue;
|
|
491
|
+
const k = kty.filter((f) => Math.abs(f.line - c.line) <= 6).sort((a, b) => Math.abs(a.line - c.line) - Math.abs(b.line - c.line))[0];
|
|
492
|
+
if (!k)
|
|
493
|
+
continue;
|
|
494
|
+
if (!k.curve && c.curve)
|
|
495
|
+
k.curve = c.curve;
|
|
496
|
+
// An OKP key's curve says which algorithm it is.
|
|
497
|
+
if (/^(Ed25519|Ed448|X25519|X448)$/.test(c.algorithm) && k.algorithm !== c.algorithm && /^(Ed25519|X25519)$/.test(k.algorithm)) {
|
|
498
|
+
const info = ALGORITHMS[c.algorithm];
|
|
499
|
+
Object.assign(k, { algorithm: c.algorithm, primitive: info.primitive, severity: info.severity, fix: info.fix, title: `${c.algorithm} is breakable by quantum computers` });
|
|
500
|
+
}
|
|
501
|
+
findings.splice(i, 1);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
// Two rules can hit the same line for the same algorithm; keep one.
|
|
505
|
+
function dedupe(findings) {
|
|
506
|
+
const seen = new Set();
|
|
507
|
+
return findings.filter((f) => {
|
|
508
|
+
const k = `${f.file}:${f.line}:${f.kind}:${f.algorithm}:${f.material?.subject ?? ""}`;
|
|
509
|
+
if (seen.has(k))
|
|
510
|
+
return false;
|
|
511
|
+
seen.add(k);
|
|
512
|
+
return true;
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
export function scanFiles(files) {
|
|
516
|
+
const findings = [];
|
|
517
|
+
const pqc = [];
|
|
518
|
+
const inventory = [];
|
|
519
|
+
const libraries = [];
|
|
520
|
+
const protocols = [];
|
|
521
|
+
let filesScanned = 0;
|
|
522
|
+
// First the project pass: constants imported from other files, values passed into functions.
|
|
523
|
+
const prepared = new Map();
|
|
524
|
+
const forProject = [];
|
|
525
|
+
for (const f of files) {
|
|
526
|
+
if (!shouldScan(f.path) || f.content.includes("\u0000") || isInventoryDocument(f.path, f.content) || !PROJECT_FILE.test(f.path))
|
|
527
|
+
continue;
|
|
528
|
+
const lines = f.content.split(/\r?\n/).map((text, i) => ({ no: i + 1, text }));
|
|
529
|
+
const prep = prepareLines(f.path, lines);
|
|
530
|
+
prepared.set(f.path, prep);
|
|
531
|
+
forProject.push({ path: f.path, code: prep.codeLines, consts: prep.consts, sideline: TEST_PATH.test(f.path) || EXAMPLE_PATH.test(f.path) || EXAMPLE_FILE.test(f.path) || TYPES_FILE.test(f.path) });
|
|
532
|
+
}
|
|
533
|
+
const project = forProject.length ? projectContext(forProject, goModules(files)) : new Map();
|
|
534
|
+
const derivedAt = [];
|
|
535
|
+
for (const f of files) {
|
|
536
|
+
if (!shouldScan(f.path))
|
|
537
|
+
continue;
|
|
538
|
+
filesScanned++;
|
|
539
|
+
if (isInventoryDocument(f.path, f.content))
|
|
540
|
+
continue;
|
|
541
|
+
const prep = prepared.get(f.path);
|
|
542
|
+
if (prep) {
|
|
543
|
+
prepared.delete(f.path);
|
|
544
|
+
const lines = f.content.split(/\r?\n/).map((text, i) => ({ no: i + 1, text }));
|
|
545
|
+
const found = scanLines(f.path, lines, { prepared: prep, project: project.get(f.path), onDerived: (d, sources) => derivedAt.push({ f: d, sources }) });
|
|
546
|
+
findings.push(...(f.onlyLines ? found.filter((x) => f.onlyLines.has(x.line)) : found));
|
|
547
|
+
}
|
|
548
|
+
else
|
|
549
|
+
findings.push(...scanFile(f.path, f.content, f.onlyLines));
|
|
550
|
+
// Post-quantum use only counts in code that ships, like the problems do.
|
|
551
|
+
if (!TEST_PATH.test(f.path) && !EXAMPLE_PATH.test(f.path)) {
|
|
552
|
+
pqc.push(...findPqc(f.path, f.content));
|
|
553
|
+
const keep = (i) => !f.onlyLines || f.onlyLines.has(i.line);
|
|
554
|
+
libraries.push(...findLibraries(f.path, f.content).filter(keep));
|
|
555
|
+
inventory.push(...findInventory(f.path, f.content).filter(keep));
|
|
556
|
+
protocols.push(...findProtocols(f.path, f.content).filter(keep));
|
|
557
|
+
if (!EXAMPLE_FILE.test(f.path) && !DOC_FILE.test(f.path) && !f.content.includes("\u0000") && (f.content.includes("-----BEGIN ") || f.content.includes("x5c"))) {
|
|
558
|
+
inventory.push(...findPem(f.path, f.content.split(/\r?\n/).map((text, i) => ({ no: i + 1, text }))).inventory.filter(keep));
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
// One use counts once: a value already reported where it is set, or at the call that passes it, isn't reported again.
|
|
563
|
+
if (derivedAt.length) {
|
|
564
|
+
const isDerived = new Set(derivedAt.map((d) => d.f));
|
|
565
|
+
const at = new Set(findings.filter((f) => f.kind === "crypto" && !isDerived.has(f)).map((f) => `${f.file}:${f.line}:${f.algorithm}`));
|
|
566
|
+
const drop = new Set(derivedAt.filter((d) => d.sources.some((s) => at.has(`${s.file}:${s.line}:${d.f.algorithm}`))).map((d) => d.f));
|
|
567
|
+
if (drop.size)
|
|
568
|
+
return { findings: findings.filter((f) => !drop.has(f)), filesScanned, pqc, inventory, libraries, protocols };
|
|
569
|
+
}
|
|
570
|
+
return { findings, filesScanned, pqc, inventory, libraries, protocols };
|
|
571
|
+
}
|
|
572
|
+
// Languages the project pass reads.
|
|
573
|
+
const PROJECT_FILE = /\.(py|pyw|js|mjs|cjs|jsx|ts|mts|cts|tsx|go|java|kt|kts|cs|c|cc|cpp|cxx|h|hh|hpp|m|mm)$/i;
|
|
574
|
+
/** Parse a unified diff patch (GitHub's `patch` field) into the added lines of the new file. */
|
|
575
|
+
export function patchAddedLines(patch) {
|
|
576
|
+
const out = [];
|
|
577
|
+
if (!patch)
|
|
578
|
+
return out;
|
|
579
|
+
let line = 0;
|
|
580
|
+
for (const l of patch.split("\n")) {
|
|
581
|
+
const h = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
582
|
+
if (h) {
|
|
583
|
+
line = Number(h[1]);
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (l.startsWith("+")) {
|
|
587
|
+
out.push({ no: line, text: l.slice(1) });
|
|
588
|
+
line++;
|
|
589
|
+
}
|
|
590
|
+
else if (l.startsWith("-")) {
|
|
591
|
+
// removed line: new-file counter does not move
|
|
592
|
+
}
|
|
593
|
+
else if (!l.startsWith("\\")) {
|
|
594
|
+
line++;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
599
|
+
export function addedLines(patch) {
|
|
600
|
+
return new Set(patchAddedLines(patch).map((l) => l.no));
|
|
601
|
+
}
|