GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — claude-code-source-code/src/utils/bash/ast.ts at main · memoryblade/claude-code-source-code Expand file tree/ Copy pathast.tsMore file actions 2679 lines (2569 loc) · 109 KB / Copy pathast.tsFile metadata and controls2679 lines (2569 loc) · 109 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /** * AST-based bash command analysis using tree-sitter. * * This module replaces the shell-quote + hand-rolled char-walker approach in * bashSecurity.ts / commands.ts. Instead of detecting parser differentials * one-by-one, we parse with tree-sitter-bash and walk the tree with an * EXPLICIT allowlist of node types. Any node type not in the allowlist causes * the entire command to be classified as 'too-complex', which means it goes * through the normal permission prompt flow. * * The key design property is FAIL-CLOSED: we never interpret structure we * don't understand. If tree-sitter produces a node we haven't explicitly * allowlisted, we refuse to extract argv and the caller must ask the user. * * This is NOT a sandbox. It does not prevent dangerous commands from running. * It answers exactly one question: "Can we produce a trustworthy argv[] for * each simple command in this string?" If yes, downstream code can match * argv[0] against permission rules and flag allowlists. If no, ask the user. */ import { SHELL_KEYWORDS } from './bashParser.js' import type { Node } from './parser.js' import { PARSE_ABORTED, parseCommandRaw } from './parser.js' export type Redirect = { op: '>' | '>>' | '<' | '<<' | '>&' | '>|' | '<&' | '&>' | '&>>' | '<<<' target: string fd?: number } export type SimpleCommand = { /** argv[0] is the command name, rest are arguments with quotes already resolved */ argv: string[] /** Leading VAR=val assignments */ envVars: { name: string; value: string }[] /** Output/input redirects */ redirects: Redirect[] /** Original source span for this command (for UI display) */ text: string } export type ParseForSecurityResult = | { kind: 'simple'; commands: SimpleCommand[] } | { kind: 'too-complex'; reason: string; nodeType?: string } | { kind: 'parse-unavailable' } /** * Structural node types that represent composition of commands. We recurse * through these to find the leaf `command` nodes. `program` is the root; * `list` is `a && b || c`; `pipeline` is `a | b`; `redirected_statement` * wraps a command with its redirects. Semicolon-separated commands appear * as direct siblings under `program` (no wrapper node). */ const STRUCTURAL_TYPES = new Set([ 'program', 'list', 'pipeline', 'redirected_statement', ]) /** * Operator tokens that separate commands. These are leaf nodes that appear * between commands in `list`/`pipeline`/`program` and carry no payload. */ const SEPARATOR_TYPES = new Set(['&&', '||', '|', ';', '&', '|&', '\n']) /** * Placeholder string used in outer argv when a $() is recursively extracted. * The actual $() output is runtime-determined; the inner command(s) are * checked against permission rules separately. Using a placeholder keeps * the outer argv clean (no multi-line heredoc bodies polluting path * extraction or triggering newline checks). */ const CMDSUB_PLACEHOLDER = '__CMDSUB_OUTPUT__' /** * Placeholder for simple_expansion ($VAR) references to variables set earlier * in the same command via variable_assignment. Since we tracked the assignment, * we know the var exists and its value is either a static string or * __CMDSUB_OUTPUT__ (if set via $()). Either way, safe to substitute. */ const VAR_PLACEHOLDER = '__TRACKED_VAR__' /** * All placeholder strings. Used for defense-in-depth: if a varScope value * contains ANY placeholder (exact or embedded), the value is NOT a pure * literal and cannot be trusted as a bare argument. Covers composites like * `VAR="prefix$(cmd)"` → `"prefix__CMDSUB_OUTPUT__"` — the substring check * catches these where exact-match Set.has() would miss. * * Also catches user-typed literals that collide with placeholder strings: * `VAR=__TRACKED_VAR__ && rm $VAR` — treated as non-literal (conservative). */ function containsAnyPlaceholder(value: string): boolean { return value.includes(CMDSUB_PLACEHOLDER) || value.includes(VAR_PLACEHOLDER) } /** * Unquoted $VAR in bash undergoes word-splitting (on $IFS: space/tab/NL) * and pathname expansion (glob matching on * ? [). Our argv stores a * single string — but at runtime bash may produce MULTIPLE args, or paths * matched by a glob. A value containing these metacharacters cannot be * trusted as a bare arg: `VAR="-rf /" && rm $VAR` → bash runs `rm -rf /` * (two args) but our argv would have `['rm', '-rf /']` (one arg). Similarly * `VAR="/etc/*" && cat $VAR` → bash expands to all /etc files. * * Inside double-quotes ("$VAR"), neither splitting nor globbing applies — * the value IS a single literal argument. */ const BARE_VAR_UNSAFE_RE = /[ \t\n*?[]/ // stdbuf flag forms — hoisted from the wrapper-stripping while-loop const STDBUF_SHORT_SEP_RE = /^-[ioe]$/ const STDBUF_SHORT_FUSED_RE = /^-[ioe]./ const STDBUF_LONG_RE = /^--(input|output|error)=/ /** * Known-safe environment variables that bash sets automatically. Their values * are controlled by the shell/OS, not arbitrary user input. Referencing these * via $VAR is safe — the expansion is deterministic and doesn't introduce * injection risk. Covers `$HOME`, `$PWD`, `$USER`, `$PATH`, `$SHELL`, etc. * Intentionally small: only vars that are always set by bash/login and whose * values are paths/names (not arbitrary content). */ const SAFE_ENV_VARS = new Set([ 'HOME', // user's home directory 'PWD', // current working directory (bash maintains) 'OLDPWD', // previous directory 'USER', // current username 'LOGNAME', // login name 'SHELL', // user's login shell 'PATH', // executable search path 'HOSTNAME', // machine hostname 'UID', // user id 'EUID', // effective user id 'PPID', // parent process id 'RANDOM', // random number (bash builtin) 'SECONDS', // seconds since shell start 'LINENO', // current line number 'TMPDIR', // temp directory // Special bash variables — always set, values are shell-controlled: 'BASH_VERSION', // bash version string 'BASHPID', // current bash process id 'SHLVL', // shell nesting level 'HISTFILE', // history file path 'IFS', // field separator (NOTE: only safe INSIDE strings; as bare arg // $IFS is the classic injection primitive and the insideString // gate in resolveSimpleExpansion correctly blocks it) ]) /** * Special shell variables ($?, $$, $!, $#, $0-$9). tree-sitter uses * `special_variable_name` for these (not `variable_name`). Values are * shell-controlled: exit status, PIDs, positional args. Safe to resolve * ONLY inside strings (same rationale as SAFE_ENV_VARS — as bare args * their value IS the argument and might be a path/flag from $1 etc.). * * SECURITY: '@' and '*' are NOT in this set. Inside "...", they expand to * the positional params — which are EMPTY in a fresh BashTool shell (how we * always spawn). Returning VAR_PLACEHOLDER would lie: `git "push$*"` gives * argv ['git','push__TRACKED_VAR__'] while bash passes ['git','push']. Deny * rule Bash(git push:*) fails on both .text (raw `$*`) AND rebuilt argv * (placeholder). With them removed, resolveSimpleExpansion falls through to * tooComplex for `$*` / `$@`. `echo "args: $*"` becomes too-complex — * acceptable (rare in BashTool usage; `"$@"` even rarer). */ const SPECIAL_VAR_NAMES = new Set([ '?', // exit status of last command '$', // current shell PID '!', // last background PID '#', // number of positional params '0', // script name '-', // shell option flags ]) /** * Node types that mean "this command cannot be statically analyzed." These * either execute arbitrary code (substitutions, subshells, control flow) or * expand to values we can't determine statically (parameter/arithmetic * expansion, brace expressions). * * This set is not exhaustive — it documents KNOWN dangerous types. The real * safety property is the allowlist in walkArgument/walkCommand: any type NOT * explicitly handled there also triggers too-complex. */ const DANGEROUS_TYPES = new Set([ 'command_substitution', 'process_substitution', 'expansion', 'simple_expansion', 'brace_expression', 'subshell', 'compound_statement', 'for_statement', 'while_statement', 'until_statement', 'if_statement', 'case_statement', 'function_definition', 'test_command', 'ansi_c_string', 'translated_string', 'herestring_redirect', 'heredoc_redirect', ]) /** * Numeric IDs for analytics (logEvent doesn't accept strings). Index into * DANGEROUS_TYPES. Append new entries at the end to keep IDs stable. * 0 = unknown/other, -1 = ERROR (parse failure), -2 = pre-check. */ const DANGEROUS_TYPE_IDS = [...DANGEROUS_TYPES] export function nodeTypeId(nodeType: string | undefined): number { if (!nodeType) return -2 if (nodeType === 'ERROR') return -1 const i = DANGEROUS_TYPE_IDS.indexOf(nodeType) return i >= 0 ? i + 1 : 0 } /** * Redirect operator tokens → canonical operator. tree-sitter produces these * as child nodes of `file_redirect`. */ const REDIRECT_OPS: Record<string, Redirect['op']> = { '>': '>', '>>': '>>', '<': '<', '>&': '>&', '<&': '<&', '>|': '>|', '&>': '&>', '&>>': '&>>', '<<<': '<<<', } /** * Brace expansion pattern: {a,b} or {a..b}. Must have , or .. inside * braces. We deliberately do NOT try to determine whether the opening brace * is backslash-escaped: tree-sitter doesn't unescape backslashes, so * distinguishing `\{a,b}` (escaped, literal) from `\\{a,b}` (literal * backslash + expansion) would require reimplementing bash quote removal. * Reject both — the escaped-brace case is rare and trivially rewritten * with single quotes. */ const BRACE_EXPANSION_RE = /\{[^{}\s]*(,|\.\.)[^{}\s]*\}/ /** * Control characters that bash silently drops but confuse static analysis. * Includes CR (0x0D): tree-sitter treats CR as a word separator but bash's * default IFS does not include CR, so tree-sitter and bash disagree on * word boundaries. */ // eslint-disable-next-line no-control-regex const CONTROL_CHAR_RE = /[\x00-\x08\x0B-\x1F\x7F]/ /** * Unicode whitespace beyond ASCII. These render invisibly (or as regular * spaces) in terminals so a user reviewing the command can't see them, but * bash treats them as literal word characters. Blocks NBSP, zero-width * spaces, line/paragraph separators, BOM. */ const UNICODE_WHITESPACE_RE = /[\u00A0\u1680\u2000-\u200B\u2028\u2029\u202F\u205F\u3000\uFEFF]/ /** * Backslash immediately before whitespace. bash treats `\ ` as a literal * space inside the current word, but tree-sitter returns the raw text with * the backslash still present. argv[0] from tree-sitter is `cat\ test` * while bash runs `cat test` (with a literal space). Rather than * reimplement bash's unescaping rules, we reject these — they're rare in * practice and trivial to rewrite with quotes. * * Also matches `\` before newline (line continuation) when adjacent to a * non-whitespace char. `tr\<NL>aceroute` — bash joins to `traceroute`, but * tree-sitter splits into two words (differential). When `\<NL>` is preceded * by whitespace (e.g. `foo && \<NL>bar`), there's no word to join — both * parsers agree, so we allow it. */ const BACKSLASH_WHITESPACE_RE = /\\[ \t]|[^ \t\n\\]\\\n/ /** * Zsh dynamic named directory expansion: ~[name]. In zsh this invokes the * zsh_directory_name hook, which can run arbitrary code. bash treats it as * a literal tilde followed by a glob character class. Since BashTool runs * via the user's default shell (often zsh), reject conservatively. */ const ZSH_TILDE_BRACKET_RE = /~\[/ /** * Zsh EQUALS expansion: word-initial `=cmd` expands to the absolute path of * `cmd` (equivalent to `$(which cmd)`). `=curl evil.com` runs as * `/usr/bin/curl evil.com`. tree-sitter parses `=curl` as a literal word, so * a `Bash(curl:*)` deny rule matching on base command name won't see `curl`. * Only matches word-initial `=` followed by a command-name char — `VAR=val` * and `--flag=val` have `=` mid-word and are not expanded by zsh. */ const ZSH_EQUALS_EXPANSION_RE = /(?:^|[\s;&|])=[a-zA-Z_]/ /** * Brace character combined with quote characters. Constructions like * `{a'}',b}` use quoted braces inside brace expansion context to obfuscate * the expansion from regex-based detection. In bash, `{a'}',b}` expands to * `a} b` (the quoted `}` becomes literal inside the first alternative). * These are hard to analyze correctly and have no legitimate use in * commands we'd want to auto-allow. * * This check runs on a version of the command with `{` masked out of * single-quoted and double-quoted spans, so JSON payloads like * `curl -d '{"k":"v"}'` don't trigger a false positive. Brace expansion * cannot occur inside quotes, so a `{` there can never start an obfuscation * pattern. The quote characters themselves stay visible so `{a'}',b}` and * `{@'{'0},...}` still match via the outer unquoted `{`. */ const BRACE_WITH_QUOTE_RE = /\{[^}]*['"]/ /** * Mask `{` characters that appear inside single- or double-quoted contexts. * Uses a single-pass bash-aware quote-state scanner instead of a regex. * * A naive regex (`/'[^']*'/g`) mis-detects spans when a `'` appears inside * a double-quoted string: for `echo "it's" {a'}',b}`, it matches from the * `'` in `it's` across to the `'` in `{a'}`, masking the unquoted `{` and * producing a false negative. The scanner tracks actual bash quote state: * `'` toggles single-quote only in unquoted context; `"` toggles * double-quote only outside single quotes; `\` escapes the next char in * unquoted context and escapes `"` / `\\` inside double quotes. * * Brace expansion is impossible in both quote contexts, so masking `{` in * either is safe. Secondary defense: BRACE_EXPANSION_RE in walkArgument. */ function maskBracesInQuotedContexts(cmd: string): string { // Fast path: no `{` → nothing to mask. Skips the char-by-char scan for // the >90% of commands with no braces (`ls -la`, `git status`, etc). if (!cmd.includes('{')) return cmd const out: string[] = [] let inSingle = false let inDouble = false let i = 0 while (i < cmd.length) { const c = cmd[i]! if (inSingle) { // Bash single quotes: no escapes, `'` always terminates. if (c === "'") inSingle = false out.push(c === '{' ? ' ' : c) i++ } else if (inDouble) { // Bash double quotes: `\` escapes `"` and `\` (also `$`, backtick, // newline — but those don't affect quote state so we let them pass). if (c === '\\' && (cmd[i + 1] === '"' || cmd[i + 1] === '\\')) { out.push(c, cmd[i + 1]!) i += 2 } else { if (c === '"') inDouble = false out.push(c === '{' ? ' ' : c) i++ } } else { // Unquoted: `\` escapes any next char. if (c === '\\' && i + 1 < cmd.length) { out.push(c, cmd[i + 1]!) i += 2 } else { if (c === "'") inSingle = true else if (c === '"') inDouble = true out.push(c) i++ } } } return out.join('') } const DOLLAR = String.fromCharCode(0x24) /** * Parse a bash command string and extract a flat list of simple commands. * Returns 'too-complex' if the command uses any shell feature we can't * statically analyze. Returns 'parse-unavailable' if tree-sitter WASM isn't * loaded — caller should fall back to conservative behavior. */ export async function parseForSecurity( cmd: string, ): Promise<ParseForSecurityResult> { // parseCommandRaw('') returns null (falsy check), so short-circuit here. // Don't use .trim() — it strips Unicode whitespace (\u00a0 etc.) which the // pre-checks in parseForSecurityFromAst need to see and reject. if (cmd === '') return { kind: 'simple', commands: [] } const root = await parseCommandRaw(cmd) return root === null ? { kind: 'parse-unavailable' } : parseForSecurityFromAst(cmd, root) } /** * Same as parseForSecurity but takes a pre-parsed AST root so callers that * need the tree for other purposes can parse once and share. Pre-checks * still run on `cmd` — they catch tree-sitter/bash differentials that a * successful parse doesn't. */ export function parseForSecurityFromAst( cmd: string, root: Node | typeof PARSE_ABORTED, ): ParseForSecurityResult { // Pre-checks: characters that cause tree-sitter and bash to disagree on // word boundaries. These run before tree-sitter because they're the known // tree-sitter/bash differentials. Everything after this point trusts // tree-sitter's tokenization. if (CONTROL_CHAR_RE.test(cmd)) { return { kind: 'too-complex', reason: 'Contains control characters' } } if (UNICODE_WHITESPACE_RE.test(cmd)) { return { kind: 'too-complex', reason: 'Contains Unicode whitespace' } } if (BACKSLASH_WHITESPACE_RE.test(cmd)) { return { kind: 'too-complex', reason: 'Contains backslash-escaped whitespace', } } if (ZSH_TILDE_BRACKET_RE.test(cmd)) { return { kind: 'too-complex', reason: 'Contains zsh ~[ dynamic directory syntax', } } if (ZSH_EQUALS_EXPANSION_RE.test(cmd)) { return { kind: 'too-complex', reason: 'Contains zsh =cmd equals expansion', } } if (BRACE_WITH_QUOTE_RE.test(maskBracesInQuotedContexts(cmd))) { return { kind: 'too-complex', reason: 'Contains brace with quote character (expansion obfuscation)', } } const trimmed = cmd.trim() if (trimmed === '') { return { kind: 'simple', commands: [] } } if (root === PARSE_ABORTED) { // SECURITY: module loaded but parse aborted (timeout / node budget / // panic). Adversarially triggerable — `(( a[0][0]... ))` with ~2800 // subscripts hits PARSE_TIMEOUT_MICROS under the 10K length limit. // Previously indistinguishable from module-not-loaded → routed to // legacy (parse-unavailable), which lacks EVAL_LIKE_BUILTINS — `trap`, // `enable`, `hash` leaked with Bash(*). Fail closed: too-complex → ask. return { kind: 'too-complex', reason: 'Parser aborted (timeout or resource limit) — possible adversarial input', nodeType: 'PARSE_ABORT', } } return walkProgram(root) } function walkProgram(root: Node): ParseForSecurityResult { // ERROR-node check folded into collectCommands — any unhandled node type // (including ERROR) falls through to tooComplex() in the default branch. // Avoids a separate full-tree walk for error detection. const commands: SimpleCommand[] = [] // Track variables assigned earlier in the same command. When a // simple_expansion ($VAR) references a tracked var, we can substitute // a placeholder instead of returning too-complex. Enables patterns like // `NOW=$(date) && jq --arg now "$NOW" ...` — $NOW is known to be the // $(date) output (already extracted as inner command). const varScope = new Map<string, string>() const err = collectCommands(root, commands, varScope) if (err) return err return { kind: 'simple', commands } } /** * Recursively collect leaf `command` nodes from a structural wrapper node. * Returns an error result on any disallowed node type, or null on success. */ function collectCommands( node: Node, commands: SimpleCommand[], varScope: Map<string, string>, ): ParseForSecurityResult | null { if (node.type === 'command') { // Pass `commands` as the innerCommands accumulator — any $() extracted // during walkCommand gets appended alongside the outer command. const result = walkCommand(node, [], commands, varScope) if (result.kind !== 'simple') return result commands.push(...result.commands) return null } if (node.type === 'redirected_statement') { return walkRedirectedStatement(node, commands, varScope) } if (node.type === 'comment') { return null } if (STRUCTURAL_TYPES.has(node.type)) { // SECURITY: `||`, `|`, `|&`, `&` must NOT carry varScope linearly. In bash: // `||` RHS runs conditionally → vars set there MAY not be set // `|`/`|&` stages run in subshells → vars set there are NEVER visible after // `&` LHS runs in a background subshell → same as above // Flag-omission attack: `true || FLAG=--dry-run && cmd $FLAG` — bash skips // the `||` RHS (FLAG unset → $FLAG empty), runs `cmd` WITHOUT --dry-run. // With linear scope, our argv has ['cmd','--dry-run'] → looks SAFE → bypass. // // Fix: snapshot incoming scope at entry. After these separators, reset to // the snapshot — vars set in clauses between separators don't leak. `scope` // for clauses BETWEEN `&&`/`;` chains shares state (common `VAR=x && cmd // $VAR`). `scope` crosses `||`/`|`/`&` as the pre-structure snapshot only. // // `&&` and `;` DO carry scope: `VAR=x && cmd $VAR` is sequential, VAR is set. // // NOTE: `scope` and `varScope` diverge after the first `||`/`|`/`&`. The // caller's varScope is only mutated for the `&&`/`;` prefix — this is // conservative (vars set in `A && B | C && D` leak A+B into caller, not // C+D) but safe. // // Efficiency: snapshot is only needed if we hit `||`/`|`/`|&`/`&`. For // the dominant case (`ls`, `git status` — no such separators), skip the // Map alloc via a cheap pre-scan. For `pipeline`, node.type already tells // us stages are subshells — copy once at entry, no snapshot needed (each // reset uses the entry copy pattern via varScope, which is untouched). const isPipeline = node.type === 'pipeline' let needsSnapshot = false if (!isPipeline) { for (const c of node.children) { if (c && (c.type === '||' || c.type === '&')) { needsSnapshot = true break } } } const snapshot = needsSnapshot ? new Map(varScope) : null // For `pipeline`, ALL stages run in subshells — start with a copy so // nothing mutates caller's scope. For `list`/`program`, the `&&`/`;` // chain mutates caller's scope (sequential); fork only on `||`/`&`. let scope = isPipeline ? new Map(varScope) : varScope for (const child of node.children) { if (!child) continue if (SEPARATOR_TYPES.has(child.type)) { if ( child.type === '||' || child.type === '|' || child.type === '|&' || child.type === '&' ) { // For pipeline: varScope is untouched (we started with a copy). // For list/program: snapshot is non-null (pre-scan set it). // `|`/`|&` only appear under `pipeline` nodes; `||`/`&` under list. scope = new Map(snapshot ?? varScope) } continue } const err = collectCommands(child, commands, scope) if (err) return err } return null } if (node.type === 'negated_command') { // `! cmd` inverts exit code only — doesn't execute code or affect // argv. Recurse into the wrapped command. Common in CI: `! grep err`, // `! test -f lock`, `! git diff --quiet`. for (const child of node.children) { if (!child) continue if (child.type === '!') continue return collectCommands(child, commands, varScope) } return null } if (node.type === 'declaration_command') { // `export`/`local`/`readonly`/`declare`/`typeset`. tree-sitter emits // these as declaration_command, not command, so they previously fell // through to tooComplex. Values are validated via walkVariableAssignment: // `$()` in the value is recursively extracted (inner command pushed to // commands[], outer argv gets CMDSUB_PLACEHOLDER); other disallowed // expansions still reject via walkArgument. argv[0] is the builtin name so // `Bash(export:*)` rules match. const argv: string[] = [] for (const child of node.children) { if (!child) continue switch (child.type) { case 'export': case 'local': case 'readonly': case 'declare': case 'typeset': argv.push(child.text) break case 'word': case 'number': case 'raw_string': case 'string': case 'concatenation': { // Flags (`declare -r`), quoted names (`export "FOO=bar"`), numbers // (`declare -i 42`). Mirrors walkCommand's argv handling — before // this, `export "FOO=bar"` hit tooComplex on the `string` child. // walkArgument validates each (expansions still reject). const arg = walkArgument(child, commands, varScope) if (typeof arg !== 'string') return arg // SECURITY: declare/typeset/local flags that change assignment // semantics break our static model. -n (nameref): `declare -n X=Y` // then `$X` dereferences to $Y's VALUE — varScope stores 'Y' // (target NAME), argv[0] shows 'Y' while bash runs whatever $Y // holds. -i (integer): `declare -i X='a[$(cmd)]'` arithmetically // evaluates the RHS at assignment time, running $(cmd) even from // a single-quoted raw_string (same primitive walkArithmetic // guards in $((…))). -a/-A (array): subscript arithmetic on // assignment. -r/-x/-g/-p/-f/-F are inert. Check the resolved // arg (not child.text) so `\-n` and quoted `-n` are caught. // Scope to declare/typeset/local only: `export -n` means "remove // export attribute" (not nameref), and export/readonly don't // accept -i; readonly -a/-A rejects subscripted args as invalid // identifiers so subscript-arith doesn't fire. if ( (argv[0] === 'declare' || argv[0] === 'typeset' || argv[0] === 'local') && /^-[a-zA-Z]*[niaA]/.test(arg) ) { return { kind: 'too-complex', reason: `declare flag ${arg} changes assignment semantics (nameref/integer/array)`, nodeType: 'declaration_command', } } // SECURITY: bare positional assignment with a subscript also // evaluates — no -a/-i flag needed. `declare 'x[$(id)]=val'` // implicitly creates an array element, arithmetically evaluating // the subscript and running $(id). tree-sitter delivers the // single-quoted form as a raw_string leaf so walkArgument sees // only the literal text. Scoped to declare/typeset/local: // export/readonly reject `[` in identifiers before eval. if ( (argv[0] === 'declare' || argv[0] === 'typeset' || argv[0] === 'local') && arg[0] !== '-' && /^[^=]*\[/.test(arg) ) { return { kind: 'too-complex', reason: `declare positional '${arg}' contains array subscript — bash evaluates $(cmd) in subscripts`, nodeType: 'declaration_command', } } argv.push(arg) break } case 'variable_assignment': { const ev = walkVariableAssignment(child, commands, varScope) if ('kind' in ev) return ev // export/declare assignments populate the scope so later $VAR refs resolve. applyVarToScope(varScope, ev) argv.push(`${ev.name}=${ev.value}`) break } case 'variable_name': // `export FOO` — bare name, no assignment. argv.push(child.text) break default: return tooComplex(child) } } commands.push({ argv, envVars: [], redirects: [], text: node.text }) return null } if (node.type === 'variable_assignment') { // Bare `VAR=value` at statement level (not a command env prefix). // Sets a shell variable — no code execution, no filesystem I/O. // The value is validated via walkVariableAssignment → walkArgument, // so `VAR=$(evil)` still recursively extracts/rejects based on the // inner command. Does NOT push to commands — a bare assignment needs // no permission rule (it's inert). Common pattern: `VAR=x && cmd` // where cmd references $VAR. ~35% of too-complex in top-5k ant cmds. const ev = walkVariableAssignment(node, commands, varScope) if ('kind' in ev) return ev // Populate scope so later `$VAR` references resolve. applyVarToScope(varScope, ev) return null } if (node.type === 'for_statement') { // `for VAR in WORD...; do BODY; done` — iterate BODY once per word. // Body commands extracted once; every iteration runs the same commands. // // SECURITY: Loop var is ALWAYS treated as unknown-value (VAR_PLACEHOLDER). // Even "static" iteration words can be: // - Absolute paths: `for i in /etc/passwd; do rm $i; done` — body argv // would have placeholder, path validation never sees /etc/passwd. // - Globs: `for i in /etc/*; do rm $i; done` — `/etc/*` is a static word // at parse time but bash expands it at runtime. // - Flags: `for i in -rf /; do rm $i; done` — flag smuggling. // // VAR_PLACEHOLDER means bare `$i` in body → too-complex. Only // string-embedding (`echo "item: $i"`) stays simple. This reverts some // of the too-complex→simple rescues in the original PR — each one was a // potential path-validation bypass. let loopVar: string | null = null let doGroup: Node | null = null for (const child of node.children) { if (!child) continue if (child.type === 'variable_name') { loopVar = child.text } else if (child.type === 'do_group') { doGroup = child } else if ( child.type === 'for' || child.type === 'in' || child.type === 'select' || child.type === ';' ) { continue // structural tokens } else if (child.type === 'command_substitution') { // `for i in $(seq 1 3)` — inner cmd IS extracted and rule-checked. const err = collectCommandSubstitution(child, commands, varScope) if (err) return err } else { // Iteration values — validated via walkArgument. Value discarded: // body argv gets VAR_PLACEHOLDER regardless of the iteration words, // and bare `$i` in body → too-complex (see SECURITY comment above). // We still validate to reject e.g. `for i in $(cmd); do ...; done` // where the iteration word itself is a disallowed expansion. const arg = walkArgument(child, commands, varScope) if (typeof arg !== 'string') return arg } } if (loopVar === null || doGroup === null) return tooComplex(node) // SECURITY: `for PS4 in '$(id)'; do set -x; :; done` sets PS4 directly // via varScope.set below — walkVariableAssignment's PS4/IFS checks never // fire. Trace-time RCE (PS4) or word-split bypass (IFS). No legit use. if (loopVar === 'PS4' || loopVar === 'IFS') { return { kind: 'too-complex', reason: `${loopVar} as loop variable bypasses assignment validation`, nodeType: 'for_statement', } } // SECURITY: Body uses a scope COPY — vars assigned inside the loop // body don't leak to commands after `done`. The loop var itself is // set in the REAL scope (bash semantics: $i still set after loop) // and copied into the body scope. ALWAYS VAR_PLACEHOLDER — see above. varScope.set(loopVar, VAR_PLACEHOLDER) const bodyScope = new Map(varScope) for (const c of doGroup.children) { if (!c) continue if (c.type === 'do' || c.type === 'done' || c.type === ';') continue const err = collectCommands(c, commands, bodyScope) if (err) return err } return null } if (node.type === 'if_statement' || node.type === 'while_statement') { // `if COND; then BODY; [elif...; else...;] fi` // `while COND; do BODY; done` // Extract condition command(s) + all branch/body commands. All get // checked against permission rules. `while read VAR` tracks VAR so // body can reference $VAR. // // SECURITY: Branch bodies use scope COPIES — vars assigned inside a // conditional branch (which may not execute) must not leak to commands // after fi/done. `if false; then T=safe; fi && rm $T` must reject $T. // Condition commands use the REAL varScope (they always run for the // check, so assignments there are unconditional — e.g., `while read V` // tracking must persist to the body copy). // // tree-sitter if_statement children: if, COND..., then, THEN-BODY..., // [elif_clause...], [else_clause], fi. We distinguish condition from // then-body by tracking whether we've seen the `then` token. let seenThen = false for (const child of node.children) { if (!child) continue if ( child.type === 'if' || child.type === 'fi' || child.type === 'else' || child.type === 'elif' || child.type === 'while' || child.type === 'until' || child.type === ';' ) { continue } if (child.type === 'then') { seenThen = true continue } if (child.type === 'do_group') { // while body: recurse with scope COPY (body assignments don't leak // past done). The COPY contains any `read VAR` tracking from the // condition (already in real varScope at this point). const bodyScope = new Map(varScope) for (const c of child.children) { if (!c) continue if (c.type === 'do' || c.type === 'done' || c.type === ';') continue const err = collectCommands(c, commands, bodyScope) if (err) return err } continue } if (child.type === 'elif_clause' || child.type === 'else_clause') { // elif_clause: elif, cond, ;, then, body... / else_clause: else, body... // Scope COPY — elif/else branch assignments don't leak past fi. const branchScope = new Map(varScope) for (const c of child.children) { if (!c) continue if ( c.type === 'elif' || c.type === 'else' || c.type === 'then' || c.type === ';' ) { continue } const err = collectCommands(c, commands, branchScope) if (err) return err } continue } // Condition (seenThen=false) or then-body (seenThen=true). // Condition uses REAL varScope (always runs). Then-body uses a COPY. // Special-case `while read VAR`: after condition `read VAR` is // collected, track VAR in the REAL scope so the body COPY inherits it. const targetScope = seenThen ? new Map(varScope) : varScope const before = commands.length const err = collectCommands(child, commands, targetScope) if (err) return err // If condition included `read VAR...`, track vars in REAL scope. // read var value is UNKNOWN (stdin input) → use VAR_PLACEHOLDER // (unknown-value sentinel, string-only). if (!seenThen) { for (let i = before; i < commands.length; i++) { const c = commands[i] if (c?.argv[0] === 'read') { for (const a of c.argv.slice(1)) { // Skip flags (-r, -d, etc.); track bare identifier args as var names. if (!a.startsWith('-') && /^[A-Za-z_][A-Za-z0-9_]*$/.test(a)) { // SECURITY: commands[] is a flat accumulator. `true || read // VAR` in the condition: the list handler correctly uses a // scope COPY for the ||-RHS (may not run), but `read VAR` // IS still pushed to commands[] — we can't tell it was // scope-isolated from here. Same for `echo | read VAR` // (pipeline, subshell in bash) and `(read VAR)` (subshell). // Overwriting a tracked literal with VAR_PLACEHOLDER hides // path traversal: `VAR=../../etc/passwd && if true || read // VAR; then cat "/tmp/$VAR"; fi` — parser would see // /tmp/__TRACKED_VAR__, bash reads /etc/passwd. Fail closed // when a tracked literal would be overwritten. Safe case // (no prior value or already a placeholder) → proceed. const existing = varScope.get(a) if ( existing !== undefined && !containsAnyPlaceholder(existing) ) { return { kind: 'too-complex', reason: `'read ${a}' in condition may not execute (||/pipeline/subshell); cannot prove it overwrites tracked literal '${existing}'`, nodeType: 'if_statement', } } varScope.set(a, VAR_PLACEHOLDER) } } } } } } return null } if (node.type === 'subshell') { // `(cmd1; cmd2)` — run commands in a subshell. Inner commands ARE // executed, so extract them for permission checking. Subshell has // isolated scope: vars set inside don't leak out. Use a COPY of // varScope (outer vars visible, inner changes discarded). const innerScope = new Map(varScope) for (const child of node.children) { if (!child) continue if (child.type === '(' || child.type === ')') continue const err = collectCommands(child, commands, innerScope) if (err) return err } return null } if (node.type === 'test_command') { // `[[ EXPR ]]` or `[ EXPR ]` — conditional test. Evaluates to true/false // based on file tests (-f, -d), string comparisons (==, !=), etc. // No code execution (no command_substitution inside — that would be a // child and we'd recurse into it via walkArgument and reject it). // Push as a synthetic command with argv[0]='[[' so permission rules // can match — `Bash([[ :*)` would be unusual but legal. // Walk arguments to validate (no cmdsub/expansion inside operands). const argv: string[] = ['[['] for (const child of node.children) { if (!child) continue if (child.type === '[[' || child.type === ']]') continue if (child.type === '[' || child.type === ']') continue // Recurse into test expression structure: unary_expression, // binary_expression, parenthesized_expression, negated_expression. // The leaves are test_operator (-f, -d, ==) and operand words. const err = walkTestExpr(child, argv, commands, varScope) if (err) return err } commands.push({ argv, envVars: [], redirects: [], text: node.text }) return null } if (node.type === 'unset_command') { // `unset FOO BAR`, `unset -f func`. Safe: only removes shell // variables/functions from the current shell — no code execution, no // filesystem I/O. tree-sitter emits a dedicated node type so it // previously fell through to tooComplex. Children: `unset` keyword, // `variable_name` for each name, `word` for flags like `-f`/`-v`. const argv: string[] = [] for (const child of node.children) { if (!child) continue switch (child.type) { case 'unset': argv.push(child.text) break case 'variable_name': argv.push(child.text) // SECURITY: unset removes the var from bash's scope. Remove from // varScope so subsequent `$VAR` references correctly reject. // `VAR=safe && unset VAR && rm $VAR` must NOT resolve $VAR. varScope.delete(child.text) break case 'word': { const arg = walkArgument(child, commands, varScope) if (typeof arg !== 'string') return arg argv.push(arg) break } default: return tooComplex(child) } } commands.push({ argv, envVars: [], redirects: [], text: node.text }) return null } return tooComplex(node) } /** * Recursively walk a test_command expression tree (unary/binary/negated/ * parenthesized expressions). Leaves are test_operator tokens and operands * (word/string/number/etc). Operands are validated via walkArgument. */ function walkTestExpr( node: Node, argv: string[], innerCommands: SimpleCommand[], varScope: Map<string, string>, ): ParseForSecurityResult | null { switch (node.type) { case 'unary_expression': case 'binary_expression': case 'negated_expression': case 'parenthesized_expression': { for (const c of node.children) { if (!c) continue const err = walkTestExpr(c, argv, innerCommands, varScope) if (err) return err } return null } case 'test_operator': case '!': case '(': case ')': case '&&': case '||': case '==': case '=': case '!=': case '<': case '>': case '=~': argv.push(node.text) return null case 'regex': case 'extglob_pattern': // RHS of =~ or ==/!= in [[ ]]. Pattern text only — no code execution. // Parser emits these as leaf nodes with no children (any $(...) or ${...} // inside the pattern is a sibling, not a child, and is walked separately). argv.push(node.text) return null |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |