leakshield 0.1.1 → 0.1.3
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/README.md +62 -4
- package/README.zh-TW.md +8 -2
- package/dist/config/loader.js +51 -0
- package/dist/decision/pseudonymization.js +106 -19
- package/dist/doctor.js +167 -0
- package/dist/opencode-transparent.js +1 -1
- package/dist/rules/builtin.js +136 -3
- package/dist/rules/dynamic.js +259 -13
- package/dist/scanner/allowlist.js +37 -0
- package/dist/scanner/cidr.js +96 -0
- package/dist/scanner/encoding.js +5 -1
- package/dist/scanner/engine.js +106 -39
- package/dist/scanner/remotes.js +140 -0
- package/dist/scanner/unicode.js +30 -0
- package/package.json +1 -1
package/dist/rules/builtin.js
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
import { containsAddressInRun, ipv4Windows, parseCidrList } from "../scanner/cidr.js";
|
|
2
|
+
/** Networks used when a rule is evaluated without a loaded config. */
|
|
3
|
+
const DEFAULT_PRIVATE_NETWORKS = parseCidrList(undefined);
|
|
4
|
+
/**
|
|
5
|
+
* A dotted run of four or more octets.
|
|
6
|
+
*
|
|
7
|
+
* Four groups is an address. A longer run is matched whole on purpose: with
|
|
8
|
+
* the old four-group pattern, `10.1.2.3.4` yielded `10.1.2.3` and the public
|
|
9
|
+
* `1.2.3.4` inside it was never reported — which the masker then caught as
|
|
10
|
+
* residual plaintext and turned into a refusal for the whole request.
|
|
11
|
+
*/
|
|
12
|
+
const IPV4_DOTTED_RUN = /\b[0-9]{1,3}(?:\.[0-9]{1,3}){3,}\b/g;
|
|
13
|
+
import { classifyTransportSpan } from "../scanner/remotes.js";
|
|
1
14
|
/** Luhn checksum(ISO/IEC 7812-1);信用卡號形狀相符後必須通過才命中。 */
|
|
2
15
|
function luhnValid(raw) {
|
|
3
16
|
const digits = raw.replace(/[^0-9]/g, "");
|
|
@@ -36,6 +49,11 @@ function ibanValid(raw) {
|
|
|
36
49
|
/** 僅公共可路由 IPv4 視為敏感;私有/回環/鏈路本地/CGNAT/保留段不命中(config 常見值)。 */
|
|
37
50
|
function publicIPv4(raw) {
|
|
38
51
|
const octets = raw.split(".").map(Number);
|
|
52
|
+
// A run longer than four octets is reported whole when any window is a
|
|
53
|
+
// public address, so a suffix like the 1.2.3.4 in 10.1.2.3.4 is never left
|
|
54
|
+
// unmasked.
|
|
55
|
+
if (octets.length > 4)
|
|
56
|
+
return ipv4Windows(raw).some((window) => publicIPv4(window));
|
|
39
57
|
if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255))
|
|
40
58
|
return false;
|
|
41
59
|
const [a, b] = octets;
|
|
@@ -53,6 +71,81 @@ function publicIPv4(raw) {
|
|
|
53
71
|
return false; // multicast / reserved
|
|
54
72
|
return true;
|
|
55
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Values on the right of `password:` / `secret =` that are source code, not a
|
|
76
|
+
* literal: environment lookups, a method-call chain, or a member read off a
|
|
77
|
+
* config-like object (issue #49). Only the unquoted branch of generic-secret
|
|
78
|
+
* reaches this, and every form here is narrow on purpose: a bare
|
|
79
|
+
* `word.word` could be a real password, so it is not exempt.
|
|
80
|
+
*/
|
|
81
|
+
// Call arguments and bracket keys may hold identifiers, numbers or an
|
|
82
|
+
// ENV_NAME-style string, never another literal: `decrypt("hunter2hunter2")`
|
|
83
|
+
// keeps being reported.
|
|
84
|
+
// Backticks and `=` are excluded too, so a template literal or a keyword
|
|
85
|
+
// argument (`hash(pw=…)`) never qualifies.
|
|
86
|
+
const ARG = `(?:[^()'"\`=\\[\\]]|'[A-Z][A-Z0-9_]*'|"[A-Z][A-Z0-9_]*")*`;
|
|
87
|
+
const IDENT = "[A-Za-z_$][\\w$]*";
|
|
88
|
+
const STEP = `(?:\\??\\.${IDENT}|\\[${ARG}\\]|\\(${ARG}\\))`;
|
|
89
|
+
const TAIL = "[;,)]*$";
|
|
90
|
+
/**
|
|
91
|
+
* A member/call chain: `z.string().min(6)`, `getPassword()`, `os.getenv("DB_PASS")`.
|
|
92
|
+
* Every STEP alternative starts with a different character, so matching is
|
|
93
|
+
* linear; "contains a call" is checked separately rather than with a second
|
|
94
|
+
* quantified group that would backtrack.
|
|
95
|
+
*/
|
|
96
|
+
const CODE_CHAIN = new RegExp(`^${IDENT}${STEP}*${TAIL}`);
|
|
97
|
+
/** A member read off an env or config-like root: `process.env.X`, `config.clientSecret`. */
|
|
98
|
+
const CONFIG_MEMBER = new RegExp(`^(?:process\\.env|import\\.meta\\.env|os\\.environ|ENV|this|self|config|cfg|conf|settings|options|opts|props|params|args|req|request|ctx|context|env|secrets)${STEP}+${TAIL}`);
|
|
99
|
+
/** Longer values are not exempted; a real expression on one line is short. */
|
|
100
|
+
const MAX_EXPRESSION_LENGTH = 256;
|
|
101
|
+
function isCodeExpressionValue(match) {
|
|
102
|
+
const value = match.replace(/^[^:=]*[:=]\s*/, "");
|
|
103
|
+
if (value.length > MAX_EXPRESSION_LENGTH)
|
|
104
|
+
return false;
|
|
105
|
+
if (value.startsWith("'") || value.startsWith('"'))
|
|
106
|
+
return false;
|
|
107
|
+
return (value.includes("(") && CODE_CHAIN.test(value)) || CONFIG_MEMBER.test(value);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A whole-token template placeholder that only names a variable:
|
|
111
|
+
* `${pass}`, `${cfg.db.password}`, `{{ password }}`, `<password>`. An
|
|
112
|
+
* interpolation holding a literal (`${"S3cr3tPass"}`) is not a placeholder.
|
|
113
|
+
*/
|
|
114
|
+
const PLACEHOLDER = /^(?:\$\{\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\}|\{\{\s*[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*\s*\}\}|<[A-Za-z][\w -]*>)$/;
|
|
115
|
+
/**
|
|
116
|
+
* True when the password part of `user:password@` is a template placeholder,
|
|
117
|
+
* as in `mongodb://${user}:${pass}@host` or `postgres://<user>:<password>@…`.
|
|
118
|
+
* `userinfo` runs from just after `://` to (and possibly including) the `@`.
|
|
119
|
+
*/
|
|
120
|
+
function placeholderPassword(userinfo) {
|
|
121
|
+
const at = userinfo.lastIndexOf("@");
|
|
122
|
+
const body = at === -1 ? userinfo : userinfo.slice(0, at);
|
|
123
|
+
const colon = body.indexOf(":");
|
|
124
|
+
if (colon === -1)
|
|
125
|
+
return false;
|
|
126
|
+
return PLACEHOLDER.test(body.slice(colon + 1));
|
|
127
|
+
}
|
|
128
|
+
const UUID_SHAPE = /[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/g;
|
|
129
|
+
/** True when [index, index+length) lies inside a UUID-shaped run in `text`. */
|
|
130
|
+
function insideUuid(text, index, length) {
|
|
131
|
+
const from = Math.max(0, index - 36);
|
|
132
|
+
const window = text.slice(from, index + length + 36);
|
|
133
|
+
for (const uuid of window.matchAll(UUID_SHAPE)) {
|
|
134
|
+
const start = from + uuid.index;
|
|
135
|
+
if (start <= index && index + length <= start + uuid[0].length)
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
/** Luhn plus shape checks: not one repeated digit, not part of a UUID (#49). */
|
|
141
|
+
function creditCardValid(match, context) {
|
|
142
|
+
const digits = match.replace(/[^0-9]/g, "");
|
|
143
|
+
if (/^(\d)\1*$/.test(digits))
|
|
144
|
+
return false;
|
|
145
|
+
if (insideUuid(context.text, context.index, match.length))
|
|
146
|
+
return false;
|
|
147
|
+
return luhnValid(match);
|
|
148
|
+
}
|
|
56
149
|
export const BUILTIN_RULES = [
|
|
57
150
|
// ── API Keys / Secrets / Tokens ──────────────────────────────────────────
|
|
58
151
|
{
|
|
@@ -133,6 +226,22 @@ export const BUILTIN_RULES = [
|
|
|
133
226
|
// 同時涵蓋有引號(YAML/JSON)與無引號(.env)寫法
|
|
134
227
|
// (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
|
|
135
228
|
pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
|
|
229
|
+
// 無引號值若是程式碼表達式(process.env.X、z.string()、config.secret)不算機密(#49)
|
|
230
|
+
validate: (match) => !isCodeExpressionValue(match),
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
id: "url-userinfo",
|
|
234
|
+
type: "SECRET",
|
|
235
|
+
severity: "HIGH",
|
|
236
|
+
description: "URL 內嵌憑證(user:password@)",
|
|
237
|
+
// 取到 authority 內最後一個 `@` 為止的完整 userinfo:`https://u:pa@ss@host`
|
|
238
|
+
// 若停在第一個 `@`,`ss` 會留在遮罩之外。前置 group 不吃 `:`,且以 `://`
|
|
239
|
+
// 起頭(skipPrefix 只回報 userinfo),避免可變長度 lookbehind 在每個位置
|
|
240
|
+
// 重掃造成二次方成長。
|
|
241
|
+
pattern: /:\/\/[^\s/?#:]*:[^\s/?#]*@/gi,
|
|
242
|
+
skipPrefix: 3,
|
|
243
|
+
// 密碼段是 ${…}/{{…}}/<…> 模板佔位時不是憑證(#49)
|
|
244
|
+
validate: (match) => !placeholderPassword(match),
|
|
136
245
|
},
|
|
137
246
|
{
|
|
138
247
|
id: "jwt",
|
|
@@ -193,7 +302,16 @@ export const BUILTIN_RULES = [
|
|
|
193
302
|
type: "PII_EMAIL",
|
|
194
303
|
severity: "MEDIUM",
|
|
195
304
|
description: "Email 地址",
|
|
196
|
-
|
|
305
|
+
// The local part is capped at 64 octets, the RFC 5321 limit. Unbounded
|
|
306
|
+
// `+` made the rule quadratic on a long token with no `@`: every start
|
|
307
|
+
// position consumed the rest of the run before failing.
|
|
308
|
+
pattern: /[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g,
|
|
309
|
+
// `user@host:path` and `ssh://user@host/…` are Git transports, not
|
|
310
|
+
// mailboxes (#34). The password half of `scheme://user:password@host` is
|
|
311
|
+
// a credential, reported by `url-userinfo` instead. Only this rule skips
|
|
312
|
+
// those spans; private domains, path keywords and URL credentials keep
|
|
313
|
+
// their own findings.
|
|
314
|
+
validate: (match, context) => classifyTransportSpan(context.text, context.index, match.length) === null,
|
|
197
315
|
},
|
|
198
316
|
{
|
|
199
317
|
id: "phone-tw",
|
|
@@ -230,6 +348,8 @@ export const BUILTIN_RULES = [
|
|
|
230
348
|
severity: "HIGH",
|
|
231
349
|
description: "資料庫連線字串(含密碼)",
|
|
232
350
|
pattern: /(?:mongodb(?:\+srv)?|postgresql|postgres|mysql|redis|mssql):\/\/[^:\s]+:[^@\s]+@[^\s"']+/gi,
|
|
351
|
+
// 密碼段是模板佔位時不是憑證(#49)
|
|
352
|
+
validate: (match) => !placeholderPassword(match.slice(match.indexOf("://") + 3)),
|
|
233
353
|
},
|
|
234
354
|
{
|
|
235
355
|
id: "db-connection-ado",
|
|
@@ -247,7 +367,7 @@ export const BUILTIN_RULES = [
|
|
|
247
367
|
description: "信用卡號(Luhn 驗證)",
|
|
248
368
|
// 13–19 位數字,允許空格或連字號分隔;Luhn 不過由 validate 排除
|
|
249
369
|
pattern: /\b(?:[0-9][ -]?){12,18}[0-9]\b/g,
|
|
250
|
-
validate:
|
|
370
|
+
validate: creditCardValid,
|
|
251
371
|
},
|
|
252
372
|
{
|
|
253
373
|
id: "iban",
|
|
@@ -264,9 +384,22 @@ export const BUILTIN_RULES = [
|
|
|
264
384
|
severity: "MEDIUM",
|
|
265
385
|
description: "公共 IPv4 位址",
|
|
266
386
|
// 私有/回環/CGNAT/保留段由 validate 排除,避免 config 常數誤報
|
|
267
|
-
pattern:
|
|
387
|
+
pattern: IPV4_DOTTED_RUN,
|
|
268
388
|
validate: publicIPv4,
|
|
269
389
|
},
|
|
390
|
+
{
|
|
391
|
+
id: "private-ipv4",
|
|
392
|
+
type: "PII_IP",
|
|
393
|
+
severity: "MEDIUM",
|
|
394
|
+
description: "私有 IPv4 位址",
|
|
395
|
+
// Opt-in:內網拓撲通常敏感,但位址字面值對版本號、時間戳的誤報也高。
|
|
396
|
+
// 要開啟:settings.rule_overrides["private-ipv4"]: true。預設涵蓋
|
|
397
|
+
// RFC 1918、CGNAT 與 link-local;settings.private_cidrs 可縮小範圍。
|
|
398
|
+
optIn: true,
|
|
399
|
+
pattern: IPV4_DOTTED_RUN,
|
|
400
|
+
// getRules 會以 settings.private_cidrs 換掉這個 validator。
|
|
401
|
+
validate: (match) => containsAddressInRun(DEFAULT_PRIVATE_NETWORKS, match),
|
|
402
|
+
},
|
|
270
403
|
{
|
|
271
404
|
id: "url",
|
|
272
405
|
type: "PII_URL",
|
package/dist/rules/dynamic.js
CHANGED
|
@@ -1,26 +1,267 @@
|
|
|
1
|
-
// ReDoS
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// ReDoS heuristic: run the compiled regex once against a fixed input and
|
|
2
|
+
// measure wall-clock time after exec() returns. This is a heuristic, not a
|
|
3
|
+
// guarantee: Node.js is single-threaded, so exec() cannot be interrupted, and
|
|
4
|
+
// a pattern that backtracks catastrophically on this input blocks until it
|
|
5
|
+
// finishes. Patterns that return under REDOS_TIMEOUT_MS are accepted; slower
|
|
6
|
+
// ones are skipped and reported by `--doctor`. Patterns that do not compile
|
|
7
|
+
// never get here: `loadConfig()` rejects them (fail-closed).
|
|
6
8
|
const REDOS_TIMEOUT_MS = 200;
|
|
7
9
|
const REDOS_TEST_INPUT = "a".repeat(50) + "!";
|
|
8
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Is this pattern's top level an alternation (`a|b`, not `(?:a|b)`)? Boundaries
|
|
12
|
+
* cannot be attached safely to each branch from outside, and `\bfoo|bar\b`
|
|
13
|
+
* would silently mean something else, so `word_boundary` refuses it.
|
|
14
|
+
*/
|
|
15
|
+
function hasTopLevelAlternation(source) {
|
|
16
|
+
let depth = 0;
|
|
17
|
+
let escaped = false;
|
|
18
|
+
let inClass = false;
|
|
19
|
+
for (const ch of source) {
|
|
20
|
+
if (escaped) {
|
|
21
|
+
escaped = false;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (ch === "\\") {
|
|
25
|
+
escaped = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (inClass) {
|
|
29
|
+
if (ch === "]")
|
|
30
|
+
inClass = false;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (ch === "[") {
|
|
34
|
+
inClass = true;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (ch === "(") {
|
|
38
|
+
depth += 1;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (ch === ")") {
|
|
42
|
+
depth = Math.max(0, depth - 1);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (ch === "|" && depth === 0)
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
/** The ASCII-word test `keywordPattern` uses for its boundaries. */
|
|
51
|
+
function asciiWordChar(ch) {
|
|
52
|
+
return ch !== undefined && /^[A-Za-z0-9_]$/.test(ch);
|
|
53
|
+
}
|
|
54
|
+
/** Characters that hide the real edge (group, class, quantifier, escape). No
|
|
55
|
+
* boundary can be placed there safely, so none is added and `--doctor` says so. */
|
|
56
|
+
const HIDDEN_EDGE = new Set(["(", ")", "[", "]", "{", "}", ".", "*", "+", "?", "|", "\\"]);
|
|
57
|
+
/** End index (exclusive) of the escape sequence starting at `start`. */
|
|
58
|
+
function escapeEnd(source, start) {
|
|
59
|
+
const next = source[start + 1];
|
|
60
|
+
if (next === undefined)
|
|
61
|
+
return start + 1;
|
|
62
|
+
if (next === "x")
|
|
63
|
+
return Math.min(source.length, start + 4);
|
|
64
|
+
if (next === "u" || next === "p" || next === "P" || next === "k") {
|
|
65
|
+
if (source[start + 2] === "{" || source[start + 2] === "<") {
|
|
66
|
+
const close = source.indexOf(source[start + 2] === "{" ? "}" : ">", start + 3);
|
|
67
|
+
return close === -1 ? source.length : close + 1;
|
|
68
|
+
}
|
|
69
|
+
return next === "u" ? Math.min(source.length, start + 6) : start + 2;
|
|
70
|
+
}
|
|
71
|
+
// Control escapes: \cA is one token, and A is not a literal word character.
|
|
72
|
+
if (next === "c")
|
|
73
|
+
return Math.min(source.length, start + 3);
|
|
74
|
+
// Legacy octal: \0, \012 (at most two digits after the leading 0).
|
|
75
|
+
if (next === "0") {
|
|
76
|
+
let index = start + 1;
|
|
77
|
+
let digits = 0;
|
|
78
|
+
while (index < source.length && digits < 3 && /[0-7]/.test(source[index] ?? "")) {
|
|
79
|
+
index += 1;
|
|
80
|
+
digits += 1;
|
|
81
|
+
}
|
|
82
|
+
return index;
|
|
83
|
+
}
|
|
84
|
+
if (/[1-9]/.test(next)) {
|
|
85
|
+
let index = start + 1;
|
|
86
|
+
while (index < source.length && /[0-9]/.test(source[index] ?? ""))
|
|
87
|
+
index += 1;
|
|
88
|
+
return index;
|
|
89
|
+
}
|
|
90
|
+
return Math.min(source.length, start + 2);
|
|
91
|
+
}
|
|
92
|
+
/** End index (exclusive) of a character class starting at `start`. */
|
|
93
|
+
function classEnd(source, start) {
|
|
94
|
+
let index = start + 1;
|
|
95
|
+
if (source[index] === "^")
|
|
96
|
+
index += 1;
|
|
97
|
+
while (index < source.length) {
|
|
98
|
+
const ch = source[index];
|
|
99
|
+
if (ch === "\\") {
|
|
100
|
+
index = Math.max(escapeEnd(source, index), index + 1);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (ch === "]")
|
|
104
|
+
return index + 1;
|
|
105
|
+
index += 1;
|
|
106
|
+
}
|
|
107
|
+
return source.length;
|
|
108
|
+
}
|
|
109
|
+
/** First token of the pattern: one escape, one class, or one character. */
|
|
110
|
+
function firstToken(source) {
|
|
111
|
+
const ch = source[0];
|
|
112
|
+
if (ch === undefined)
|
|
113
|
+
return "";
|
|
114
|
+
if (ch === "\\")
|
|
115
|
+
return source.slice(0, escapeEnd(source, 0));
|
|
116
|
+
if (ch === "[")
|
|
117
|
+
return source.slice(0, classEnd(source, 0));
|
|
118
|
+
return ch;
|
|
119
|
+
}
|
|
120
|
+
/** Last token of the pattern, walking past escapes and classes. */
|
|
121
|
+
function lastToken(source) {
|
|
122
|
+
let index = 0;
|
|
123
|
+
let start = 0;
|
|
124
|
+
while (index < source.length) {
|
|
125
|
+
start = index;
|
|
126
|
+
const ch = source[index];
|
|
127
|
+
if (ch === "\\") {
|
|
128
|
+
index = Math.max(escapeEnd(source, index), index + 1);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (ch === "[") {
|
|
132
|
+
index = Math.max(classEnd(source, index), index + 1);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
index += 1;
|
|
136
|
+
}
|
|
137
|
+
return source.slice(start);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* What a boundary can do at this edge. Only a literal ASCII word character can
|
|
141
|
+
* take a `\b`. An escape is never assumed to end in a word character: `\D`,
|
|
142
|
+
* `\x21` or `\u5bc6` all end in something else, and appending `\b` would drop
|
|
143
|
+
* real matches (including the CJK case the acceptance criteria call out).
|
|
144
|
+
*/
|
|
145
|
+
function classifyEdge(token) {
|
|
146
|
+
if (token === "")
|
|
147
|
+
return "none";
|
|
148
|
+
if (token === "\\b" || token === "^" || token === "$")
|
|
149
|
+
return "satisfied";
|
|
150
|
+
if (token.startsWith("\\") || token.startsWith("["))
|
|
151
|
+
return "hidden";
|
|
152
|
+
if (token.length === 1) {
|
|
153
|
+
if (asciiWordChar(token))
|
|
154
|
+
return "word";
|
|
155
|
+
if (HIDDEN_EDGE.has(token))
|
|
156
|
+
return "hidden";
|
|
157
|
+
return "none";
|
|
158
|
+
}
|
|
159
|
+
return "hidden";
|
|
160
|
+
}
|
|
161
|
+
const EDGE_CLASS = {
|
|
162
|
+
word: "added",
|
|
163
|
+
satisfied: "none",
|
|
164
|
+
hidden: "hidden",
|
|
165
|
+
none: "none",
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Which edges of a rule can actually take a boundary. `word_boundary` can only
|
|
169
|
+
* add `\b` where the edge is a literal ASCII word character; an edge that is a
|
|
170
|
+
* group, class, quantifier or escape is reported as hidden rather than guessed
|
|
171
|
+
* at, and `--doctor` warns so the rule does not look stricter than it is.
|
|
172
|
+
*/
|
|
173
|
+
export function customRuleBoundaries(rule) {
|
|
174
|
+
if (rule.word_boundary !== true)
|
|
175
|
+
return { lead: "none", trail: "none" };
|
|
176
|
+
return {
|
|
177
|
+
lead: EDGE_CLASS[classifyEdge(firstToken(rule.pattern))],
|
|
178
|
+
trail: EDGE_CLASS[classifyEdge(lastToken(rule.pattern))],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Pattern source with `word_boundary` applied. A `\b` is added only where the
|
|
183
|
+
* edge is a literal ASCII word character; an already-written `\b`/`^`/`$` is
|
|
184
|
+
* respected. A top-level alternation is refused because `\bfoo|bar\b` would
|
|
185
|
+
* silently mean `(\bfoo)|(bar\b)`; group it as `(?:foo|bar)`.
|
|
186
|
+
*/
|
|
187
|
+
export function customRuleSource(rule) {
|
|
188
|
+
if (rule.word_boundary !== true)
|
|
189
|
+
return rule.pattern;
|
|
190
|
+
if (hasTopLevelAlternation(rule.pattern)) {
|
|
191
|
+
// Static example on purpose: a config error must not repeat the pattern,
|
|
192
|
+
// which may itself be the literal the rule exists to protect.
|
|
193
|
+
throw new Error(`custom rule "${rule.description}": word_boundary cannot be applied to a top-level alternation; group it as (?:foo|bar)`);
|
|
194
|
+
}
|
|
195
|
+
// One boundary decision for both enforcement and what `--doctor` reports.
|
|
196
|
+
const edges = customRuleBoundaries(rule);
|
|
197
|
+
const lead = edges.lead === "added" ? "\\b" : "";
|
|
198
|
+
const trail = edges.trail === "added" ? "\\b" : "";
|
|
199
|
+
return lead + rule.pattern + trail;
|
|
200
|
+
}
|
|
201
|
+
/** Final flags: `g` is always present; `i` stays the default so existing rules
|
|
202
|
+
* keep matching as they did before `flags` existed. */
|
|
203
|
+
export function customRuleFlags(rule) {
|
|
204
|
+
const requested = rule.flags ?? "i";
|
|
205
|
+
return Array.from(new Set(`g${requested}`)).join("");
|
|
206
|
+
}
|
|
207
|
+
/** The exact RegExp the scanner uses for a custom rule. */
|
|
208
|
+
export function customRulePattern(rule) {
|
|
209
|
+
return new RegExp(customRuleSource(rule), customRuleFlags(rule));
|
|
210
|
+
}
|
|
211
|
+
// The timing check can land on either side of the limit from one run to the
|
|
212
|
+
// next, so the first verdict for a pattern is kept for the life of the
|
|
213
|
+
// process: `--doctor` and the scanner it smoke-tests then agree on which
|
|
214
|
+
// rules are enforced. Bounded so a long-lived process cannot grow it forever.
|
|
215
|
+
const MAX_REMEMBERED_VERDICTS = 1024;
|
|
216
|
+
const verdicts = new Map();
|
|
217
|
+
export function checkCustomPattern(pattern, flags = "gi") {
|
|
218
|
+
const key = `${flags}\u0000${pattern}`;
|
|
219
|
+
const remembered = verdicts.get(key);
|
|
220
|
+
if (remembered !== undefined)
|
|
221
|
+
return remembered;
|
|
222
|
+
const verdict = probeCustomPattern(pattern, flags);
|
|
223
|
+
if (verdicts.size >= MAX_REMEMBERED_VERDICTS)
|
|
224
|
+
verdicts.clear();
|
|
225
|
+
verdicts.set(key, verdict);
|
|
226
|
+
return verdict;
|
|
227
|
+
}
|
|
228
|
+
/** Probe the rule's final pattern (flags and boundaries included). */
|
|
229
|
+
export function checkCustomRule(rule) {
|
|
230
|
+
let compiled;
|
|
231
|
+
try {
|
|
232
|
+
compiled = customRulePattern(rule);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return "invalid";
|
|
236
|
+
}
|
|
237
|
+
return checkCustomPattern(compiled.source, compiled.flags);
|
|
238
|
+
}
|
|
239
|
+
function probeCustomPattern(pattern, flags) {
|
|
9
240
|
let compiled;
|
|
10
241
|
try {
|
|
11
|
-
compiled = new RegExp(pattern,
|
|
242
|
+
compiled = new RegExp(pattern, flags);
|
|
12
243
|
}
|
|
13
244
|
catch {
|
|
14
|
-
return
|
|
245
|
+
return "invalid";
|
|
15
246
|
}
|
|
16
247
|
const start = Date.now();
|
|
17
248
|
try {
|
|
18
249
|
compiled.exec(REDOS_TEST_INPUT);
|
|
19
250
|
}
|
|
20
251
|
catch {
|
|
21
|
-
return
|
|
252
|
+
return "redos-suspect";
|
|
253
|
+
}
|
|
254
|
+
return Date.now() - start < REDOS_TIMEOUT_MS ? "ok" : "redos-suspect";
|
|
255
|
+
}
|
|
256
|
+
/** Descriptions of the custom rules `buildDynamicRules` skips, in config order. */
|
|
257
|
+
export function skippedCustomRules(config) {
|
|
258
|
+
const skipped = [];
|
|
259
|
+
for (const rule of config.custom_rules ?? []) {
|
|
260
|
+
const verdict = checkCustomRule(rule);
|
|
261
|
+
if (verdict !== "ok")
|
|
262
|
+
skipped.push({ description: rule.description, reason: verdict });
|
|
22
263
|
}
|
|
23
|
-
return
|
|
264
|
+
return skipped;
|
|
24
265
|
}
|
|
25
266
|
export function buildDynamicRules(config) {
|
|
26
267
|
const rules = [];
|
|
@@ -53,15 +294,20 @@ export function buildDynamicRules(config) {
|
|
|
53
294
|
});
|
|
54
295
|
}
|
|
55
296
|
for (const rule of config.custom_rules) {
|
|
56
|
-
|
|
57
|
-
|
|
297
|
+
const verdict = checkCustomRule(rule);
|
|
298
|
+
if (verdict !== "ok") {
|
|
299
|
+
console.warn(verdict === "invalid"
|
|
300
|
+
? `[leakshield] custom_rules: 略過無法編譯的 pattern —「${rule.description}」`
|
|
301
|
+
: `[leakshield] custom_rules: 略過疑似 ReDoS 的 pattern(計時啟發式檢查,非保證)—「${rule.description}」`);
|
|
58
302
|
continue;
|
|
59
303
|
}
|
|
304
|
+
const allow = (rule.allow ?? []).filter((value) => value.length > 0);
|
|
60
305
|
rules.push({
|
|
61
306
|
type: "CUSTOM",
|
|
62
307
|
severity: rule.severity,
|
|
63
308
|
description: rule.description,
|
|
64
|
-
pattern:
|
|
309
|
+
pattern: customRulePattern(rule),
|
|
310
|
+
...(allow.length > 0 ? { allow: new Set(allow) } : {}),
|
|
65
311
|
});
|
|
66
312
|
}
|
|
67
313
|
return rules;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact-match allowlists (issue #32).
|
|
3
|
+
*
|
|
4
|
+
* An allowlist entry suppresses a finding only when the matched text is exactly
|
|
5
|
+
* that string. It is not a pattern, it is not a substring test, and it does not
|
|
6
|
+
* rewrite anything: the content still leaves the machine as-is. That makes it a
|
|
7
|
+
* real bypass, which is why every suppression is counted here and surfaced by
|
|
8
|
+
* `--doctor`, and why the entry lists are capped at config load.
|
|
9
|
+
*
|
|
10
|
+
* The counter is process-wide and monotonic. It is diagnostic evidence ("how
|
|
11
|
+
* often did the allowlist actually fire?"), not a metric to optimize.
|
|
12
|
+
*/
|
|
13
|
+
/** Values that never produce a finding, for one rule or for every rule. */
|
|
14
|
+
export function allowSet(values) {
|
|
15
|
+
return new Set((values ?? []).filter((value) => value.length > 0));
|
|
16
|
+
}
|
|
17
|
+
/** True when `matchedText` is exactly an allowlisted value. */
|
|
18
|
+
export function isAllowlisted(matchedText, globalAllow, ruleAllow) {
|
|
19
|
+
if (globalAllow.size === 0 && (ruleAllow === undefined || ruleAllow.size === 0))
|
|
20
|
+
return false;
|
|
21
|
+
return globalAllow.has(matchedText) || ruleAllow?.has(matchedText) === true;
|
|
22
|
+
}
|
|
23
|
+
let suppressions = 0;
|
|
24
|
+
const MAX_COUNT = Number.MAX_SAFE_INTEGER;
|
|
25
|
+
/** Record one suppressed finding. Bounded so a long-lived process cannot wrap. */
|
|
26
|
+
export function noteAllowlistSuppression() {
|
|
27
|
+
if (suppressions < MAX_COUNT)
|
|
28
|
+
suppressions += 1;
|
|
29
|
+
}
|
|
30
|
+
/** Findings suppressed by an allowlist since this module was loaded. */
|
|
31
|
+
export function allowlistSuppressions() {
|
|
32
|
+
return suppressions;
|
|
33
|
+
}
|
|
34
|
+
/** Test seam only: reset the counter between cases. */
|
|
35
|
+
export function resetAllowlistSuppressionsForTests() {
|
|
36
|
+
suppressions = 0;
|
|
37
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IPv4 CIDR helpers for the private-range rule.
|
|
3
|
+
*
|
|
4
|
+
* Password-strength regex cannot express "address inside 172.16.0.0/12": a
|
|
5
|
+
* pattern that covers the range also covers version strings, and one that is
|
|
6
|
+
* narrow enough to avoid them misses octets. Membership is therefore a
|
|
7
|
+
* numeric comparison, and the network list is validated when the config
|
|
8
|
+
* loads so a typo cannot silently weaken the rule.
|
|
9
|
+
*/
|
|
10
|
+
/** Ranges the rule covers when `settings.private_cidrs` is empty. */
|
|
11
|
+
export const DEFAULT_PRIVATE_CIDRS = [
|
|
12
|
+
"10.0.0.0/8",
|
|
13
|
+
"172.16.0.0/12",
|
|
14
|
+
"192.168.0.0/16",
|
|
15
|
+
"100.64.0.0/10",
|
|
16
|
+
"169.254.0.0/16",
|
|
17
|
+
];
|
|
18
|
+
/** Dotted-quad to a 32-bit unsigned integer, or null when it is not an address. */
|
|
19
|
+
export function ipv4ToInt(raw) {
|
|
20
|
+
const parts = raw.split(".");
|
|
21
|
+
if (parts.length !== 4)
|
|
22
|
+
return null;
|
|
23
|
+
let value = 0;
|
|
24
|
+
for (const part of parts) {
|
|
25
|
+
if (!/^\d{1,3}$/.test(part))
|
|
26
|
+
return null;
|
|
27
|
+
const octet = Number(part);
|
|
28
|
+
if (octet > 255)
|
|
29
|
+
return null;
|
|
30
|
+
value = value * 256 + octet;
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
/** Parse `a.b.c.d/prefix`; returns null for anything else. */
|
|
35
|
+
export function parseCidr(text) {
|
|
36
|
+
const parts = text.trim().split("/");
|
|
37
|
+
if (parts.length !== 2)
|
|
38
|
+
return null;
|
|
39
|
+
const [address, prefixText] = parts;
|
|
40
|
+
if (!/^\d{1,2}$/.test(prefixText))
|
|
41
|
+
return null;
|
|
42
|
+
const prefix = Number(prefixText);
|
|
43
|
+
if (prefix > 32)
|
|
44
|
+
return null;
|
|
45
|
+
const addressValue = ipv4ToInt(address);
|
|
46
|
+
if (addressValue === null)
|
|
47
|
+
return null;
|
|
48
|
+
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
|
|
49
|
+
return { base: (addressValue & mask) >>> 0, mask };
|
|
50
|
+
}
|
|
51
|
+
/** Parse a configured list, falling back to the documented defaults. */
|
|
52
|
+
export function parseCidrList(entries) {
|
|
53
|
+
const source = entries !== undefined && entries.length > 0 ? entries : DEFAULT_PRIVATE_CIDRS;
|
|
54
|
+
const parsed = [];
|
|
55
|
+
for (const entry of source) {
|
|
56
|
+
const cidr = parseCidr(entry);
|
|
57
|
+
if (cidr !== null)
|
|
58
|
+
parsed.push(cidr);
|
|
59
|
+
}
|
|
60
|
+
return parsed;
|
|
61
|
+
}
|
|
62
|
+
/** True when the dotted-quad address falls inside one of the networks. */
|
|
63
|
+
export function containsAddress(cidrs, raw) {
|
|
64
|
+
const value = ipv4ToInt(raw);
|
|
65
|
+
if (value === null)
|
|
66
|
+
return false;
|
|
67
|
+
return cidrs.some((cidr) => ((value & cidr.mask) >>> 0) === cidr.base);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Every four-octet window in a dotted run, in order.
|
|
71
|
+
*
|
|
72
|
+
* `10.1.2.3.4` is not an address, but it contains `1.2.3.4`. A regex finds
|
|
73
|
+
* only the first four groups, so the runner is what keeps detection
|
|
74
|
+
* consistent for the addresses hiding behind that prefix.
|
|
75
|
+
*/
|
|
76
|
+
export function ipv4Windows(raw) {
|
|
77
|
+
const parts = raw.split(".");
|
|
78
|
+
const windows = [];
|
|
79
|
+
for (let start = 0; start + 4 <= parts.length; start += 1) {
|
|
80
|
+
windows.push(parts.slice(start, start + 4).join("."));
|
|
81
|
+
}
|
|
82
|
+
return windows;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* True when `raw` is inside one of the networks, including when it is a
|
|
86
|
+
* dotted run longer than four octets: the run is reported whole if any of
|
|
87
|
+
* its four-octet windows matches.
|
|
88
|
+
*/
|
|
89
|
+
export function containsAddressInRun(cidrs, raw) {
|
|
90
|
+
const groups = raw.split(".").length;
|
|
91
|
+
if (groups === 4)
|
|
92
|
+
return containsAddress(cidrs, raw);
|
|
93
|
+
if (groups > 4)
|
|
94
|
+
return ipv4Windows(raw).some((window) => containsAddress(cidrs, window));
|
|
95
|
+
return false;
|
|
96
|
+
}
|
package/dist/scanner/encoding.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Prevents attackers from bypassing detection using Base64, URL encoding, etc.
|
|
4
4
|
*/
|
|
5
5
|
import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
|
|
6
|
+
import { foldConfusables } from "./unicode.js";
|
|
6
7
|
// ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
|
|
7
8
|
/**
|
|
8
9
|
* Detects potential Base64 encoded strings.
|
|
@@ -160,7 +161,10 @@ export function scanTextWithDecoding(text, config, opts) {
|
|
|
160
161
|
// (a ZWSP in Base64 or hex), so decode the stripped form as well. Each
|
|
161
162
|
// candidate is decoded once even when both forms contain it.
|
|
162
163
|
const stripped = text.replace(ZERO_WIDTH_CHARS, "");
|
|
163
|
-
|
|
164
|
+
// A Cyrillic/Greek look-alike swapped into an encoded run hides it the same
|
|
165
|
+
// way, so decode the folded form too (#46). Decoding never recurses.
|
|
166
|
+
const folded = foldConfusables(stripped);
|
|
167
|
+
const sources = [...new Set([text, stripped, folded])];
|
|
164
168
|
const decodedCandidates = new Set();
|
|
165
169
|
const firstSighting = (kind, candidate) => {
|
|
166
170
|
const id = `${kind}\0${candidate}`;
|