-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathbashPermissions.ts
More file actions
2621 lines (2441 loc) Β· 96.4 KB
/
Copy pathbashPermissions.ts
File metadata and controls
2621 lines (2441 loc) Β· 96.4 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
import { feature } from 'bun:bundle'
import { APIUserAbortError } from '@anthropic-ai/sdk'
import type { z } from 'zod/v4'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../../services/analytics/index.js'
import type { ToolPermissionContext, ToolUseContext } from '../../Tool.js'
import type { PendingClassifierCheck } from '../../types/permissions.js'
import { count } from '../../utils/array.js'
import {
checkSemantics,
nodeTypeId,
type ParseForSecurityResult,
parseForSecurityFromAst,
type Redirect,
type SimpleCommand,
} from '../../utils/bash/ast.js'
import {
type CommandPrefixResult,
extractOutputRedirections,
getCommandSubcommandPrefix,
splitCommand_DEPRECATED,
} from '../../utils/bash/commands.js'
import { parseCommandRaw } from '../../utils/bash/parser.js'
import { tryParseShellCommand } from '../../utils/bash/shellQuote.js'
import { getCwd } from '../../utils/cwd.js'
import { logForDebugging } from '../../utils/debug.js'
import { isEnvTruthy } from '../../utils/envUtils.js'
import { AbortError } from '../../utils/errors.js'
import type {
ClassifierBehavior,
ClassifierResult,
} from '../../utils/permissions/bashClassifier.js'
import {
classifyBashCommand,
getBashPromptAllowDescriptions,
getBashPromptAskDescriptions,
getBashPromptDenyDescriptions,
isClassifierPermissionsEnabled,
} from '../../utils/permissions/bashClassifier.js'
import type {
PermissionDecisionReason,
PermissionResult,
} from '../../utils/permissions/PermissionResult.js'
import type {
PermissionRule,
PermissionRuleValue,
} from '../../utils/permissions/PermissionRule.js'
import { extractRules } from '../../utils/permissions/PermissionUpdate.js'
import type { PermissionUpdate } from '../../utils/permissions/PermissionUpdateSchema.js'
import { permissionRuleValueToString } from '../../utils/permissions/permissionRuleParser.js'
import {
createPermissionRequestMessage,
getRuleByContentsForTool,
} from '../../utils/permissions/permissions.js'
import {
parsePermissionRule,
type ShellPermissionRule,
matchWildcardPattern as sharedMatchWildcardPattern,
permissionRuleExtractPrefix as sharedPermissionRuleExtractPrefix,
suggestionForExactCommand as sharedSuggestionForExactCommand,
suggestionForPrefix as sharedSuggestionForPrefix,
} from '../../utils/permissions/shellRuleMatching.js'
import { getPlatform } from '../../utils/platform.js'
import { SandboxManager } from '../../utils/sandbox/sandbox-adapter.js'
import { jsonStringify } from '../../utils/slowOperations.js'
import { windowsPathToPosixPath } from '../../utils/windowsPaths.js'
import { BashTool } from './BashTool.js'
import { checkCommandOperatorPermissions } from './bashCommandHelpers.js'
import {
bashCommandIsSafeAsync_DEPRECATED,
stripSafeHeredocSubstitutions,
} from './bashSecurity.js'
import { checkPermissionMode } from './modeValidation.js'
import { checkPathConstraints } from './pathValidation.js'
import { checkSedConstraints } from './sedValidation.js'
import { shouldUseSandbox } from './shouldUseSandbox.js'
// DCE cliff: Bun's feature() evaluator has a per-function complexity budget.
// bashToolHasPermission is right at the limit. `import { X as Y }` aliases
// inside the import block count toward this budget; when they push it over
// the threshold Bun can no longer prove feature('BASH_CLASSIFIER') is a
// constant and silently evaluates the ternaries to `false`, dropping every
// pendingClassifierCheck spread. Keep aliases as top-level const rebindings
// instead. (See also the comment on checkSemanticsDeny below.)
const bashCommandIsSafeAsync = bashCommandIsSafeAsync_DEPRECATED
const splitCommand = splitCommand_DEPRECATED
// Env-var assignment prefix (VAR=value). Shared across three while-loops that
// skip safe env vars before extracting the command name.
const ENV_VAR_ASSIGN_RE = /^[A-Za-z_]\w*=/
// CC-643: On complex compound commands, splitCommand_DEPRECATED can produce a
// very large subcommands array (possible exponential growth; #21405's ReDoS fix
// may have been incomplete). Each subcommand then runs tree-sitter parse +
// ~20 validators + logEvent (bashSecurity.ts), and with memoized metadata the
// resulting microtask chain starves the event loop β REPL freeze at 100% CPU,
// strace showed /proc/self/stat reads at ~127Hz with no epoll_wait. Fifty is
// generous: legitimate user commands don't split that wide. Above the cap we
// fall back to 'ask' (safe default β we can't prove safety, so we prompt).
export const MAX_SUBCOMMANDS_FOR_SECURITY_CHECK = 50
// GH#11380: Cap the number of per-subcommand rules suggested for compound
// commands. Beyond this, the "Yes, and don't ask again for X, Y, Zβ¦" label
// degrades to "similar commands" anyway, and saving 10+ rules from one prompt
// is more likely noise than intent. Users chaining this many write commands
// in one && list are rare; they can always approve once and add rules manually.
export const MAX_SUGGESTED_RULES_FOR_COMPOUND = 5
/**
* [ANT-ONLY] Log classifier evaluation results for analysis.
* This helps us understand which classifier rules are being evaluated
* and how the classifier is deciding on commands.
*/
function logClassifierResultForAnts(
command: string,
behavior: ClassifierBehavior,
descriptions: string[],
result: ClassifierResult,
): void {
if (process.env.USER_TYPE !== 'ant') {
return
}
logEvent('tengu_internal_bash_classifier_result', {
behavior:
behavior as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
descriptions: jsonStringify(
descriptions,
) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
matches: result.matches,
matchedDescription: (result.matchedDescription ??
'') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
confidence:
result.confidence as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
reason:
result.reason as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
// Note: command contains code/filepaths - this is ANT-ONLY so it's OK
command:
command as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
}
/**
* Extract a stable command prefix (command + subcommand) from a raw command string.
* Skips leading env var assignments only if they are in SAFE_ENV_VARS (or
* ANT_ONLY_SAFE_ENV_VARS for ant users). Returns null if a non-safe env var is
* encountered (to fall back to exact match), or if the second token doesn't look
* like a subcommand (lowercase alphanumeric, e.g., "commit", "run").
*
* Examples:
* 'git commit -m "fix typo"' β 'git commit'
* 'NODE_ENV=prod npm run build' β 'npm run' (NODE_ENV is safe)
* 'MY_VAR=val npm run build' β null (MY_VAR is not safe)
* 'ls -la' β null (flag, not a subcommand)
* 'cat file.txt' β null (filename, not a subcommand)
* 'chmod 755 file' β null (number, not a subcommand)
*/
export function getSimpleCommandPrefix(command: string): string | null {
const tokens = command.trim().split(/\s+/).filter(Boolean)
if (tokens.length === 0) return null
// Skip env var assignments (VAR=value) at the start, but only if they are
// in SAFE_ENV_VARS (or ANT_ONLY_SAFE_ENV_VARS for ant users). If a non-safe
// env var is encountered, return null to fall back to exact match. This
// prevents generating prefix rules like Bash(npm run:*) that can never match
// at allow-rule check time, because stripSafeWrappers only strips safe vars.
let i = 0
while (i < tokens.length && ENV_VAR_ASSIGN_RE.test(tokens[i]!)) {
const varName = tokens[i]!.split('=')[0]!
const isAntOnlySafe =
process.env.USER_TYPE === 'ant' && ANT_ONLY_SAFE_ENV_VARS.has(varName)
if (!SAFE_ENV_VARS.has(varName) && !isAntOnlySafe) {
return null
}
i++
}
const remaining = tokens.slice(i)
if (remaining.length < 2) return null
const subcmd = remaining[1]!
// Second token must look like a subcommand (e.g., "commit", "run", "compose"),
// not a flag (-rf), filename (file.txt), path (/tmp), URL, or number (755).
if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(subcmd)) return null
return remaining.slice(0, 2).join(' ')
}
// Bare-prefix suggestions like `bash:*` or `sh:*` would allow arbitrary code
// via `-c`. Wrapper suggestions like `env:*` or `sudo:*` would do the same:
// `env` is NOT in SAFE_WRAPPER_PATTERNS, so `env bash -c "evil"` survives
// stripSafeWrappers unchanged and hits the startsWith("env ") check at
// the prefix-rule matcher. Shell list mirrors DANGEROUS_SHELL_PREFIXES in
// src/utils/shell/prefix.ts which guarded the old Haiku extractor.
const BARE_SHELL_PREFIXES = new Set([
'sh',
'bash',
'zsh',
'fish',
'csh',
'tcsh',
'ksh',
'dash',
'cmd',
'powershell',
'pwsh',
// wrappers that exec their args as a command
'env',
'xargs',
// SECURITY: checkSemantics (ast.ts) strips these wrappers to check the
// wrapped command. Suggesting `Bash(nice:*)` would be β `Bash(*)` β users
// would add it after a prompt, then `nice rm -rf /` passes semantics while
// deny/cd+git gates see 'nice' (SAFE_WRAPPER_PATTERNS below didn't strip
// bare `nice` until this fix). Block these from ever being suggested.
'nice',
'stdbuf',
'nohup',
'timeout',
'time',
// privilege escalation β sudo:* from `sudo -u foo ...` would auto-approve
// any future sudo invocation
'sudo',
'doas',
'pkexec',
])
/**
* UI-only fallback: extract the first word alone when getSimpleCommandPrefix
* declines. In external builds TREE_SITTER_BASH is off, so the async
* tree-sitter refinement in BashPermissionRequest never fires β without this,
* pipes and compounds (`python3 file.py 2>&1 | tail -20`) dump into the
* editable field verbatim.
*
* Deliberately not used by suggestionForExactCommand: a backend-suggested
* `Bash(rm:*)` is too broad to auto-generate, but as an editable starting
* point it's what users expect (Slack C07VBSHV7EV/p1772670433193449).
*
* Reuses the same SAFE_ENV_VARS gate as getSimpleCommandPrefix β a rule like
* `Bash(python3:*)` can never match `RUN=/path python3 ...` at check time
* because stripSafeWrappers won't strip RUN.
*/
export function getFirstWordPrefix(command: string): string | null {
const tokens = command.trim().split(/\s+/).filter(Boolean)
let i = 0
while (i < tokens.length && ENV_VAR_ASSIGN_RE.test(tokens[i]!)) {
const varName = tokens[i]!.split('=')[0]!
const isAntOnlySafe =
process.env.USER_TYPE === 'ant' && ANT_ONLY_SAFE_ENV_VARS.has(varName)
if (!SAFE_ENV_VARS.has(varName) && !isAntOnlySafe) {
return null
}
i++
}
const cmd = tokens[i]
if (!cmd) return null
// Same shape check as the subcommand regex in getSimpleCommandPrefix:
// rejects paths (./script.sh, /usr/bin/python), flags, numbers, filenames.
if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(cmd)) return null
if (BARE_SHELL_PREFIXES.has(cmd)) return null
return cmd
}
function suggestionForExactCommand(command: string): PermissionUpdate[] {
// Heredoc commands contain multi-line content that changes each invocation,
// making exact-match rules useless (they'll never match again). Extract a
// stable prefix before the heredoc operator and suggest a prefix rule instead.
const heredocPrefix = extractPrefixBeforeHeredoc(command)
if (heredocPrefix) {
return sharedSuggestionForPrefix(BashTool.name, heredocPrefix)
}
// Multiline commands without heredoc also make poor exact-match rules.
// Saving the full multiline text can produce patterns containing `:*` in
// the middle, which fails permission validation and corrupts the settings
// file. Use the first line as a prefix rule instead.
if (command.includes('\n')) {
const firstLine = command.split('\n')[0]!.trim()
if (firstLine) {
return sharedSuggestionForPrefix(BashTool.name, firstLine)
}
}
// Single-line commands: extract a 2-word prefix for reusable rules.
// Without this, exact-match rules are saved that never match future
// invocations with different arguments.
const prefix = getSimpleCommandPrefix(command)
if (prefix) {
return sharedSuggestionForPrefix(BashTool.name, prefix)
}
return sharedSuggestionForExactCommand(BashTool.name, command)
}
/**
* If the command contains a heredoc (<<), extract the command prefix before it.
* Returns the first word(s) before the heredoc operator as a stable prefix,
* or null if the command doesn't contain a heredoc.
*
* Examples:
* 'git commit -m "$(cat <<\'EOF\'\n...\nEOF\n)"' β 'git commit'
* 'cat <<EOF\nhello\nEOF' β 'cat'
* 'echo hello' β null (no heredoc)
*/
function extractPrefixBeforeHeredoc(command: string): string | null {
if (!command.includes('<<')) return null
const idx = command.indexOf('<<')
if (idx <= 0) return null
const before = command.substring(0, idx).trim()
if (!before) return null
const prefix = getSimpleCommandPrefix(before)
if (prefix) return prefix
// Fallback: skip safe env var assignments and take up to 2 tokens.
// This preserves flag tokens (e.g., "python3 -c" stays "python3 -c",
// not just "python3") and skips safe env var prefixes like "NODE_ENV=test".
// If a non-safe env var is encountered, return null to avoid generating
// prefix rules that can never match (same rationale as getSimpleCommandPrefix).
const tokens = before.split(/\s+/).filter(Boolean)
let i = 0
while (i < tokens.length && ENV_VAR_ASSIGN_RE.test(tokens[i]!)) {
const varName = tokens[i]!.split('=')[0]!
const isAntOnlySafe =
process.env.USER_TYPE === 'ant' && ANT_ONLY_SAFE_ENV_VARS.has(varName)
if (!SAFE_ENV_VARS.has(varName) && !isAntOnlySafe) {
return null
}
i++
}
if (i >= tokens.length) return null
return tokens.slice(i, i + 2).join(' ') || null
}
function suggestionForPrefix(prefix: string): PermissionUpdate[] {
return sharedSuggestionForPrefix(BashTool.name, prefix)
}
/**
* Extract prefix from legacy :* syntax (e.g., "npm:*" -> "npm")
* Delegates to shared implementation.
*/
export const permissionRuleExtractPrefix = sharedPermissionRuleExtractPrefix
/**
* Match a command against a wildcard pattern (case-sensitive for Bash).
* Delegates to shared implementation.
*/
export function matchWildcardPattern(
pattern: string,
command: string,
): boolean {
return sharedMatchWildcardPattern(pattern, command)
}
/**
* Parse a permission rule into a structured rule object.
* Delegates to shared implementation.
*/
export const bashPermissionRule: (
permissionRule: string,
) => ShellPermissionRule = parsePermissionRule
/**
* Whitelist of environment variables that are safe to strip from commands.
* These variables CANNOT execute code or load libraries.
*
* SECURITY: These must NEVER be added to the whitelist:
* - PATH, LD_PRELOAD, LD_LIBRARY_PATH, DYLD_* (execution/library loading)
* - PYTHONPATH, NODE_PATH, CLASSPATH, RUBYLIB (module loading)
* - GOFLAGS, RUSTFLAGS, NODE_OPTIONS (can contain code execution flags)
* - HOME, TMPDIR, SHELL, BASH_ENV (affect system behavior)
*/
const SAFE_ENV_VARS = new Set([
// Go - build/runtime settings only
'GOEXPERIMENT', // experimental features
'GOOS', // target OS
'GOARCH', // target architecture
'CGO_ENABLED', // enable/disable CGO
'GO111MODULE', // module mode
// Rust - logging/debugging only
'RUST_BACKTRACE', // backtrace verbosity
'RUST_LOG', // logging filter
// Node - environment name only (not NODE_OPTIONS!)
'NODE_ENV',
// Python - behavior flags only (not PYTHONPATH!)
'PYTHONUNBUFFERED', // disable buffering
'PYTHONDONTWRITEBYTECODE', // no .pyc files
// Pytest - test configuration
'PYTEST_DISABLE_PLUGIN_AUTOLOAD', // disable plugin loading
'PYTEST_DEBUG', // debug output
// API keys and authentication
'ANTHROPIC_API_KEY', // API authentication
// Locale and character encoding
'LANG', // default locale
'LANGUAGE', // language preference list
'LC_ALL', // override all locale settings
'LC_CTYPE', // character classification
'LC_TIME', // time format
'CHARSET', // character set preference
// Terminal and display
'TERM', // terminal type
'COLORTERM', // color terminal indicator
'NO_COLOR', // disable color output (universal standard)
'FORCE_COLOR', // force color output
'TZ', // timezone
// Color configuration for various tools
'LS_COLORS', // colors for ls (GNU)
'LSCOLORS', // colors for ls (BSD/macOS)
'GREP_COLOR', // grep match color (deprecated)
'GREP_COLORS', // grep color scheme
'GCC_COLORS', // GCC diagnostic colors
// Display formatting
'TIME_STYLE', // time display format for ls
'BLOCK_SIZE', // block size for du/df
'BLOCKSIZE', // alternative block size
])
/**
* ANT-ONLY environment variables that are safe to strip from commands.
* These are only enabled when USER_TYPE === 'ant'.
*
* SECURITY: These env vars are stripped before permission-rule matching, which
* means `DOCKER_HOST=tcp://evil.com docker ps` matches a `Bash(docker ps:*)`
* rule after stripping. This is INTENTIONALLY ANT-ONLY (gated at line ~380)
* and MUST NEVER ship to external users. DOCKER_HOST redirects the Docker
* daemon endpoint β stripping it defeats prefix-based permission restrictions
* by hiding the network endpoint from the permission check. KUBECONFIG
* similarly controls which cluster kubectl talks to. These are convenience
* strippings for internal power users who accept the risk.
*
* Based on analysis of 30 days of tengu_internal_bash_tool_use_permission_request events.
*/
const ANT_ONLY_SAFE_ENV_VARS = new Set([
// Kubernetes and container config (config file pointers, not execution)
'KUBECONFIG', // kubectl config file path β controls which cluster kubectl uses
'DOCKER_HOST', // Docker daemon socket/endpoint β controls which daemon docker talks to
// Cloud provider project/profile selection (just names/identifiers)
'AWS_PROFILE', // AWS profile name selection
'CLOUDSDK_CORE_PROJECT', // GCP project ID
'CLUSTER', // generic cluster name
// Anthropic internal cluster selection (just names/identifiers)
'COO_CLUSTER', // coo cluster name
'COO_CLUSTER_NAME', // coo cluster name (alternate)
'COO_NAMESPACE', // coo namespace
'COO_LAUNCH_YAML_DRY_RUN', // dry run mode
// Feature flags (boolean/string flags only)
'SKIP_NODE_VERSION_CHECK', // skip version check
'EXPECTTEST_ACCEPT', // accept test expectations
'CI', // CI environment indicator
'GIT_LFS_SKIP_SMUDGE', // skip LFS downloads
// GPU/Device selection (just device IDs)
'CUDA_VISIBLE_DEVICES', // GPU device selection
'JAX_PLATFORMS', // JAX platform selection
// Display/terminal settings
'COLUMNS', // terminal width
'TMUX', // TMUX socket info
// Test/debug configuration
'POSTGRESQL_VERSION', // postgres version string
'FIRESTORE_EMULATOR_HOST', // emulator host:port
'HARNESS_QUIET', // quiet mode flag
'TEST_CROSSCHECK_LISTS_MATCH_UPDATE', // test update flag
'DBT_PER_DEVELOPER_ENVIRONMENTS', // DBT config
'STATSIG_FORD_DB_CHECKS', // statsig DB check flag
// Build configuration
'ANT_ENVIRONMENT', // Anthropic environment name
'ANT_SERVICE', // Anthropic service name
'MONOREPO_ROOT_DIR', // monorepo root path
// Version selectors
'PYENV_VERSION', // Python version selection
// Credentials (approved subset - these don't change exfil risk)
'PGPASSWORD', // Postgres password
'GH_TOKEN', // GitHub token
'GROWTHBOOK_API_KEY', // self-hosted growthbook
])
/**
* Strips full-line comments from a command.
* This handles cases where Claude adds comments in bash commands, e.g.:
* "# Check the logs directory\nls /home/user/logs"
* Should be stripped to: "ls /home/user/logs"
*
* Only strips full-line comments (lines where the entire line is a comment),
* not inline comments that appear after a command on the same line.
*/
function stripCommentLines(command: string): string {
const lines = command.split('\n')
const nonCommentLines = lines.filter(line => {
const trimmed = line.trim()
// Keep lines that are not empty and don't start with #
return trimmed !== '' && !trimmed.startsWith('#')
})
// If all lines were comments/empty, return original
if (nonCommentLines.length === 0) {
return command
}
return nonCommentLines.join('\n')
}
export function stripSafeWrappers(command: string): string {
// SECURITY: Use [ \t]+ not \s+ β \s matches \n/\r which are command
// separators in bash. Matching across a newline would strip the wrapper from
// one line and leave a different command on the next line for bash to execute.
//
// SECURITY: `(?:--[ \t]+)?` consumes the wrapper's own `--` so
// `nohup -- rm -- -/../foo` strips to `rm -- -/../foo` (not `-- rm ...`
// which would skip path validation with `--` as an unknown baseCmd).
const SAFE_WRAPPER_PATTERNS = [
// timeout: enumerate GNU long flags β no-value (--foreground,
// --preserve-status, --verbose), value-taking in both =fused and
// space-separated forms (--kill-after=5, --kill-after 5, --signal=TERM,
// --signal TERM). Short: -v (no-arg), -k/-s with separate or fused value.
// SECURITY: flag VALUES use allowlist [A-Za-z0-9_.+-] (signals are
// TERM/KILL/9, durations are 5/5s/10.5). Previously [^ \t]+ matched
// $ ( ) ` | ; & β `timeout -k$(id) 10 ls` stripped to `ls`, matched
// Bash(ls:*), while bash expanded $(id) during word splitting BEFORE
// timeout ran. Contrast ENV_VAR_PATTERN below which already allowlists.
/^timeout[ \t]+(?:(?:--(?:foreground|preserve-status|verbose)|--(?:kill-after|signal)=[A-Za-z0-9_.+-]+|--(?:kill-after|signal)[ \t]+[A-Za-z0-9_.+-]+|-v|-[ks][ \t]+[A-Za-z0-9_.+-]+|-[ks][A-Za-z0-9_.+-]+)[ \t]+)*(?:--[ \t]+)?\d+(?:\.\d+)?[smhd]?[ \t]+/,
/^time[ \t]+(?:--[ \t]+)?/,
// SECURITY: keep in sync with checkSemantics wrapper-strip (ast.ts
// ~:1990-2080) AND stripWrappersFromArgv (pathValidation.ts ~:1260).
// Previously this pattern REQUIRED `-n N`; checkSemantics already handled
// bare `nice` and legacy `-N`. Asymmetry meant checkSemantics exposed the
// wrapped command to semantic checks but deny-rule matching and the cd+git
// gate saw the wrapper name. `nice rm -rf /` with Bash(rm:*) deny became
// ask instead of deny; `cd evil && nice git status` skipped the bare-repo
// RCE gate. PR #21503 fixed stripWrappersFromArgv; this was missed.
// Now matches: `nice cmd`, `nice -n N cmd`, `nice -N cmd` (all forms
// checkSemantics strips).
/^nice(?:[ \t]+-n[ \t]+-?\d+|[ \t]+-\d+)?[ \t]+(?:--[ \t]+)?/,
// stdbuf: fused short flags only (-o0, -eL). checkSemantics handles more
// (space-separated, long --output=MODE), but we fail-closed on those
// above so not over-stripping here is safe. Main need: `stdbuf -o0 cmd`.
/^stdbuf(?:[ \t]+-[ioe][LN0-9]+)+[ \t]+(?:--[ \t]+)?/,
/^nohup[ \t]+(?:--[ \t]+)?/,
] as const
// Pattern for environment variables:
// ^([A-Za-z_][A-Za-z0-9_]*) - Variable name (standard identifier)
// = - Equals sign
// ([A-Za-z0-9_./:-]+) - Value: alphanumeric + safe punctuation only
// [ \t]+ - Required HORIZONTAL whitespace after value
//
// SECURITY: Only matches unquoted values with safe characters (no $(), `, $var, ;|&).
//
// SECURITY: Trailing whitespace MUST be [ \t]+ (horizontal only), NOT \s+.
// \s matches \n/\r. If reconstructCommand emits an unquoted newline between
// `TZ=UTC` and `echo`, \s+ would match across it and strip `TZ=UTC<NL>`,
// leaving `echo curl evil.com` to match Bash(echo:*). But bash treats the
// newline as a command separator. Defense-in-depth with needsQuoting fix.
const ENV_VAR_PATTERN = /^([A-Za-z_][A-Za-z0-9_]*)=([A-Za-z0-9_./:-]+)[ \t]+/
let stripped = command
let previousStripped = ''
// Phase 1: Strip leading env vars and comments only.
// In bash, env var assignments before a command (VAR=val cmd) are genuine
// shell-level assignments. These are safe to strip for permission matching.
while (stripped !== previousStripped) {
previousStripped = stripped
stripped = stripCommentLines(stripped)
const envVarMatch = stripped.match(ENV_VAR_PATTERN)
if (envVarMatch) {
const varName = envVarMatch[1]!
const isAntOnlySafe =
process.env.USER_TYPE === 'ant' && ANT_ONLY_SAFE_ENV_VARS.has(varName)
if (SAFE_ENV_VARS.has(varName) || isAntOnlySafe) {
stripped = stripped.replace(ENV_VAR_PATTERN, '')
}
}
}
// Phase 2: Strip wrapper commands and comments only. Do NOT strip env vars.
// Wrapper commands (timeout, time, nice, nohup) use execvp to run their
// arguments, so VAR=val after a wrapper is treated as the COMMAND to execute,
// not as an env var assignment. Stripping env vars here would create a
// mismatch between what the parser sees and what actually executes.
// (HackerOne #3543050)
previousStripped = ''
while (stripped !== previousStripped) {
previousStripped = stripped
stripped = stripCommentLines(stripped)
for (const pattern of SAFE_WRAPPER_PATTERNS) {
stripped = stripped.replace(pattern, '')
}
}
return stripped.trim()
}
// SECURITY: allowlist for timeout flag VALUES (signals are TERM/KILL/9,
// durations are 5/5s/10.5). Rejects $ ( ) ` | ; & and newlines that
// previously matched via [^ \t]+ β `timeout -k$(id) 10 ls` must NOT strip.
const TIMEOUT_FLAG_VALUE_RE = /^[A-Za-z0-9_.+-]+$/
/**
* Parse timeout's GNU flags (long + short, fused + space-separated) and
* return the argv index of the DURATION token, or -1 if flags are unparseable.
* Enumerates: --foreground/--preserve-status/--verbose (no value),
* --kill-after/--signal (value, both =fused and space-separated), -v (no
* value), -k/-s (value, both fused and space-separated).
*
* Extracted from stripWrappersFromArgv to keep bashToolHasPermission under
* Bun's feature() DCE complexity threshold β inlining this breaks
* feature('BASH_CLASSIFIER') evaluation in classifier tests.
*/
function skipTimeoutFlags(a: readonly string[]): number {
let i = 1
while (i < a.length) {
const arg = a[i]!
const next = a[i + 1]
if (
arg === '--foreground' ||
arg === '--preserve-status' ||
arg === '--verbose'
)
i++
else if (/^--(?:kill-after|signal)=[A-Za-z0-9_.+-]+$/.test(arg)) i++
else if (
(arg === '--kill-after' || arg === '--signal') &&
next &&
TIMEOUT_FLAG_VALUE_RE.test(next)
)
i += 2
else if (arg === '--') {
i++
break
} // end-of-options marker
else if (arg.startsWith('--')) return -1
else if (arg === '-v') i++
else if (
(arg === '-k' || arg === '-s') &&
next &&
TIMEOUT_FLAG_VALUE_RE.test(next)
)
i += 2
else if (/^-[ks][A-Za-z0-9_.+-]+$/.test(arg)) i++
else if (arg.startsWith('-')) return -1
else break
}
return i
}
/**
* Argv-level counterpart to stripSafeWrappers. Strips the same wrapper
* commands (timeout, time, nice, nohup) from AST-derived argv. Env vars
* are already separated into SimpleCommand.envVars so no env-var stripping.
*
* KEEP IN SYNC with SAFE_WRAPPER_PATTERNS above β if you add a wrapper
* there, add it here too.
*/
export function stripWrappersFromArgv(argv: string[]): string[] {
// SECURITY: Consume optional `--` after wrapper options, matching what the
// wrapper does. Otherwise `['nohup','--','rm','--','-/../foo']` yields `--`
// as baseCmd and skips path validation. See SAFE_WRAPPER_PATTERNS comment.
let a = argv
for (;;) {
if (a[0] === 'time' || a[0] === 'nohup') {
a = a.slice(a[1] === '--' ? 2 : 1)
} else if (a[0] === 'timeout') {
const i = skipTimeoutFlags(a)
if (i < 0 || !a[i] || !/^\d+(?:\.\d+)?[smhd]?$/.test(a[i]!)) return a
a = a.slice(i + 1)
} else if (
a[0] === 'nice' &&
a[1] === '-n' &&
a[2] &&
/^-?\d+$/.test(a[2])
) {
a = a.slice(a[3] === '--' ? 4 : 3)
} else {
return a
}
}
}
/**
* Env vars that make a *different binary* run (injection or resolution hijack).
* Heuristic only β export-&& form bypasses this, and excludedCommands isn't a
* security boundary anyway.
*/
export const BINARY_HIJACK_VARS = /^(LD_|DYLD_|PATH$)/
/**
* Strip ALL leading env var prefixes from a command, regardless of whether the
* var name is in the safe-list.
*
* Used for deny/ask rule matching: when a user denies `claude` or `rm`, the
* command should stay blocked even if prefixed with arbitrary env vars like
* `FOO=bar claude`. The safe-list restriction in stripSafeWrappers is correct
* for allow rules (prevents `DOCKER_HOST=evil docker ps` from auto-matching
* `Bash(docker ps:*)`), but deny rules must be harder to circumvent.
*
* Also used for sandbox.excludedCommands matching (not a security boundary β
* permission prompts are), with BINARY_HIJACK_VARS as a blocklist.
*
* SECURITY: Uses a broader value pattern than stripSafeWrappers. The value
* pattern excludes only actual shell injection characters ($, backtick, ;, |,
* &, parens, redirects, quotes, backslash) and whitespace. Characters like
* =, +, @, ~, , are harmless in unquoted env var assignment position and must
* be matched to prevent trivial bypass via e.g. `FOO=a=b denied_command`.
*
* @param blocklist - optional regex tested against each var name; matching vars
* are NOT stripped (and stripping stops there). Omit for deny rules; pass
* BINARY_HIJACK_VARS for excludedCommands.
*/
export function stripAllLeadingEnvVars(
command: string,
blocklist?: RegExp,
): string {
// Broader value pattern for deny-rule stripping. Handles:
//
// - Standard assignment (FOO=bar), append (FOO+=bar), array (FOO[0]=bar)
// - Single-quoted values: '[^'\n\r]*' β bash suppresses all expansion
// - Double-quoted values with backslash escapes: "(?:\\.|[^"$`\\\n\r])*"
// In bash double quotes, only \$, \`, \", \\, and \newline are special.
// Other \x sequences are harmless, so we allow \. inside double quotes.
// We still exclude raw $ and ` (without backslash) to block expansion.
// - Unquoted values: excludes shell metacharacters, allows backslash escapes
// - Concatenated segments: FOO='x'y"z" β bash concatenates adjacent segments
//
// SECURITY: Trailing whitespace MUST be [ \t]+ (horizontal only), NOT \s+.
//
// The outer * matches one atomic unit per iteration: a complete quoted
// string, a backslash-escape pair, or a single unquoted safe character.
// The inner double-quote alternation (?:...|...)* is bounded by the
// closing ", so it cannot interact with the outer * for backtracking.
//
// Note: $ is excluded from unquoted/double-quoted value classes to block
// dangerous forms like $(cmd), ${var}, and $((expr)). This means
// FOO=$VAR is not stripped β adding $VAR matching creates ReDoS risk
// (CodeQL #671) and $VAR bypasses are low-priority.
const ENV_VAR_PATTERN =
/^([A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?)\+?=(?:'[^'\n\r]*'|"(?:\\.|[^"$`\\\n\r])*"|\\.|[^ \t\n\r$`;|&()<>\\\\'"])*[ \t]+/
let stripped = command
let previousStripped = ''
while (stripped !== previousStripped) {
previousStripped = stripped
stripped = stripCommentLines(stripped)
const m = stripped.match(ENV_VAR_PATTERN)
if (!m) continue
if (blocklist?.test(m[1]!)) break
stripped = stripped.slice(m[0].length)
}
return stripped.trim()
}
function filterRulesByContentsMatchingInput(
input: z.infer<typeof BashTool.inputSchema>,
rules: Map<string, PermissionRule>,
matchMode: 'exact' | 'prefix',
{
stripAllEnvVars = false,
skipCompoundCheck = false,
}: { stripAllEnvVars?: boolean; skipCompoundCheck?: boolean } = {},
): PermissionRule[] {
const command = input.command.trim()
// Strip output redirections for permission matching
// This allows rules like Bash(python:*) to match "python script.py > output.txt"
// Security validation of redirection targets happens separately in checkPathConstraints
const commandWithoutRedirections =
extractOutputRedirections(command).commandWithoutRedirections
// For exact matching, try both the original command (to preserve quotes)
// and the command without redirections (to allow rules without redirections to match)
// For prefix matching, only use the command without redirections
const commandsForMatching =
matchMode === 'exact'
? [command, commandWithoutRedirections]
: [commandWithoutRedirections]
// Strip safe wrapper commands (timeout, time, nice, nohup) and env vars for matching
// This allows rules like Bash(npm install:*) to match "timeout 10 npm install foo"
// or "GOOS=linux go build"
const commandsToTry = commandsForMatching.flatMap(cmd => {
const strippedCommand = stripSafeWrappers(cmd)
return strippedCommand !== cmd ? [cmd, strippedCommand] : [cmd]
})
// SECURITY: For deny/ask rules, also try matching after stripping ALL leading
// env var prefixes. This prevents bypass via `FOO=bar denied_command` where
// FOO is not in the safe-list. The safe-list restriction in stripSafeWrappers
// is intentional for allow rules (see HackerOne #3543050), but deny rules
// must be harder to circumvent β a denied command should stay denied
// regardless of env var prefixes.
//
// We iteratively apply both stripping operations to all candidates until no
// new candidates are produced (fixed-point). This handles interleaved patterns
// like `nohup FOO=bar timeout 5 claude` where:
// 1. stripSafeWrappers strips `nohup` β `FOO=bar timeout 5 claude`
// 2. stripAllLeadingEnvVars strips `FOO=bar` β `timeout 5 claude`
// 3. stripSafeWrappers strips `timeout 5` β `claude` (deny match)
//
// Without iteration, single-pass compositions miss multi-layer interleaving.
if (stripAllEnvVars) {
const seen = new Set(commandsToTry)
let startIdx = 0
// Iterate until no new candidates are produced (fixed-point)
while (startIdx < commandsToTry.length) {
const endIdx = commandsToTry.length
for (let i = startIdx; i < endIdx; i++) {
const cmd = commandsToTry[i]
if (!cmd) {
continue
}
// Try stripping env vars
const envStripped = stripAllLeadingEnvVars(cmd)
if (!seen.has(envStripped)) {
commandsToTry.push(envStripped)
seen.add(envStripped)
}
// Try stripping safe wrappers
const wrapperStripped = stripSafeWrappers(cmd)
if (!seen.has(wrapperStripped)) {
commandsToTry.push(wrapperStripped)
seen.add(wrapperStripped)
}
}
startIdx = endIdx
}
}
// Precompute compound-command status for each candidate to avoid re-parsing
// inside the rule filter loop (which would scale splitCommand calls with
// rules.length Γ commandsToTry.length). The compound check only applies to
// prefix/wildcard matching in 'prefix' mode, and only for allow rules.
// SECURITY: deny/ask rules must match compound commands so they can't be
// bypassed by wrapping a denied command in a compound expression.
const isCompoundCommand = new Map<string, boolean>()
if (matchMode === 'prefix' && !skipCompoundCheck) {
for (const cmd of commandsToTry) {
if (!isCompoundCommand.has(cmd)) {
isCompoundCommand.set(cmd, splitCommand(cmd).length > 1)
}
}
}
return Array.from(rules.entries())
.filter(([ruleContent]) => {
const bashRule = bashPermissionRule(ruleContent)
return commandsToTry.some(cmdToMatch => {
switch (bashRule.type) {
case 'exact':
return bashRule.command === cmdToMatch
case 'prefix':
switch (matchMode) {
// In 'exact' mode, only return true if the command exactly matches the prefix rule
case 'exact':
return bashRule.prefix === cmdToMatch
case 'prefix': {
// SECURITY: Don't allow prefix rules to match compound commands.
// e.g., Bash(cd:*) must NOT match "cd /path && python3 evil.py".
// In the normal flow commands are split before reaching here, but
// shell escaping can defeat the first splitCommand pass β e.g.,
// cd src\&\& python3 hello.py β splitCommand β ["cd src&& python3 hello.py"]
// which then looks like a single command that starts with "cd ".
// Re-splitting the candidate here catches those cases.
if (isCompoundCommand.get(cmdToMatch)) {
return false
}
// Ensure word boundary: prefix must be followed by space or end of string
// This prevents "ls:*" from matching "lsof" or "lsattr"
if (cmdToMatch === bashRule.prefix) {
return true
}
if (cmdToMatch.startsWith(bashRule.prefix + ' ')) {
return true
}
// Also match "xargs <prefix>" for bare xargs with no flags.
// This allows Bash(grep:*) to match "xargs grep pattern",
// and deny rules like Bash(rm:*) to block "xargs rm file".
// Natural word-boundary: "xargs -n1 grep" does NOT start with
// "xargs grep " so flagged xargs invocations are not matched.
const xargsPrefix = 'xargs ' + bashRule.prefix
if (cmdToMatch === xargsPrefix) {
return true
}
return cmdToMatch.startsWith(xargsPrefix + ' ')
}
}
break
case 'wildcard':
// SECURITY FIX: In exact match mode, wildcards must NOT match because we're
// checking the full unparsed command. Wildcard matching on unparsed commands
// allows "foo *" to match "foo arg && curl evil.com" since .* matches operators.
// Wildcards should only match after splitting into individual subcommands.
if (matchMode === 'exact') {
return false
}
// SECURITY: Same as for prefix rules, don't allow wildcard rules to match
// compound commands in prefix mode. e.g., Bash(cd *) must not match
// "cd /path && python3 evil.py" even though "cd *" pattern would match it.
if (isCompoundCommand.get(cmdToMatch)) {
return false
}
// In prefix mode (after splitting), wildcards can safely match subcommands
return matchWildcardPattern(bashRule.pattern, cmdToMatch)
}
})
})
.map(([, rule]) => rule)
}
function matchingRulesForInput(
input: z.infer<typeof BashTool.inputSchema>,
toolPermissionContext: ToolPermissionContext,
matchMode: 'exact' | 'prefix',
{ skipCompoundCheck = false }: { skipCompoundCheck?: boolean } = {},
) {
const denyRuleByContents = getRuleByContentsForTool(
toolPermissionContext,
BashTool,
'deny',
)
// SECURITY: Deny/ask rules use aggressive env var stripping so that
// `FOO=bar denied_command` still matches a deny rule for `denied_command`.
const matchingDenyRules = filterRulesByContentsMatchingInput(
input,
denyRuleByContents,
matchMode,
{ stripAllEnvVars: true, skipCompoundCheck: true },
)
const askRuleByContents = getRuleByContentsForTool(
toolPermissionContext,
BashTool,
'ask',
)
const matchingAskRules = filterRulesByContentsMatchingInput(
input,
askRuleByContents,
matchMode,
{ stripAllEnvVars: true, skipCompoundCheck: true },
)
const allowRuleByContents = getRuleByContentsForTool(
toolPermissionContext,
BashTool,
'allow',
)
const matchingAllowRules = filterRulesByContentsMatchingInput(
input,
allowRuleByContents,
matchMode,
{ skipCompoundCheck },
)
return {
matchingDenyRules,
matchingAskRules,
matchingAllowRules,
}
}
/**
* Checks if the subcommand is an exact match for a permission rule
*/
export const bashToolCheckExactMatchPermission = (
input: z.infer<typeof BashTool.inputSchema>,
toolPermissionContext: ToolPermissionContext,
): PermissionResult => {
const command = input.command.trim()
const { matchingDenyRules, matchingAskRules, matchingAllowRules } =
matchingRulesForInput(input, toolPermissionContext, 'exact')
// 1. Deny if exact command was denied
if (matchingDenyRules[0] !== undefined) {