forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathValidation.ts
More file actions
1303 lines (1213 loc) · 42.7 KB
/
Copy pathpathValidation.ts
File metadata and controls
1303 lines (1213 loc) · 42.7 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 { homedir } from 'os'
import { isAbsolute, resolve } from 'path'
import type { z } from 'zod/v4'
import type { ToolPermissionContext } from '../../Tool.js'
import type { Redirect, SimpleCommand } from '../../utils/bash/ast.js'
import {
extractOutputRedirections,
splitCommand_DEPRECATED,
} from '../../utils/bash/commands.js'
import { tryParseShellCommand } from '../../utils/bash/shellQuote.js'
import { getDirectoryForPath } from '../../utils/path.js'
import { allWorkingDirectories } from '../../utils/permissions/filesystem.js'
import type { PermissionResult } from '../../utils/permissions/PermissionResult.js'
import { createReadRuleSuggestion } from '../../utils/permissions/PermissionUpdate.js'
import type { PermissionUpdate } from '../../utils/permissions/PermissionUpdateSchema.js'
import {
expandTilde,
type FileOperationType,
formatDirectoryList,
isDangerousRemovalPath,
validatePath,
} from '../../utils/permissions/pathValidation.js'
import type { BashTool } from './BashTool.js'
import { stripSafeWrappers } from './bashPermissions.js'
import { sedCommandIsAllowedByAllowlist } from './sedValidation.js'
export type PathCommand =
| 'cd'
| 'ls'
| 'find'
| 'mkdir'
| 'touch'
| 'rm'
| 'rmdir'
| 'mv'
| 'cp'
| 'cat'
| 'head'
| 'tail'
| 'sort'
| 'uniq'
| 'wc'
| 'cut'
| 'paste'
| 'column'
| 'tr'
| 'file'
| 'stat'
| 'diff'
| 'awk'
| 'strings'
| 'hexdump'
| 'od'
| 'base64'
| 'nl'
| 'grep'
| 'rg'
| 'sed'
| 'git'
| 'jq'
| 'sha256sum'
| 'sha1sum'
| 'md5sum'
/**
* Checks if an rm/rmdir command targets dangerous paths that should always
* require explicit user approval, even if allowlist rules exist.
* This prevents catastrophic data loss from commands like `rm -rf /`.
*/
function checkDangerousRemovalPaths(
command: 'rm' | 'rmdir',
args: string[],
cwd: string,
): PermissionResult {
// Extract paths using the existing path extractor
const extractor = PATH_EXTRACTORS[command]
const paths = extractor(args)
for (const path of paths) {
// Expand tilde and resolve to absolute path
// NOTE: We check the path WITHOUT resolving symlinks, because dangerous paths
// like /tmp should be caught even though /tmp is a symlink to /private/tmp on macOS
const cleanPath = expandTilde(path.replace(/^['"]|['"]$/g, ''))
const absolutePath = isAbsolute(cleanPath)
? cleanPath
: resolve(cwd, cleanPath)
// Check if this is a dangerous path (using the non-symlink-resolved path)
if (isDangerousRemovalPath(absolutePath)) {
return {
behavior: 'ask',
message: `Dangerous ${command} operation detected: '${absolutePath}'\n\nThis command would remove a critical system directory. This requires explicit approval and cannot be auto-allowed by permission rules.`,
decisionReason: {
type: 'other',
reason: `Dangerous ${command} operation on critical path: ${absolutePath}`,
},
// Don't provide suggestions - we don't want to encourage saving dangerous commands
suggestions: [],
}
}
}
// No dangerous paths found
return {
behavior: 'passthrough',
message: `No dangerous removals detected for ${command} command`,
}
}
/**
* SECURITY: Extract positional (non-flag) arguments, correctly handling the
* POSIX `--` end-of-options delimiter.
*
* Most commands (rm, cat, touch, etc.) stop parsing options at `--` and treat
* ALL subsequent arguments as positional, even if they start with `-`. Naive
* `!arg.startsWith('-')` filtering drops these, causing path validation to be
* silently skipped for attack payloads like:
*
* rm -- -/../.claude/settings.local.json
*
* Here `-/../.claude/settings.local.json` starts with `-` so the naive filter
* drops it, validation sees zero paths, returns passthrough, and the file is
* deleted without a prompt. With `--` handling, the path IS extracted and
* validated (blocked by isClaudeConfigFilePath / pathInAllowedWorkingPath).
*/
function filterOutFlags(args: string[]): string[] {
const result: string[] = []
let afterDoubleDash = false
for (const arg of args) {
if (afterDoubleDash) {
result.push(arg)
} else if (arg === '--') {
afterDoubleDash = true
} else if (!arg?.startsWith('-')) {
result.push(arg)
}
}
return result
}
// Helper: Parse grep/rg style commands (pattern then paths)
function parsePatternCommand(
args: string[],
flagsWithArgs: Set<string>,
defaults: string[] = [],
): string[] {
const paths: string[] = []
let patternFound = false
// SECURITY: Track `--` end-of-options delimiter. After `--`, all args are
// positional regardless of leading `-`. See filterOutFlags() doc comment.
let afterDoubleDash = false
for (let i = 0; i < args.length; i++) {
const arg = args[i]
if (arg === undefined || arg === null) continue
if (!afterDoubleDash && arg === '--') {
afterDoubleDash = true
continue
}
if (!afterDoubleDash && arg.startsWith('-')) {
const flag = arg.split('=')[0]
// Pattern flags mark that we've found the pattern
if (flag && ['-e', '--regexp', '-f', '--file'].includes(flag)) {
patternFound = true
}
// Skip next arg if flag needs it
if (flag && flagsWithArgs.has(flag) && !arg.includes('=')) {
i++
}
continue
}
// First non-flag is pattern, rest are paths
if (!patternFound) {
patternFound = true
continue
}
paths.push(arg)
}
return paths.length > 0 ? paths : defaults
}
/**
* Extracts paths from command arguments for different path commands.
* Each command has specific logic for how it handles paths and flags.
*/
export const PATH_EXTRACTORS: Record<
PathCommand,
(args: string[]) => string[]
> = {
// cd: special case - all args form one path
cd: args => (args.length === 0 ? [homedir()] : [args.join(' ')]),
// ls: filter flags, default to current dir
ls: args => {
const paths = filterOutFlags(args)
return paths.length > 0 ? paths : ['.']
},
// find: collect paths until hitting a real flag, also check path-taking flags
// SECURITY: `find -- -path` makes `-path` a starting point (not a predicate).
// GNU find supports `--` to allow search roots starting with `-`. After `--`,
// we conservatively collect all remaining args as paths to validate. This
// over-includes predicates like `-name foo`, but find is a read-only op and
// predicates resolve to paths within cwd (allowed), so no false blocks for
// legitimate use. The over-inclusion ensures attack paths like
// `find -- -/../../etc` are caught.
find: args => {
const paths: string[] = []
const pathFlags = new Set([
'-newer',
'-anewer',
'-cnewer',
'-mnewer',
'-samefile',
'-path',
'-wholename',
'-ilname',
'-lname',
'-ipath',
'-iwholename',
])
const newerPattern = /^-newer[acmBt][acmtB]$/
let foundNonGlobalFlag = false
let afterDoubleDash = false
for (let i = 0; i < args.length; i++) {
const arg = args[i]
if (!arg) continue
if (afterDoubleDash) {
paths.push(arg)
continue
}
if (arg === '--') {
afterDoubleDash = true
continue
}
// Handle flags
if (arg.startsWith('-')) {
// Global options don't stop collection
if (['-H', '-L', '-P'].includes(arg)) continue
// Mark that we've seen a non-global flag
foundNonGlobalFlag = true
// Check if this flag takes a path argument
if (pathFlags.has(arg) || newerPattern.test(arg)) {
const nextArg = args[i + 1]
if (nextArg) {
paths.push(nextArg)
i++ // Skip the path we just processed
}
}
continue
}
// Only collect non-flag arguments before first non-global flag
if (!foundNonGlobalFlag) {
paths.push(arg)
}
}
return paths.length > 0 ? paths : ['.']
},
// All simple commands: just filter out flags
mkdir: filterOutFlags,
touch: filterOutFlags,
rm: filterOutFlags,
rmdir: filterOutFlags,
mv: filterOutFlags,
cp: filterOutFlags,
cat: filterOutFlags,
head: filterOutFlags,
tail: filterOutFlags,
sort: filterOutFlags,
uniq: filterOutFlags,
wc: filterOutFlags,
cut: filterOutFlags,
paste: filterOutFlags,
column: filterOutFlags,
file: filterOutFlags,
stat: filterOutFlags,
diff: filterOutFlags,
awk: filterOutFlags,
strings: filterOutFlags,
hexdump: filterOutFlags,
od: filterOutFlags,
base64: filterOutFlags,
nl: filterOutFlags,
sha256sum: filterOutFlags,
sha1sum: filterOutFlags,
md5sum: filterOutFlags,
// tr: special case - skip character sets
tr: args => {
const hasDelete = args.some(
a =>
a === '-d' ||
a === '--delete' ||
(a.startsWith('-') && a.includes('d')),
)
const nonFlags = filterOutFlags(args)
return nonFlags.slice(hasDelete ? 1 : 2) // Skip SET1 or SET1+SET2
},
// grep: pattern then paths, defaults to stdin
grep: args => {
const flags = new Set([
'-e',
'--regexp',
'-f',
'--file',
'--exclude',
'--include',
'--exclude-dir',
'--include-dir',
'-m',
'--max-count',
'-A',
'--after-context',
'-B',
'--before-context',
'-C',
'--context',
])
const paths = parsePatternCommand(args, flags)
// Special: if -r/-R flag present and no paths, use current dir
if (
paths.length === 0 &&
args.some(a => ['-r', '-R', '--recursive'].includes(a))
) {
return ['.']
}
return paths
},
// rg: pattern then paths, defaults to current dir
rg: args => {
const flags = new Set([
'-e',
'--regexp',
'-f',
'--file',
'-t',
'--type',
'-T',
'--type-not',
'-g',
'--glob',
'-m',
'--max-count',
'--max-depth',
'-r',
'--replace',
'-A',
'--after-context',
'-B',
'--before-context',
'-C',
'--context',
])
return parsePatternCommand(args, flags, ['.'])
},
// sed: processes files in-place or reads from stdin
sed: args => {
const paths: string[] = []
let skipNext = false
let scriptFound = false
// SECURITY: Track `--` end-of-options delimiter. After `--`, all args are
// positional regardless of leading `-`. See filterOutFlags() doc comment.
let afterDoubleDash = false
for (let i = 0; i < args.length; i++) {
if (skipNext) {
skipNext = false
continue
}
const arg = args[i]
if (!arg) continue
if (!afterDoubleDash && arg === '--') {
afterDoubleDash = true
continue
}
// Handle flags (only before `--`)
if (!afterDoubleDash && arg.startsWith('-')) {
// -f flag: next arg is a script file that needs validation
if (['-f', '--file'].includes(arg)) {
const scriptFile = args[i + 1]
if (scriptFile) {
paths.push(scriptFile) // Add script file to paths for validation
skipNext = true
}
scriptFound = true
}
// -e flag: next arg is expression, not a file
else if (['-e', '--expression'].includes(arg)) {
skipNext = true
scriptFound = true
}
// Combined flags like -ie or -nf
else if (arg.includes('e') || arg.includes('f')) {
scriptFound = true
}
continue
}
// First non-flag is the script (if not already found via -e/-f)
if (!scriptFound) {
scriptFound = true
continue
}
// Rest are file paths
paths.push(arg)
}
return paths
},
// jq: filter then file paths (similar to grep)
// The jq command structure is: jq [flags] filter [files...]
// If no files are provided, jq reads from stdin
jq: args => {
const paths: string[] = []
const flagsWithArgs = new Set([
'-e',
'--expression',
'-f',
'--from-file',
'--arg',
'--argjson',
'--slurpfile',
'--rawfile',
'--args',
'--jsonargs',
'-L',
'--library-path',
'--indent',
'--tab',
])
let filterFound = false
// SECURITY: Track `--` end-of-options delimiter. After `--`, all args are
// positional regardless of leading `-`. See filterOutFlags() doc comment.
let afterDoubleDash = false
for (let i = 0; i < args.length; i++) {
const arg = args[i]
if (arg === undefined || arg === null) continue
if (!afterDoubleDash && arg === '--') {
afterDoubleDash = true
continue
}
if (!afterDoubleDash && arg.startsWith('-')) {
const flag = arg.split('=')[0]
// Pattern flags mark that we've found the filter
if (flag && ['-e', '--expression'].includes(flag)) {
filterFound = true
}
// Skip next arg if flag needs it
if (flag && flagsWithArgs.has(flag) && !arg.includes('=')) {
i++
}
continue
}
// First non-flag is filter, rest are file paths
if (!filterFound) {
filterFound = true
continue
}
paths.push(arg)
}
// If no file paths, jq reads from stdin (no paths to validate)
return paths
},
// git: handle subcommands that access arbitrary files outside the repository
git: args => {
// git diff --no-index is special - it explicitly compares files outside git's control
// This flag allows git diff to compare any two files on the filesystem, not just
// files within the repository, which is why it needs path validation
if (args.length >= 1 && args[0] === 'diff') {
if (args.includes('--no-index')) {
// SECURITY: git diff --no-index accepts `--` before file paths.
// Use filterOutFlags which handles `--` correctly instead of naive
// startsWith('-') filtering, to catch paths like `-/../etc/passwd`.
const filePaths = filterOutFlags(args.slice(1))
return filePaths.slice(0, 2) // git diff --no-index expects exactly 2 paths
}
}
// Other git commands (add, rm, mv, show, etc.) operate within the repository context
// and are already constrained by git's own security model, so they don't need
// additional path validation
return []
},
}
const SUPPORTED_PATH_COMMANDS = Object.keys(PATH_EXTRACTORS) as PathCommand[]
const ACTION_VERBS: Record<PathCommand, string> = {
cd: 'change directories to',
ls: 'list files in',
find: 'search files in',
mkdir: 'create directories in',
touch: 'create or modify files in',
rm: 'remove files from',
rmdir: 'remove directories from',
mv: 'move files to/from',
cp: 'copy files to/from',
cat: 'concatenate files from',
head: 'read the beginning of files from',
tail: 'read the end of files from',
sort: 'sort contents of files from',
uniq: 'filter duplicate lines from files in',
wc: 'count lines/words/bytes in files from',
cut: 'extract columns from files in',
paste: 'merge files from',
column: 'format files from',
tr: 'transform text from files in',
file: 'examine file types in',
stat: 'read file stats from',
diff: 'compare files from',
awk: 'process text from files in',
strings: 'extract strings from files in',
hexdump: 'display hex dump of files from',
od: 'display octal dump of files from',
base64: 'encode/decode files from',
nl: 'number lines in files from',
grep: 'search for patterns in files from',
rg: 'search for patterns in files from',
sed: 'edit files in',
git: 'access files with git from',
jq: 'process JSON from files in',
sha256sum: 'compute SHA-256 checksums for files in',
sha1sum: 'compute SHA-1 checksums for files in',
md5sum: 'compute MD5 checksums for files in',
}
export const COMMAND_OPERATION_TYPE: Record<PathCommand, FileOperationType> = {
cd: 'read',
ls: 'read',
find: 'read',
mkdir: 'create',
touch: 'create',
rm: 'write',
rmdir: 'write',
mv: 'write',
cp: 'write',
cat: 'read',
head: 'read',
tail: 'read',
sort: 'read',
uniq: 'read',
wc: 'read',
cut: 'read',
paste: 'read',
column: 'read',
tr: 'read',
file: 'read',
stat: 'read',
diff: 'read',
awk: 'read',
strings: 'read',
hexdump: 'read',
od: 'read',
base64: 'read',
nl: 'read',
grep: 'read',
rg: 'read',
sed: 'write',
git: 'read',
jq: 'read',
sha256sum: 'read',
sha1sum: 'read',
md5sum: 'read',
}
/**
* Command-specific validators that run before path validation.
* Returns true if the command is valid, false if it should be rejected.
* Used to block commands with flags that could bypass path validation.
*/
const COMMAND_VALIDATOR: Partial<
Record<PathCommand, (args: string[]) => boolean>
> = {
mv: (args: string[]) => !args.some(arg => arg?.startsWith('-')),
cp: (args: string[]) => !args.some(arg => arg?.startsWith('-')),
}
function validateCommandPaths(
command: PathCommand,
args: string[],
cwd: string,
toolPermissionContext: ToolPermissionContext,
compoundCommandHasCd?: boolean,
operationTypeOverride?: FileOperationType,
): PermissionResult {
const extractor = PATH_EXTRACTORS[command]
const paths = extractor(args)
const operationType = operationTypeOverride ?? COMMAND_OPERATION_TYPE[command]
// SECURITY: Check command-specific validators (e.g., to block flags that could bypass path validation)
// Some commands like mv/cp have flags (--target-directory=PATH) that can bypass path extraction,
// so we block ALL flags for these commands to ensure security.
const validator = COMMAND_VALIDATOR[command]
if (validator && !validator(args)) {
return {
behavior: 'ask',
message: `${command} with flags requires manual approval to ensure path safety. For security, Claude Code cannot automatically validate ${command} commands that use flags, as some flags like --target-directory=PATH can bypass path validation.`,
decisionReason: {
type: 'other',
reason: `${command} command with flags requires manual approval`,
},
}
}
// SECURITY: Block write operations in compound commands containing 'cd'
// This prevents bypassing path safety checks via directory changes before operations.
// Example attack: cd .claude/ && mv test.txt settings.json
// This would bypass the check for .claude/settings.json because paths are resolved
// relative to the original CWD, not accounting for the cd's effect.
//
// ALTERNATIVE APPROACH: Instead of blocking all writes with cd, we could track the
// effective CWD through the command chain (e.g., after "cd .claude/", subsequent
// commands would be validated with CWD=".claude/"). This would be more permissive
// but requires careful handling of:
// - Relative paths (cd ../foo)
// - Special cd targets (cd ~, cd -, cd with no args)
// - Multiple cd commands in sequence
// - Error cases where cd target cannot be determined
// For now, we take the conservative approach of requiring manual approval.
if (compoundCommandHasCd && operationType !== 'read') {
return {
behavior: 'ask',
message: `Commands that change directories and perform write operations require explicit approval to ensure paths are evaluated correctly. For security, Claude Code cannot automatically determine the final working directory when 'cd' is used in compound commands.`,
decisionReason: {
type: 'other',
reason:
'Compound command contains cd with write operation - manual approval required to prevent path resolution bypass',
},
}
}
for (const path of paths) {
const { allowed, resolvedPath, decisionReason } = validatePath(
path,
cwd,
toolPermissionContext,
operationType,
)
if (!allowed) {
const workingDirs = Array.from(
allWorkingDirectories(toolPermissionContext),
)
const dirListStr = formatDirectoryList(workingDirs)
// Use security check's custom reason if available (type: 'other' or 'safetyCheck')
// Otherwise use the standard "was blocked" message
const message =
decisionReason?.type === 'other' ||
decisionReason?.type === 'safetyCheck'
? decisionReason.reason
: `${command} in '${resolvedPath}' was blocked. For security, Claude Code may only ${ACTION_VERBS[command]} the allowed working directories for this session: ${dirListStr}.`
if (decisionReason?.type === 'rule') {
return {
behavior: 'deny',
message,
decisionReason,
}
}
return {
behavior: 'ask',
message,
blockedPath: resolvedPath,
decisionReason,
}
}
}
// All paths are valid - return passthrough
return {
behavior: 'passthrough',
message: `Path validation passed for ${command} command`,
}
}
export function createPathChecker(
command: PathCommand,
operationTypeOverride?: FileOperationType,
) {
return (
args: string[],
cwd: string,
context: ToolPermissionContext,
compoundCommandHasCd?: boolean,
): PermissionResult => {
// First check normal path validation (which includes explicit deny rules)
const result = validateCommandPaths(
command,
args,
cwd,
context,
compoundCommandHasCd,
operationTypeOverride,
)
// If explicitly denied, respect that (don't override with dangerous path message)
if (result.behavior === 'deny') {
return result
}
// Check for dangerous removal paths AFTER explicit deny rules but BEFORE other results
// This ensures the check runs even if the user has allowlist rules or if glob patterns
// were rejected, but respects explicit deny rules. Dangerous patterns get a specific
// error message that overrides generic glob pattern rejection messages.
if (command === 'rm' || command === 'rmdir') {
const dangerousPathResult = checkDangerousRemovalPaths(command, args, cwd)
if (dangerousPathResult.behavior !== 'passthrough') {
return dangerousPathResult
}
}
// If it's a passthrough, return it directly
if (result.behavior === 'passthrough') {
return result
}
// If it's an ask decision, add suggestions based on the operation type
if (result.behavior === 'ask') {
const operationType =
operationTypeOverride ?? COMMAND_OPERATION_TYPE[command]
const suggestions: PermissionUpdate[] = []
// Only suggest adding directory/rules if we have a blocked path
if (result.blockedPath) {
if (operationType === 'read') {
// For read operations, suggest a Read rule for the directory (only if it exists)
const dirPath = getDirectoryForPath(result.blockedPath)
const suggestion = createReadRuleSuggestion(dirPath, 'session')
if (suggestion) {
suggestions.push(suggestion)
}
} else {
// For write/create operations, suggest adding the directory
suggestions.push({
type: 'addDirectories',
directories: [getDirectoryForPath(result.blockedPath)],
destination: 'session',
})
}
}
// For write operations, also suggest enabling accept-edits mode
if (operationType === 'write' || operationType === 'create') {
suggestions.push({
type: 'setMode',
mode: 'acceptEdits',
destination: 'session',
})
}
result.suggestions = suggestions
}
// Return the decision directly
return result
}
}
/**
* Parses command arguments using shell-quote, converting glob objects to strings.
* This is necessary because shell-quote parses patterns like *.txt as glob objects,
* but we need them as strings for path validation.
*/
function parseCommandArguments(cmd: string): string[] {
const parseResult = tryParseShellCommand(cmd, env => `$${env}`)
if (!parseResult.success) {
// Malformed shell syntax, return empty array
return []
}
const parsed = parseResult.tokens
const extractedArgs: string[] = []
for (const arg of parsed) {
if (typeof arg === 'string') {
// Include empty strings - they're valid arguments (e.g., grep "" /tmp/t)
extractedArgs.push(arg)
} else if (
typeof arg === 'object' &&
arg !== null &&
'op' in arg &&
arg.op === 'glob' &&
'pattern' in arg
) {
// shell-quote parses glob patterns as objects, but we need them as strings for validation
extractedArgs.push(String(arg.pattern))
}
}
return extractedArgs
}
/**
* Validates a single command for path constraints and shell safety.
*
* This function:
* 1. Parses the command arguments
* 2. Checks if it's a path command (cd, ls, find)
* 3. Validates for shell injection patterns
* 4. Validates all paths are within allowed directories
*
* @param cmd - The command string to validate
* @param cwd - Current working directory
* @param toolPermissionContext - Context containing allowed directories
* @param compoundCommandHasCd - Whether the full compound command contains a cd
* @returns PermissionResult - 'passthrough' if not a path command, otherwise validation result
*/
function validateSinglePathCommand(
cmd: string,
cwd: string,
toolPermissionContext: ToolPermissionContext,
compoundCommandHasCd?: boolean,
): PermissionResult {
// SECURITY: Strip wrapper commands (timeout, nice, nohup, time) before extracting
// the base command. Without this, dangerous commands wrapped with these utilities
// would bypass path validation since the wrapper command (e.g., 'timeout') would
// be checked instead of the actual command (e.g., 'rm').
// Example: 'timeout 10 rm -rf /' would otherwise see 'timeout' as the base command.
const strippedCmd = stripSafeWrappers(cmd)
// Parse command into arguments, handling quotes and globs
const extractedArgs = parseCommandArguments(strippedCmd)
if (extractedArgs.length === 0) {
return {
behavior: 'passthrough',
message: 'Empty command - no paths to validate',
}
}
// Check if this is a path command we need to validate
const [baseCmd, ...args] = extractedArgs
if (!baseCmd || !SUPPORTED_PATH_COMMANDS.includes(baseCmd as PathCommand)) {
return {
behavior: 'passthrough',
message: `Command '${baseCmd}' is not a path-restricted command`,
}
}
// For read-only sed commands (e.g., sed -n '1,10p' file.txt),
// validate file paths as read operations instead of write operations.
// sed is normally classified as 'write' for path validation, but when the
// command is purely reading (line printing with -n), file args are read-only.
const operationTypeOverride =
baseCmd === 'sed' && sedCommandIsAllowedByAllowlist(strippedCmd)
? ('read' as FileOperationType)
: undefined
// Validate all paths are within allowed directories
const pathChecker = createPathChecker(
baseCmd as PathCommand,
operationTypeOverride,
)
return pathChecker(args, cwd, toolPermissionContext, compoundCommandHasCd)
}
/**
* Like validateSinglePathCommand but operates on AST-derived argv directly
* instead of re-parsing the command string with shell-quote. Avoids the
* shell-quote single-quote backslash bug that causes parseCommandArguments
* to silently return [] and skip path validation.
*/
function validateSinglePathCommandArgv(
cmd: SimpleCommand,
cwd: string,
toolPermissionContext: ToolPermissionContext,
compoundCommandHasCd?: boolean,
): PermissionResult {
const argv = stripWrappersFromArgv(cmd.argv)
if (argv.length === 0) {
return {
behavior: 'passthrough',
message: 'Empty command - no paths to validate',
}
}
const [baseCmd, ...args] = argv
if (!baseCmd || !SUPPORTED_PATH_COMMANDS.includes(baseCmd as PathCommand)) {
return {
behavior: 'passthrough',
message: `Command '${baseCmd}' is not a path-restricted command`,
}
}
// sed read-only override: use .text for the allowlist check since
// sedCommandIsAllowedByAllowlist takes a string. argv is already
// wrapper-stripped but .text is raw tree-sitter span (includes
// `timeout 5 ` prefix), so strip here too.
const operationTypeOverride =
baseCmd === 'sed' &&
sedCommandIsAllowedByAllowlist(stripSafeWrappers(cmd.text))
? ('read' as FileOperationType)
: undefined
const pathChecker = createPathChecker(
baseCmd as PathCommand,
operationTypeOverride,
)
return pathChecker(args, cwd, toolPermissionContext, compoundCommandHasCd)
}
function validateOutputRedirections(
redirections: Array<{ target: string; operator: '>' | '>>' }>,
cwd: string,
toolPermissionContext: ToolPermissionContext,
compoundCommandHasCd?: boolean,
): PermissionResult {
// SECURITY: Block output redirections in compound commands containing 'cd'
// This prevents bypassing path safety checks via directory changes before redirections.
// Example attack: cd .claude/ && echo "malicious" > settings.json
// The redirection target would be validated relative to the original CWD, but the
// actual write happens in the changed directory after 'cd' executes.
if (compoundCommandHasCd && redirections.length > 0) {
return {
behavior: 'ask',
message: `Commands that change directories and write via output redirection require explicit approval to ensure paths are evaluated correctly. For security, Claude Code cannot automatically determine the final working directory when 'cd' is used in compound commands.`,
decisionReason: {
type: 'other',
reason:
'Compound command contains cd with output redirection - manual approval required to prevent path resolution bypass',
},
}
}
for (const { target } of redirections) {
// /dev/null is always safe - it discards output
if (target === '/dev/null') {
continue
}
const { allowed, resolvedPath, decisionReason } = validatePath(
target,
cwd,
toolPermissionContext,
'create', // Treat > and >> as create operations
)
if (!allowed) {
const workingDirs = Array.from(
allWorkingDirectories(toolPermissionContext),
)
const dirListStr = formatDirectoryList(workingDirs)
// Use security check's custom reason if available (type: 'other' or 'safetyCheck')
// Otherwise use the standard message for deny rules or working directory restrictions
const message =
decisionReason?.type === 'other' ||
decisionReason?.type === 'safetyCheck'
? decisionReason.reason
: decisionReason?.type === 'rule'
? `Output redirection to '${resolvedPath}' was blocked by a deny rule.`
: `Output redirection to '${resolvedPath}' was blocked. For security, Claude Code may only write to files in the allowed working directories for this session: ${dirListStr}.`
// If denied by a deny rule, return 'deny' behavior
if (decisionReason?.type === 'rule') {
return {
behavior: 'deny',
message,
decisionReason,
}
}
return {
behavior: 'ask',
message,
blockedPath: resolvedPath,
decisionReason,
suggestions: [
{
type: 'addDirectories',
directories: [getDirectoryForPath(resolvedPath)],
destination: 'session',
},
],
}
}
}
return {
behavior: 'passthrough',