/** * Glob matching for patterns the AGENT wrote (node9Firewall#509). * * The jail and the protected-file gate ask one question about a glob operand: * can it select one of node9's own fixed names? The pattern comes from the * agent's command, so it is hostile input. A backtracking matcher is the wrong * tool for that: picomatch needs 363 ms for `+(*)z` and never returns on * `+(*)+(*)z` or on ten `{*,?}` in a row, against names as short as `id_rsa` * (measured on 4.0.7, the latest release). A hook that does not return is a * hook that fails open. * * This matcher never backtracks. It reads the pattern once into a tree and * then moves a SET of positions in the name through that tree, with one * memoised answer per (group alternative, start position). Its cost is * polynomial in the pattern and the name whatever the pattern holds. * * Bash's own reading is the specification (jail-glob-bash.spec.ts compares * the two on generated patterns): * - brace expansion happens first and as TEXT: `!({a,b})` is the two words * `!(a)` and `!(b)`, and `.e{n,}v` is `.env` and `.ev`; * - a plain `*`, `?` or `[...]` never takes a leading dot, and a plain `*` * at the start does not even match empty in front of one (`*.env` does * not select `.env`); inside an extglob group a `*` may match empty there * (`@(*|x).env` does select it); * - `**(x)` is a `*` followed by the group `*(x)`; * * Two of bash's habits cannot be reproduced exactly, so the answer is given * as two bounds (see `matches`): what bash MAY select and what it SURELY * selects. A caller uses the one whose error is harmless to it. */ export interface GlobOptions { /** Wildcards may take a leading dot: find's `-name`, or a `dotglob` shell. */ dot?: boolean; nocase?: boolean; /** * false for a pattern handed to fnmatch (`find -name`): no brace expansion * and no extglob groups, their characters are literal. Default true. */ shell?: boolean; } /** * Past these a pattern is not compiled. No real command comes near them (the * longest glob operand in 85,558 real commands is far shorter), and inside * them the worst pattern costs a few milliseconds (glob-match.spec.ts). */ export const GLOB_LIMITS = { length: 256, pathLength: 4096, words: 64, depth: 12 } as const; type ClassItem = { lo: string; hi: string } | { re: RegExp }; type Node = | { t: 'lit'; c: string } | { t: 'any' } | { t: 'star' } | { t: 'class'; neg: boolean; items: ClassItem[] } | { t: 'group'; op: '@' | '+' | '*' | '?' | '!'; alts: Node[][] }; const POSIX_CLASSES: Record = { alpha: /[A-Za-z]/, digit: /[0-9]/, alnum: /[A-Za-z0-9]/, upper: /[A-Z]/, lower: /[a-z]/, space: /\s/, blank: /[ \t]/, punct: /[!-/:-@[-`{-~]/, xdigit: /[0-9A-Fa-f]/, word: /\w/, print: /[ -~]/, graph: /[!-~]/, cntrl: /[\x00-\x1f\x7f]/, }; // ── Glob syntax ───────────────────────────────────────────────────────────── const PLAIN_META_RE = /(?= 0; i = text.indexOf('{', i + 1)) { if (i > 0 && text[i - 1] === '\\') continue; const close = text.indexOf('}', i + 1); if (close < 0) return false; const comma = text.indexOf(',', i + 1); const dots = text.indexOf('..', i + 1); return comma >= 0 || dots >= 0; } return false; } /** * Does this operand hold glob syntax an unquoted shell word expands: `*`, `?`, * `[`, an extglob group, or a brace group? ONE definition for the jail and * the file-access walk, which used to disagree (the walk knew `{`, the jail * knew neither braces nor extglob). */ export function hasGlobSyntax(text: string): boolean { return PLAIN_META_RE.test(text) || EXTGLOB_OPENER_RE.test(text) || mayBeBraceGroup(text); } /** * Shell options that change what a glob selects, read off the command text: * `dotglob` (and a set `GLOBIGNORE`, which turns it on) lets a wildcard take a * leading dot (`shopt -s dotglob; cat ?env` reads `.env`), and `nocaseglob` * folds case (`cat .EN?`). The zsh spellings count too. A mention is enough: * the option may be set in a nested shell or an earlier statement, and reading * a glob more widely only makes the jail stricter. */ const DOTGLOB_RE = /\b(?:dotglob|GLOBIGNORE|globdots|glob_dots)\b/i; const NOCASEGLOB_RE = /\b(?:nocaseglob|nocase_glob|no_case_glob|case_glob)\b/i; export function shellGlobMode(command: string): { dot: boolean; nocase: boolean } { return { dot: DOTGLOB_RE.test(command), nocase: NOCASEGLOB_RE.test(command) }; } // ── Brace expansion ───────────────────────────────────────────────────────── function matchingBrace(text: string, from: number): number { let depth = 0; for (let j = from; j < text.length; j++) { if (text[j] === '\\') j++; else if (text[j] === '{') depth++; else if (text[j] === '}' && --depth === 0) return j; } return -1; } function splitTopLevel(body: string): string[] { const out: string[] = []; let depth = 0; let cur = ''; for (let j = 0; j < body.length; j++) { const c = body[j]; if (c === '\\') { cur += c + (body[j + 1] ?? ''); j++; continue; } if (c === '{') depth++; else if (c === '}') depth--; if (c === ',' && depth === 0) { out.push(cur); cur = ''; } else cur += c; } out.push(cur); return out; } /** `{a..e}`, `{1..10}`, `{01..10..2}`: its words, null when the body is not a * sequence, 'wide' when it has more words than the limit. */ function sequenceWords(body: string): string[] | 'wide' | null { const m = /^(-?\d+|[A-Za-z])\.\.(-?\d+|[A-Za-z])(?:\.\.(-?\d+))?$/.exec(body); if (!m) return null; const numeric = /\d/.test(m[1]) && /\d/.test(m[2]); if (!numeric && (/\d/.test(m[1]) || /\d/.test(m[2]))) return null; const from = numeric ? parseInt(m[1], 10) : m[1].charCodeAt(0); const to = numeric ? parseInt(m[2], 10) : m[2].charCodeAt(0); const step = Math.max(1, Math.abs(parseInt(m[3] ?? '1', 10)) || 1); if (Math.abs(to - from) / step >= GLOB_LIMITS.words) return 'wide'; const padded = numeric && (/^-?0\d/.test(m[1]) || /^-?0\d/.test(m[2])); const width = padded ? Math.max(m[1].length, m[2].length) : 0; const out: string[] = []; for (let v = from; from <= to ? v <= to : v >= to; v += from <= to ? step : -step) { if (!numeric) out.push(String.fromCharCode(v)); else if (!width) out.push(String(v)); else out.push((v < 0 ? '-' : '') + String(Math.abs(v)).padStart(width - (v < 0 ? 1 : 0), '0')); } return out; } /** * Brace expansion as text, before any glob reading (bash's order). Returns * null when the word expands to more than GLOB_LIMITS.words words. */ export function braceExpand(text: string): string[] | null { let budget = GLOB_LIMITS.words; const expand = (word: string): string[] | null => { for (let i = 0; i < word.length; i++) { if (word[i] === '\\') { i++; continue; } if (word[i] !== '{') continue; const close = matchingBrace(word, i); // No closing brace for this one; an inner `{` may still have its own. if (close < 0) continue; const body = word.slice(i + 1, close); let alternatives: string[]; const sequence = sequenceWords(body); if (sequence === 'wide') return null; if (sequence) alternatives = sequence; else { alternatives = splitTopLevel(body); // `{a}` is not a group: bash keeps the braces and reads on inside. if (alternatives.length < 2) continue; } const out: string[] = []; for (const alternative of alternatives) { const rest = expand(word.slice(0, i) + alternative + word.slice(close + 1)); if (rest === null) return null; for (const w of rest) out.push(w); if (out.length > GLOB_LIMITS.words) return null; } return out; } if (--budget < 0) return null; return [word]; }; return expand(text); } // ── Pattern tree ──────────────────────────────────────────────────────────── interface Bracket { /** The index after the closing `]`. */ end: number; neg: boolean; items: ClassItem[]; /** Holds an equivalence class (`[=e=]`), a collating symbol (`[.e.]`) or an * unknown class name. bash does not read these the same way twice: * `.e[[=e=]][en]` selects both `.een` and `.en` (when the class does not * match, the `]` after it becomes a member and the expression runs on). A * pattern holding one is not compiled; nobody writes them by accident. */ unreadable: boolean; } /** * The bracket expression opened at `at`, or null when it never closes and the * `[` is literal. ONE reader, for the parser and for the pass that pairs * group parentheses, so the two cannot disagree on where an expression ends. * Reads ranges, a leading `!` or `^` and POSIX classes (`[:alpha:]`). */ function readBracket(text: string, at: number): Bracket | null { let j = at + 1; let neg = false; if (text[j] === '!' || text[j] === '^') { neg = true; j++; } const items: ClassItem[] = []; let unreadable = false; for (let first = true; j < text.length; first = false) { const c = text[j]; if (c === ']' && !first) return { end: j + 1, neg, items, unreadable }; const kind = c === '[' ? text[j + 1] : ''; if (kind === ':' || kind === '=' || kind === '.') { const end = text.indexOf(`${kind}]`, j + 2); if (end > 0) { const name = text.slice(j + 2, end); const re = kind === ':' ? POSIX_CLASSES[name] : undefined; if (re) items.push({ re }); else unreadable = true; j = end + 2; continue; } } const lo = c === '\\' && j + 1 < text.length ? text[++j] : c; j++; if (text[j] === '-' && j + 1 < text.length && text[j + 1] !== ']') { const escaped = text[j + 1] === '\\' && j + 2 < text.length; items.push({ lo, hi: escaped ? text[j + 2] : text[j + 1] }); j += escaped ? 3 : 2; } else items.push({ lo, hi: lo }); } return null; } /** * The extglob openers that have a closing `)`, found in one pass. An opener * that never closes is literal text; knowing that before parsing means the * parser never tries a group and then re-reads the same text as literals, * which doubled its work per unclosed opener (`@(a@(a@(a...`). */ function closedGroups(text: string): Set { const closed = new Set(); const open: number[] = []; for (let i = 0; i < text.length; i++) { const c = text[i]; if (c === '\\') i++; else if (c === '[') { const bracket = readBracket(text, i); if (bracket) i = bracket.end - 1; } else if (text[i + 1] === '(' && '@+*?!'.includes(c)) { open.push(i); i++; } else if (c === ')' && open.length) closed.add(open.pop() as number); } return closed; } /** null: the pattern nests groups deeper than GLOB_LIMITS.depth, or holds a * bracket element that is not read (readBracket). */ function parsePattern(text: string, extglob: boolean): Node[] | null { let i = 0; let tooDeep = false; let unreadable = false; const closed = extglob ? closedGroups(text) : new Set(); /** The alternatives of a group whose opener was just read, or null when the * group never closes (its opener is then literal text). */ const alternatives = (depth: number): Node[][] | null => { const start = i; const out: Node[][] = []; for (;;) { out.push(sequence('|)', depth)); if (i >= text.length) { i = start; return null; } if (text[i++] === ')') return out; } }; const atom = (depth: number): Node => { const c = text[i]; if (c === '\\' && i + 1 < text.length) { i += 2; return { t: 'lit', c: text[i - 1] }; } if (closed.has(i)) { if (depth >= GLOB_LIMITS.depth) tooDeep = true; else { const save = i; i += 2; const alts = alternatives(depth + 1); if (alts) return { t: 'group', op: c as '@' | '+' | '*' | '?' | '!', alts }; i = save; } } if (c === '*') { // `**(x)` is a star and then the group `*(x)`: the last star of a run // belongs to the group that follows it. i++; while (text[i] === '*' && !closed.has(i)) i++; return { t: 'star' }; } if (c === '?') { i++; return { t: 'any' }; } if (c === '[') { const bracket = readBracket(text, i); if (bracket) { i = bracket.end; if (bracket.unreadable) unreadable = true; return { t: 'class', neg: bracket.neg, items: bracket.items }; } } i++; return { t: 'lit', c }; }; const sequence = (stops: string, depth: number): Node[] => { const nodes: Node[] = []; while (i < text.length && !stops.includes(text[i]) && !tooDeep) nodes.push(atom(depth)); return nodes; }; // A stray `)` or `|` outside any group is literal text. const nodes: Node[] = []; while (i < text.length && !tooDeep) nodes.push(atom(0)); return tooDeep || unreadable ? null : nodes; } // ── Matching ──────────────────────────────────────────────────────────────── type Positions = Set; /** A node bash reads as part of a run of wildcards after a `*`: another `*`, * a `?`, or a `?(...)` / `*(...)` group. */ const inStarRun = (node: Node): boolean => node.t === 'star' || node.t === 'any' || (node.t === 'group' && (node.op === '?' || node.op === '*')); /** * Does the pattern select the name? * * Bash's matcher cannot be reproduced exactly: after a `*` it never tries the * rest of the pattern against an empty tail (`*+(|x)` does not select `h`), * and a negated group reached there matches whatever follows (`.env*!(x)zzz` * selects `.env`). So the answer comes as two bounds: * - `upper`: true whenever bash selects the name. A negated group stands * for any stretch, and the star-then-negation case is accepted. * - lower (`upper` false): true only when bash selects the name. A negated * group matches nothing, and a group after a run of wildcards must take * at least one character. * Both directions are checked against real bash (jail-glob-bash.spec.ts). */ function matches(nodes: Node[], s: string, dot: boolean, upper: boolean): boolean { const n = s.length; // A wildcard may not take a leading dot unless `dot`. const hidden = (p: number): boolean => p === 0 && !dot && s.charCodeAt(0) === 46; const inClass = (klass: { neg: boolean; items: ClassItem[] }, ch: string): boolean => { const hit = klass.items.some((item) => 're' in item ? item.re.test(ch) : ch >= item.lo && ch <= item.hi ); return klass.neg ? !hit : hit; }; // Before it matches anything bash drops every dot name unless the pattern // itself starts with a dot (glob.c skipname; a leading group is read by rules // of its own). For the lower bound only a literal leading dot counts. if (!upper && hidden(0) && !(nodes[0]?.t === 'lit' && nodes[0].c === '.')) return false; // One answer per (alternative, start): a nested group is evaluated once per // position, never once per path that reaches it. const memo = new Map>(); const fromOne = (alt: Node[], p: number, depth: number): Positions => { let perStart = memo.get(alt); if (!perStart) memo.set(alt, (perStart = new Map())); let ends = perStart.get(p); if (!ends) perStart.set(p, (ends = run(alt, new Set([p]), depth))); return ends; }; const once = (alts: Node[][], starts: Positions, depth: number): Positions => { const out: Positions = new Set(); for (const alt of alts) for (const p of starts) for (const q of fromOne(alt, p, depth)) out.add(q); return out; }; const step = (node: Node, starts: Positions, depth: number): Positions => { const out: Positions = new Set(); switch (node.t) { case 'lit': for (const p of starts) if (s[p] === node.c) out.add(p + 1); return out; case 'any': for (const p of starts) if (p < n && !hidden(p)) out.add(p + 1); return out; case 'class': for (const p of starts) if (p < n && !hidden(p) && inClass(node, s[p])) out.add(p + 1); return out; case 'star': for (const p of starts) { if (hidden(p)) { // `*.env` does not select `.env`; `@(*|x).env` does. if (upper && depth > 0) out.add(p); continue; } for (let q = p; q <= n; q++) out.add(q); } return out; } const inner = depth + 1; if (node.op === '!') { if (!upper) return out; for (const p of starts) { const last = hidden(p) ? p : n; for (let q = p; q <= last; q++) out.add(q); } return out; } if (node.op === '@') return once(node.alts, starts, inner); if (node.op === '?') { for (const q of once(node.alts, starts, inner)) out.add(q); for (const p of starts) out.add(p); return out; } let frontier: Positions = node.op === '+' ? once(node.alts, starts, inner) : new Set(starts); for (const p of frontier) out.add(p); while (frontier.size) { const next: Positions = new Set(); for (const q of once(node.alts, frontier, inner)) { if (out.has(q)) continue; out.add(q); next.add(q); } frontier = next; } return out; }; const run = (sequence: Node[], starts: Positions, depth: number): Positions => { let current = starts; // Ends this sequence reaches by bash's star-then-negation rule (upper only). let early: Positions | null = null; let afterStar = false; for (let k = 0; k < sequence.length && current.size; k++) { const node = sequence[k]; if (afterStar && node.t === 'group') { if (upper && node.op === '!') { early ??= new Set(); for (const p of current) early.add(p); } if (!upper && (node.op === '@' || node.op === '+')) { // The group must take at least one character. const out: Positions = new Set(); for (const p of current) for (const q of step(node, new Set([p]), depth)) if (q > p) out.add(q); current = out; afterStar = false; continue; } // A `?(...)` or `*(...)` inside the run: bash tries it once or skips // it. Skipping is always one of its readings. if (!upper && inStarRun(node)) continue; } current = step(node, current, depth); afterStar = node.t === 'star' || (afterStar && inStarRun(node)); } if (!early) return current; for (const q of current) early.add(q); return early; }; return run(nodes, new Set([0]), 0).has(n); } /** A compiled agent-written pattern for one path segment. */ export interface CompiledGlob { /** False only when bash cannot select the name: use it to ask "can this * pattern reach a file I protect". */ mayMatch(name: string): boolean; /** True only when bash does select the name: use it to ask "does this * pattern select any name at all". */ surelyMatches(name: string): boolean; } /** * Compile an agent-written glob for one path segment. Returns null when the * pattern is past GLOB_LIMITS: the caller decides what an unreadable pattern * means for it (the jail reads it as aimed at the jailed name). Never throws. */ export function compileGlob(pattern: string, options: GlobOptions = {}): CompiledGlob | null { if (pattern.length > GLOB_LIMITS.length) return null; const shell = options.shell !== false; const fold = (text: string): string => (options.nocase ? text.toLowerCase() : text); const words = shell ? braceExpand(pattern) : [pattern]; if (words === null) return null; const compiled: Array<{ tree: Node[]; asWritten: Node[] | null }> = []; for (const word of words) { const tree = parsePattern(fold(word), shell); if (tree === null) return null; // `nocaseglob` folds case only where the shell expands something. A word // with no glob syntax is not expanded: `cat .ENV` opens a file named // `.ENV`. (It may still be `.env` on a file system that ignores case, so // only the lower bound reads such a word as written.) const literal = options.nocase && !(shell ? hasGlobSyntax(word) : PLAIN_META_RE.test(word)); compiled.push({ tree, asWritten: literal ? parsePattern(word, shell) : null }); } const dot = options.dot === true; return { mayMatch: (name) => compiled.some(({ tree }) => matches(tree, fold(name), dot, true)), surelyMatches: (name) => compiled.some(({ tree, asWritten }) => asWritten ? matches(asWritten, name, dot, false) : matches(tree, fold(name), dot, false) ), }; } /** * Compile an agent-written glob that spans directories (`/etc/sudoers.?/x`, * `/usr/**` + `/x`) for whole paths: the path is cut at `/`, `**` alone in a * segment stands for any number of segments, every other segment is read as * compileGlob reads it. Braces are expanded over the whole pattern first, so a * group may span a `/`. The result answers "may bash select this path" (the * upper bound). null as for compileGlob. */ export function compilePathGlob( pattern: string, options: GlobOptions = {} ): ((path: string) => boolean) | null { // The length limit is per segment: a path glob is matched segment by // segment, and a deep working directory must not make `build/**/*.map` // unreadable. if (pattern.length > GLOB_LIMITS.pathLength) return null; const shell = options.shell !== false; const fold = (text: string): string => (options.nocase ? text.toLowerCase() : text); const words = shell ? braceExpand(fold(pattern)) : [fold(pattern)]; if (words === null) return null; const dot = options.dot === true; type Segment = Node[] | '**'; const compiled: Segment[][] = []; for (const word of words) { const segments: Segment[] = []; for (const segment of word.split('/')) { if (segment === '**') { segments.push('**'); continue; } if (segment.length > GLOB_LIMITS.length) return null; // Braces are already expanded; a `{` left here is literal. const tree = parsePattern(segment, shell); if (tree === null) return null; segments.push(tree); } compiled.push(segments); } return (path) => { const parts = fold(path).split('/'); return compiled.some((segments) => { // reach: the segments read so far can end having consumed j path parts. let reach = new Set([0]); for (const segment of segments) { const next = new Set(); for (const j of reach) { if (segment === '**') for (let k = j; k <= parts.length; k++) next.add(k); else if (j < parts.length && matches(segment, parts[j], dot, true)) next.add(j + 1); } if (!next.size) return false; reach = next; } return reach.has(parts.length); }); }; }