mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-30 20:04:15 +01:00
Secrets check catches Google keys in encoded text, reads later declarators and reports provider keys once (GST-4104) (#4871)
The secrets check now catches more Google API keys in encoded text, reads each declaration under the name its value is assigned to, reports a provider key once, and stops matching look-alike values against your environment's secrets. Why: these gaps were left open on the last secrets-check change, and two of them made a check fail in a way no allowlist entry could clear. Nothing to do: the fixes ship in the next release. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p2/adversarial-native#1 reader=adversarial-native Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p2/outside-voice#2 reader=outside-voice Review-Finding: p2/outside-voice#3 reader=outside-voice Review-Finding: p2/outside-voice#4 reader=outside-voice
This commit is contained in:
1 parent
dade7cacf1
commit
d785fc4acf
5 files changed
+238
-15
No files matched your search
+53
-8
@@ -403,6 +403,13 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
|
||||
const findings: Finding[] = [];
|
||||
// Dedup by (id, original-offset) so overlapping global matches don't double-count.
|
||||
const seen = new Set<string>();
|
||||
// GST-4104: the spans of secret findings from rules other than env.kv*, so a
|
||||
// declaration rule (env.kv.js, env.kv.go) whose whole literal is exactly one
|
||||
// of them stays quiet: a provider key in `const apiKey = "<key>"` reports as
|
||||
// its provider rule alone, and allowlisting that rule clears it, while a
|
||||
// literal that holds more (`"<key>" + "<other>"`) keeps the declaration
|
||||
// finding. Every provider rule comes before the declaration rules in PATTERNS.
|
||||
const covered = new Set<string>();
|
||||
|
||||
for (const pat of PATTERNS) {
|
||||
const re = new RegExp(pat.regex.source, withFlags(pat.regex.flags));
|
||||
@@ -433,10 +440,17 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
|
||||
if (pat.id === "pii.email" && emailAllowed(span, opts, normalized, normOffset))
|
||||
continue;
|
||||
|
||||
if (DECLARATION_RULES.has(pat.id) && covered.has(`${normOffset}:${span.length}`)) {
|
||||
const quote = normalized[normOffset - 1];
|
||||
const rest = normalized.slice(normOffset + span.length, normOffset + span.length + 80);
|
||||
if ((quote === '"' || quote === "'" || quote === "\x60") && rest[0] === quote && !/^.[ \t]*\+/.test(rest)) continue;
|
||||
}
|
||||
|
||||
const origOffset = map[Math.min(normOffset, map.length - 1)] ?? 0;
|
||||
const key = `${pat.id}:${origOffset}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
if (pat.category === "secret" && !pat.id.startsWith("env.kv")) covered.add(`${normOffset}:${span.length}`);
|
||||
|
||||
starts ??= lineStarts(input);
|
||||
const { line, col } = lineColAt(starts, input, origOffset);
|
||||
@@ -485,10 +499,24 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
|
||||
// and the allowlist and placeholder rules see both forms.
|
||||
const value = normalizeOriginal(raw).normalized;
|
||||
if (allow.has(raw) || allow.has(value) || value.length < MIN_ENV_VALUE_LENGTH || isPlaceholderSpan(value)) continue;
|
||||
for (const form of new Set([value, ...base64Forms(value), ...base64Forms(raw)])) {
|
||||
for (const { form, encoded, before, after } of [{ form: value, encoded: false }, ...base64Encodings(value), ...base64Encodings(raw)]) {
|
||||
// GST-4104: a base64 form leaves out the characters it shares with
|
||||
// neighbouring bytes, so the characters beside a match must carry the
|
||||
// value's bits there too; a value that differs only in those bits
|
||||
// (`build124` for `build123`) is not this secret. Either alphabet's
|
||||
// symbol reads as its index, since a form without symbols is the same
|
||||
// text in both.
|
||||
const fits = (c: string | undefined, edge?: Base64Edge) => {
|
||||
const index = c === undefined ? -1 : Math.max(BASE64_STANDARD.indexOf(c), BASE64_URL.indexOf(c));
|
||||
return !edge || index < 0 || (index & edge.mask) === edge.bits;
|
||||
};
|
||||
let from = 0;
|
||||
let normOffset: number;
|
||||
while ((normOffset = normalized.indexOf(form, from)) !== -1) {
|
||||
if (!fits(normalized[normOffset - 1], before) || !fits(normalized[normOffset + form.length], after)) {
|
||||
from = normOffset + 1;
|
||||
continue;
|
||||
}
|
||||
from = normOffset + form.length;
|
||||
const origOffset = map[Math.min(normOffset, map.length - 1)] ?? 0;
|
||||
// Keyed on the span, not the offset alone: when one credential's value is
|
||||
@@ -503,7 +531,7 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
|
||||
tier: "HIGH",
|
||||
severity: "HIGH",
|
||||
category: "secret",
|
||||
description: `Value of the ${name} environment variable${form === value ? "" : ", base64-encoded"}`,
|
||||
description: `Value of the ${name} environment variable${encoded ? ", base64-encoded" : ""}`,
|
||||
line,
|
||||
col,
|
||||
// A live credential: the name already says what leaked; show no bytes.
|
||||
@@ -535,6 +563,7 @@ const PUBLIC_ENV_NAME = /(^|_)PUBLIC(_|$)/i;
|
||||
/** gstack's own credential-named variables whose values are not secrets (bin/gstack-brain-lock.sh sets the lock token). */
|
||||
export const NON_SECRET_ENV_NAMES: ReadonlySet<string> = new Set(["GSTACK_BRAIN_LOCK_TOKEN"]);
|
||||
const MIN_ENV_VALUE_LENGTH = 8;
|
||||
const DECLARATION_RULES = new Set(["env.kv.js", "env.kv.go"]);
|
||||
|
||||
/**
|
||||
* The (name, value) pairs of `env` worth scanning for by value: credential-named
|
||||
@@ -559,19 +588,35 @@ const MIN_ENV_VALUE_LENGTH = 8;
|
||||
* bytes and drops the characters that also carry bits of a neighbouring byte:
|
||||
* 0, 2 or 3 at the front, and the last one when the value does not end on a
|
||||
* 3-byte boundary. Forms shorter than the minimum value length are dropped.
|
||||
* GST-4104: each form keeps the value's bits in the character dropped at each
|
||||
* end (the low 4 or 2 bits of the one before it, the high 2 or 4 bits of the
|
||||
* one after it), which scan checks against the text.
|
||||
*/
|
||||
const BASE64_LEAD = [0, 2, 3];
|
||||
export function base64Forms(value: string): string[] {
|
||||
const BASE64_LEAD_BITS = [0, 4, 2];
|
||||
const BASE64_TAIL_BITS = [0, 2, 4];
|
||||
const BASE64_STANDARD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
const BASE64_URL = BASE64_STANDARD.slice(0, 62) + "-_";
|
||||
interface Base64Edge { mask: number; bits: number }
|
||||
function base64Encodings(value: string): Array<{ form: string; encoded: true; before?: Base64Edge; after?: Base64Edge }> {
|
||||
const bytes = Buffer.from(value, "utf8");
|
||||
const forms = new Set<string>();
|
||||
const out: Array<{ form: string; encoded: true; before?: Base64Edge; after?: Base64Edge }> = [];
|
||||
for (const [shift, lead] of BASE64_LEAD.entries()) {
|
||||
const encoded = Buffer.concat([Buffer.alloc(shift), bytes]).toString("base64").replace(/=+$/, "");
|
||||
const core = encoded.slice(lead, encoded.length - ((shift + bytes.length) % 3 === 0 ? 0 : 1));
|
||||
const leadBits = BASE64_LEAD_BITS[shift]!;
|
||||
const tailBits = BASE64_TAIL_BITS[(shift + bytes.length) % 3]!;
|
||||
const core = encoded.slice(lead, encoded.length - (tailBits ? 1 : 0));
|
||||
if (core.length < MIN_ENV_VALUE_LENGTH) continue;
|
||||
forms.add(core);
|
||||
forms.add(core.replace(/\+/g, "-").replace(/\//g, "_"));
|
||||
const edge = (c: string, mask: number) => ({ mask, bits: BASE64_STANDARD.indexOf(c) & mask });
|
||||
const before = leadBits ? edge(encoded[lead - 1]!, (1 << leadBits) - 1) : undefined;
|
||||
const after = tailBits ? edge(encoded[encoded.length - 1]!, ((1 << tailBits) - 1) << (6 - tailBits)) : undefined;
|
||||
out.push({ form: core, encoded: true, before, after });
|
||||
out.push({ form: core.replace(/\+/g, "-").replace(/\//g, "_"), encoded: true, before, after });
|
||||
}
|
||||
return [...forms];
|
||||
return out;
|
||||
}
|
||||
export function base64Forms(value: string): string[] {
|
||||
return [...new Set(base64Encodings(value).map(({ form }) => form))];
|
||||
}
|
||||
|
||||
export function credentialEnvValues(env: Record<string, string | undefined>): Array<{ name: string; value: string }> {
|
||||
|
||||
+37
-6
@@ -251,8 +251,10 @@ export function looksLikeRunStamp(span: string): boolean {
|
||||
* `AQ.`) cannot occur by chance and always reports. A match is chance when it
|
||||
* starts at least 64 characters into a run of 200 or more characters of one
|
||||
* alphabet (standard `+` and `/` for `AIza`, url-safe `-` and `_` for
|
||||
* `sk-`), the 64 or more characters before it hold an uppercase letter, a
|
||||
* lowercase letter and a digit with no `=` (padding only ends a run), and at
|
||||
* `sk-`) that the match itself belongs to (GST-4104: an `AIza` key holding
|
||||
* `-` or `_` is never chance in standard base64), the 64 or more
|
||||
* characters before it hold an uppercase letter, a lowercase letter and a
|
||||
* digit with no `=` (padding only ends a run), and at
|
||||
* most one in 16 of them is a `+`, `/`, `-` or `_`, so a path or a long
|
||||
* name (`MY_LONG_SERVICE_..._KEY_V2=`, `/v1/Projects/Abc123/...`) never
|
||||
* qualifies. A known secret's exact value, base64 forms included, is found by
|
||||
@@ -267,6 +269,7 @@ function chanceMatchInBase64(match: RegExpExecArray): boolean {
|
||||
const { start, end } = spanBounds(match);
|
||||
const text = match.input;
|
||||
const alphabet = text.startsWith("sk-", start) ? BASE64_URL : BASE64_STANDARD;
|
||||
for (let i = start; i < end; i++) if (!alphabet.test(text[i]!)) return false;
|
||||
let before = 0;
|
||||
while (before < BASE64_RUN_MIN && start - before > 0 && alphabet.test(text[start - before - 1]!)) before++;
|
||||
if (before < BASE64_DEPTH_MIN) return false;
|
||||
@@ -1334,6 +1337,32 @@ function declaredLiteralIsSecret(span: string, match: RegExpExecArray): boolean
|
||||
return literal.split(/\s+/).some(isSecretShapedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* GST-4104: the name env.kv.js binds, read from the text before the
|
||||
* declaration's `=`: the last declarator after a comma outside brackets,
|
||||
* quotes and block comments, then the last word before its type's `:`. The type reads up to the
|
||||
* `=`, so `let token: string, buildHash =` names `buildHash` (the value is
|
||||
* not the token's), while `Brand<string, "key">` stays one type.
|
||||
*/
|
||||
function declaredName(head: string): string | undefined {
|
||||
let from = 0;
|
||||
for (let i = 0, depth = 0; i < head.length; i++) {
|
||||
const c = head[i]!;
|
||||
if (c === '"' || c === "'" || c === "\x60") {
|
||||
const close = head.indexOf(c, i + 1);
|
||||
if (close < 0) break;
|
||||
i = close;
|
||||
} else if (c === "/" && head[i + 1] === "*") {
|
||||
const close = head.indexOf("*/", i + 2);
|
||||
if (close < 0) break;
|
||||
i = close + 1;
|
||||
} else if ("<([{".includes(c)) depth++;
|
||||
else if (">)]}".includes(c)) depth--;
|
||||
else if (c === "," && depth === 0) from = i + 1;
|
||||
}
|
||||
return /([$\w]+)[?!]?[ \t]*$/.exec(head.slice(from).split(":", 1)[0]!)?.[1]?.replace(/\$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* GBRA-108: in a .json, .json5, .jsonc or .jsonl file, a field named exactly `"key"` whose value is a short
|
||||
* lowercase path of words (`"key": "sources/vector-index"`,
|
||||
@@ -1992,8 +2021,10 @@ export const PATTERNS: RedactPattern[] = [
|
||||
// "<key>";`) gave no finding. This rule reads one to four of `declare`,
|
||||
// `public`, `private`, `protected`, `static`, `readonly`, `override`,
|
||||
// `accessor`, `const`, `let` and `var` (after an optional `export`),
|
||||
// an optional `#` private name, a secret-named name with an optional
|
||||
// `?`/`!` and type (which stops at `;`, so the value belongs to the same
|
||||
// up to four earlier declarators without a value (`let a: string, token
|
||||
// = "<key>"`; GST-4104; each type ends on a non-space so spaces before a
|
||||
// comma have one reading), an optional `#` private name, a secret-named
|
||||
// name with an optional `?`/`!` and type (which stops at `;`, so the value belongs to the same
|
||||
// declaration), then `=` and a quoted or template literal (an empty
|
||||
// first piece of a `+` chain and leading spaces are read past), at a line
|
||||
// start (diff markers as env.kv) or after `//` or `/*`. A name with no
|
||||
@@ -2004,10 +2035,10 @@ export const PATTERNS: RedactPattern[] = [
|
||||
// exemptions. It is its own pattern so env.kv's matches are unchanged,
|
||||
// and validate keeps it to .js, .jsx, .ts, .tsx, .mjs, .cjs, .mts and .cts
|
||||
// files; a scan without a path is env.kv.rust's.
|
||||
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:\/{2,3}|\/\*{1,2})))[ \t]*(?:export[ \t]+)?(?:(?:declare|public|private|protected|static|readonly|override|accessor|const|let|var)[ \t]+){1,4}#?[$\w]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[?!]?(?:[ \t]*:[^=;\n]{1,120}?)?[ \t]*=[ \t]*["'\x60]((?:["'\x60][ \t]*\+[ \t]*["'\x60]|[ \t]+)?[^\s'"\x60\\]{8,}|[^\s'"\x60\\]{1,7}(?=["'\x60]?[ \t]*\+))/i,
|
||||
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:\/{2,3}|\/\*{1,2})))[ \t]*(?:export[ \t]+)?(?:(?:declare|public|private|protected|static|readonly|override|accessor|const|let|var)[ \t]+){1,4}(?:[$\w]+[?!]?(?:[ \t]*:[^=;,\n]{0,119}[^=;,\s])?[ \t]*,[ \t]*){0,4}#?[$\w]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[?!]?(?:[ \t]*:[^=;\n]{1,120}?)?[ \t]*=[ \t]*["'\x60]((?:["'\x60][ \t]*\+[ \t]*["'\x60]|[ \t]+)?[^\s'"\x60\\]{8,}|[^\s'"\x60\\]{1,7}(?=["'\x60]?[ \t]*\+))/i,
|
||||
validate: (span, match, opts) => {
|
||||
if (!opts?.sourcePath || !JS_SOURCE.test(opts.sourcePath)) return false;
|
||||
const name = /([$\w]+)[?!]?[ \t]*(?::[^=;\n]*)?=/.exec(match[0])?.[1]?.replace(/\$/g, "");
|
||||
const name = declaredName(match[0].slice(0, match[0].indexOf("=")));
|
||||
return !!name && isCredentialShapedEnvName(`${name}=`) && declaredLiteralIsSecret(span, match);
|
||||
},
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user