vtcode_safety/command_safety/shell_parser/
mod.rs1#![expect(
2 clippy::indexing_slicing,
3 clippy::string_slice,
4 reason = "Shell parsing tracks byte offsets at character boundaries while validating operator pairs."
5)]
6
7mod ast;
23
24use anyhow::Result;
25
26pub use ast::{BashNode, BashTree, prewarm_bash_parser};
27
28fn scanner_crash_shape(script: &str) -> bool {
44 let mut saw_open_brace = false;
45 for byte in script.as_bytes() {
46 match byte {
47 b'{' => saw_open_brace = true,
48 0xF0..=0xF7 if saw_open_brace => return true,
49 _ => {}
50 }
51 }
52 false
53}
54
55pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
59 match parse_with_tree_sitter(script, false) {
62 Ok(commands) if !commands.is_empty() => return Ok(commands),
63 Ok(_) => {} Err(e) => {
65 tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
66 }
67 }
68
69 parse_with_basic_tokenization(script)
71}
72
73pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
77 parse_with_tree_sitter(script, true)
78}
79
80pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
90 enum ShellQuote {
91 Single,
92 Double,
93 }
94
95 let mut quote: Option<ShellQuote> = None;
96 let mut characters = command.chars();
97
98 while let Some(character) = characters.next() {
99 match quote {
100 Some(ShellQuote::Single) => {
101 if character == '\'' {
102 quote = None;
103 }
104 }
105 Some(ShellQuote::Double) => match character {
106 '"' => quote = None,
107 '$' | '`' => return true,
108 '\\'
109 if characters.next().is_none() => {
115 return true;
116 }
117 _ => {}
118 },
119 None => match character {
120 '\'' => quote = Some(ShellQuote::Single),
121 '"' => quote = Some(ShellQuote::Double),
122 '\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
123 _ => {}
124 },
125 }
126 }
127
128 quote.is_some()
129}
130
131pub fn contains_dynamic_find_syntax(script: &str) -> bool {
134 if let Ok(commands) = parse_shell_commands_tree_sitter(script)
135 && commands.iter().any(|command| {
136 command
137 .first()
138 .map(|program| base_command_name(program) == "find")
139 .unwrap_or(false)
140 && command.iter().any(|word| contains_dynamic_shell_syntax(word))
141 })
142 {
143 return true;
144 }
145
146 let has_find_word = script.split_whitespace().any(|word| {
150 let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
151 base_command_name(command) == "find"
152 });
153 has_find_word && contains_dynamic_shell_syntax(script)
154}
155
156pub fn has_only_output_redirections(script: &str) -> bool {
160 if contains_dynamic_shell_syntax(script) {
161 return false;
162 }
163 if contains_background_operator(script) {
164 return false;
165 }
166
167 let Ok(tree) = BashTree::parse(script) else {
168 return false;
169 };
170 if tree.has_error() {
171 return false;
172 }
173
174 let mut saw_redirection = false;
175 if !collect_output_redirections(tree.root(), &mut saw_redirection) {
176 return false;
177 }
178 saw_redirection
179}
180
181pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
184 use anyhow::{Context, anyhow, ensure};
185 if !script.contains(['<', '>']) {
186 return Ok(());
187 }
188 let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
189 ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
190 let mut pending = vec![tree.root()];
191 while let Some(node) = pending.pop() {
192 if node.kind() == "file_redirect" {
193 let text = node.text();
194 let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
195 let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
196 for destination in node.field_children("destination") {
197 let raw = destination.text();
198 ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
199 let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
200 ensure!(words.len() == 1, "redirection destination must be one literal path");
201 let path = words.first().context("missing redirection destination")?;
202 if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
203 continue;
204 }
205 ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
210 if path == "/dev/null" {
212 continue;
213 }
214 vtcode_commons::paths::validate_path_safety(path)
215 .with_context(|| format!("unsafe shell redirection destination: {path}"))?;
216 }
217 }
218 pending.extend(node.named_children());
219 }
220 Ok(())
221}
222
223fn contains_background_operator(script: &str) -> bool {
224 let chars = script.chars().collect::<Vec<_>>();
225 let mut index = 0;
226 let mut in_single_quote = false;
227 let mut in_double_quote = false;
228
229 while index < chars.len() {
230 let character = chars[index];
231 if character == '\'' && !in_double_quote {
232 in_single_quote.toggle();
233 index += 1;
234 continue;
235 }
236 if character == '"' && !in_single_quote {
237 in_double_quote.toggle();
238 index += 1;
239 continue;
240 }
241 if in_single_quote || in_double_quote {
242 index += 1;
243 continue;
244 }
245
246 if character == '&' {
247 let previous = index.checked_sub(1).and_then(|position| chars.get(position));
248 let next = chars.get(index + 1);
249 if next == Some(&'&') {
250 index += 2;
251 continue;
252 }
253 let part_of_allowed_operator = next == Some(&'&')
254 || next == Some(&'>')
255 || previous == Some(&'>')
256 || previous == Some(&'|')
257 || previous == Some(&'<');
258 if !part_of_allowed_operator {
259 return true;
260 }
261 }
262 index += 1;
263 }
264
265 false
266}
267
268fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
269 match node.kind() {
270 "file_redirect" => {
271 *saw_redirection = true;
272 if !is_output_redirection(node.text()) {
273 return false;
274 }
275 }
276 "heredoc_redirect" | "herestring_redirect" => return false,
277 _ => {}
278 }
279
280 node.children()
281 .iter()
282 .all(|child| collect_output_redirections(*child, saw_redirection))
283}
284
285fn is_output_redirection(text: &str) -> bool {
286 let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
287 if redirect.starts_with("&>") {
288 return !redirect.starts_with("&>-");
289 }
290 if let Some(destination) = redirect.strip_prefix(">&") {
291 return destination.trim().chars().all(|character| character.is_ascii_digit());
292 }
293
294 redirect.starts_with('>') && !redirect.starts_with(">&-")
295}
296
297pub fn output_redirection_destinations(script: &str) -> Vec<String> {
308 let mut destinations = Vec::new();
309 collect_output_destinations(script, &mut destinations, 0);
310 destinations
311}
312
313const MAX_NESTED_SHELL_DEPTH: u8 = 2;
316
317fn collect_output_destinations(script: &str, destinations: &mut Vec<String>, depth: u8) {
318 if !script.contains('>') {
319 return;
320 }
321 let Ok(tree) = BashTree::parse(script) else {
322 return;
323 };
324 if tree.has_error() {
325 return;
326 }
327
328 let mut pending = vec![tree.root()];
331 while let Some(node) = pending.pop() {
332 if node.kind() == "file_redirect" && is_output_redirection(node.text()) {
333 for destination in node.field_children("destination") {
334 let raw = destination.text();
335 if contains_dynamic_shell_syntax(raw) {
336 continue;
337 }
338 let Ok(words) = shell_words::split(raw) else {
339 continue;
340 };
341 if let [path] = words.as_slice()
342 && !path.is_empty()
343 && !path.bytes().all(|byte| byte.is_ascii_digit())
344 && path != "-"
345 && !path.contains(['$', '`', '(', ')', '<', '>', '|', ';', '&', '*', '?', '['])
348 {
349 destinations.push(path.clone());
350 }
351 }
352 }
353 for child in node.named_children().into_iter().rev() {
354 pending.push(child);
355 }
356 }
357
358 if depth >= MAX_NESTED_SHELL_DEPTH {
363 return;
364 }
365 for command in parse_shell_commands(script).unwrap_or_default() {
366 let Some(script) = shell_inline_script(&command) else {
367 continue;
368 };
369 if contains_dynamic_shell_syntax(script) {
370 continue;
371 }
372 let inner = super::dangerous_commands::strip_nested_script_quotes(script);
373 collect_output_destinations(inner, destinations, depth + 1);
374 }
375}
376
377pub(crate) fn shell_inline_script(command: &[String]) -> Option<&str> {
385 let command = super::dangerous_commands::unwrap_command_prefix(command)?;
386 let executable = command.first()?;
387 let name = std::path::Path::new(executable)
388 .file_name()
389 .and_then(|name| name.to_str())
390 .unwrap_or_default();
391 if !matches!(name, "sh" | "bash" | "zsh") {
392 return None;
393 }
394 for (index, argument) in command.iter().enumerate().skip(1) {
395 let Some(flags) = argument.strip_prefix('-') else {
396 continue;
397 };
398 if flags.starts_with('-') {
400 continue;
401 }
402 if flags.contains('c') {
403 return command.get(index + 1).map(String::as_str);
404 }
405 }
406 None
407}
408
409fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
411 if scanner_crash_shape(script) {
416 return Err("shell script matches the tree-sitter-bash #337 scanner crash shape".to_string());
417 }
418 let tree = BashTree::parse(script)?;
419
420 let mut commands = Vec::new();
421 if reject_syntax_errors && tree.has_error() {
422 return Err("Shell script contains syntax errors".to_string());
423 }
424
425 collect_commands_from_node(tree.root(), &mut commands);
429
430 Ok(commands)
431}
432
433fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
434 match node.kind() {
435 "command" | "simple_command" => {
436 if let Some(cmd) = extract_command_from_node(node)
437 && !cmd.is_empty()
438 {
439 commands.push(cmd);
440 }
441 }
442 _ => {
443 for child in node.children() {
444 collect_commands_from_node(child, commands);
445 }
446 }
447 }
448}
449
450fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
452 let mut command = Vec::new();
453
454 if node.kind() == "pipeline" {
456 for child in node.children() {
457 if child.kind() == "command" || child.kind() == "simple_command" {
458 return extract_command_from_node(child);
459 }
460 }
461 }
462
463 for child in node.children() {
465 if child.kind() == "command_name" {
466 let trimmed = child.text().trim();
467 if !trimmed.is_empty() {
468 command.push(trimmed.to_string());
469 }
470 continue;
471 }
472
473 if matches!(child.kind(), "variable_assignment" | "concatenation") {
481 let trimmed = child.text().trim();
482 if !trimmed.is_empty() {
483 command.push(trimmed.to_string());
484 }
485 continue;
486 }
487
488 if matches!(
489 child.kind(),
490 "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
491 ) {
492 let trimmed = child.text().trim();
493 if !trimmed.is_empty() {
494 command.push(trimmed.to_string());
495 }
496 }
497 }
498
499 if command.is_empty() { None } else { Some(command) }
500}
501
502fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
504 let mut commands = Vec::new();
505 let mut current_command = String::new();
506 let mut in_quotes = false;
507 let mut quote_char = ' ';
508 let mut escaped = false;
509
510 for ch in script.chars() {
511 if escaped {
512 current_command.push(ch);
513 escaped = false;
514 continue;
515 }
516
517 match ch {
518 '\\' => {
519 escaped = true;
520 }
521 '\'' | '"' if !in_quotes => {
522 in_quotes = true;
523 quote_char = ch;
524 }
525 c if c == quote_char && in_quotes => {
526 in_quotes = false;
527 }
528 '&' | '|' | ';' if !in_quotes => {
529 if !current_command.trim().is_empty()
530 && let Ok(cmd) = tokenize_command(¤t_command)
531 {
532 commands.push(cmd);
533 }
534 current_command.clear();
535 }
536 _ => current_command.push(ch),
537 }
538 }
539
540 if !current_command.trim().is_empty()
541 && let Ok(cmd) = tokenize_command(¤t_command)
542 {
543 commands.push(cmd);
544 }
545
546 Ok(commands)
547}
548
549fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
552 shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
553}
554
555pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
563 if command.is_empty() {
564 return None;
565 }
566
567 let cmd_name = command[0].as_str();
568 let base_cmd = std::path::Path::new(cmd_name)
569 .file_name()
570 .and_then(|osstr| osstr.to_str())
571 .unwrap_or("");
572
573 if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
574 return None;
575 }
576
577 for window in command.windows(2) {
579 if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
580 let script = &window[1];
581 return parse_shell_commands(script).ok();
582 }
583 }
584
585 None
586}
587
588use anyhow::{anyhow, bail};
591
592pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
598 let mut idx = 0usize;
599 let bytes = rest.as_bytes();
600 if bytes.first() == Some(&b'-') {
601 idx += 1;
602 }
603 while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
604 idx += 1;
605 }
606 let quote = match bytes.get(idx) {
607 Some(b'\'') | Some(b'"') => bytes[idx],
608 _ => return None,
609 };
610 idx += 1;
611 let delim_start = idx;
612 while idx < bytes.len() && bytes[idx] != quote {
613 idx += 1;
614 }
615 if idx >= bytes.len() || idx == delim_start {
616 return None;
617 }
618 let delim = rest[delim_start..idx].to_string();
619 idx += 1; Some((delim, idx))
621}
622
623pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
628 let bytes = rest.as_bytes();
629 let mut idx = 0usize;
630 while idx <= bytes.len() {
631 let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
632 let line = rest[idx..line_end].trim_end_matches('\r');
633 let next = if line_end < bytes.len() {
634 line_end + 1
635 } else {
636 bytes.len()
637 };
638 if line == delim {
639 return Some(next);
640 }
641 if line_end >= bytes.len() {
642 return None;
643 }
644 idx = next;
645 }
646 None
647}
648
649fn consume_bytes(
652 chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
653 max_bytes: usize,
654 fallback: usize,
655) -> usize {
656 let mut consumed = 0usize;
657 let mut end = fallback;
658 while consumed < max_bytes
659 && let Some((idx, ch)) = chars.next()
660 {
661 consumed += ch.len_utf8();
662 end = idx + ch.len_utf8();
663 }
664 end
665}
666
667#[derive(Clone, Copy, Eq, PartialEq)]
669enum QuoteState {
670 None,
671 Single,
672 Double,
673}
674
675#[derive(Clone, Copy, Debug, PartialEq, Eq)]
677pub(crate) enum SubstitutionKind {
678 Backtick,
679 DollarParen,
680}
681
682impl SubstitutionKind {
683 fn label(self) -> &'static str {
684 match self {
685 Self::Backtick => "backtick",
686 Self::DollarParen => "'$('",
687 }
688 }
689}
690
691pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
696 anyhow!(
697 "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
698 kind.label()
699 )
700}
701
702pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
705 let mut segments = Vec::new();
706 let mut state = QuoteState::None;
707 let mut escaped = false;
708 let mut segment_start = 0usize;
709 let mut pending_heredoc: Option<String> = None;
713 let mut chars = command.char_indices().peekable();
714
715 while let Some((idx, ch)) = chars.next() {
716 match state {
717 QuoteState::Single => {
718 if ch == '\'' {
719 state = QuoteState::None;
720 }
721 }
722 QuoteState::Double => {
723 if escaped {
724 escaped = false;
725 continue;
726 }
727
728 match ch {
729 '\\' => escaped = true,
730 '"' => state = QuoteState::None,
731 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
732 '$' if matches!(chars.peek(), Some((_, '('))) => {
733 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
734 }
735 _ => {}
736 }
737 }
738 QuoteState::None => {
739 if escaped {
740 escaped = false;
741 if ch == ';' {
746 bail!("Escaped command chaining detected");
747 }
748 continue;
749 }
750
751 match ch {
752 '\\' => escaped = true,
753 '\'' => state = QuoteState::Single,
754 '"' => state = QuoteState::Double,
755 '<' if matches!(chars.peek(), Some((_, '<'))) => {
761 let _ = chars.next(); let rest: String = chars.clone().map(|(_, c)| c).collect();
763 if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
764 let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
765 pending_heredoc = Some(delim);
766 }
767 }
768 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
769 '$' if matches!(chars.peek(), Some((_, '('))) => {
770 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
771 }
772 ';' => bail!("Unquoted command chaining detected"),
773 '\n' => {
774 if let Some(delim) = pending_heredoc.take() {
779 let rest: String = chars.clone().map(|(_, c)| c).collect();
780 if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
781 push_segment(command, segment_start, idx, &mut segments);
784 segment_start = consume_bytes(&mut chars, skip, command.len());
785 continue;
786 }
787 }
788 bail!(
789 "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
790 );
791 }
792 '|' | '&' => {
793 push_segment(command, segment_start, idx, &mut segments);
794 segment_start = idx + ch.len_utf8();
795 if let Some((next_idx, next_ch)) = chars.peek().copied()
796 && next_ch == ch
797 {
798 let _next = chars.next();
799 segment_start = next_idx + next_ch.len_utf8();
800 }
801 }
802 _ => {}
803 }
804 }
805 }
806 }
807
808 push_segment(command, segment_start, command.len(), &mut segments);
809 Ok(segments)
810}
811
812fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
813 let segment = command[start..end].trim();
814 if !segment.is_empty() {
815 segments.push(segment.to_string());
816 }
817}
818
819pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
821 let segment_lower = segment.to_ascii_lowercase();
822 if segment_lower.starts_with(":(){:|:&};:") {
823 return Some(":(){:|:&};:");
824 }
825
826 let tokens =
827 shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
828 let first = tokens.first()?;
829 let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
830
831 match command_name.as_str() {
832 "rmdir" => Some("rmdir"),
833 "wget" => Some("wget"),
834 "curl" => Some("curl"),
835 "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
836 "chown"
837 if tokens.iter().skip(1).any(|arg| {
838 let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
839 arg == "root" || arg.starts_with("root:")
840 }) =>
841 {
842 Some("chown root")
843 }
844 _ => None,
845 }
846}
847
848fn strip_wrapping_quotes(token: &str) -> &str {
849 token
850 .strip_prefix('\'')
851 .and_then(|token| token.strip_suffix('\''))
852 .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
853 .unwrap_or(token)
854}
855
856fn base_command_name(command: &str) -> &str {
857 std::path::Path::new(command)
858 .file_name()
859 .and_then(|name| name.to_str())
860 .unwrap_or(command)
861}
862#[cfg(test)]
863mod crash_regression {
864 use super::*;
865
866 #[test]
870 fn parse_survives_brace_plus_astral_input() {
871 let parsed = parse_shell_commands("{\u{2FA8E}");
872 assert!(parsed.is_ok(), "parse must not fail: {parsed:?}");
873
874 let parsed = parse_shell_commands("echo {\u{2FA8E}} && echo done").expect("two commands");
877 assert_eq!(parsed.len(), 2, "both commands must survive: {parsed:?}");
878 assert!(parsed[0].contains(&"echo".to_string()), "first command tokens: {parsed:?}");
879 assert_eq!(parsed[1].last().map(String::as_str), Some("done"));
880 }
881
882 #[test]
883 fn strict_parse_rejects_crash_shape_instead_of_crashing() {
884 let result = parse_shell_commands_tree_sitter("{\u{2FA8E}");
888 assert!(result.is_err(), "strict path must reject, not crash: {result:?}");
889 }
890
891 #[test]
892 fn scanner_crash_shape_matches_issue_337_shape() {
893 assert!(scanner_crash_shape("{\u{2FA8E}"));
894 assert!(scanner_crash_shape("echo {a}\u{1F574}"));
895 assert!(scanner_crash_shape("{x} \u{1F847}"));
896 assert!(!scanner_crash_shape("\u{2FA8E}{"));
898 assert!(!scanner_crash_shape("{hello}"));
900 assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
902 }
903}
904
905#[cfg(test)]
906mod tests;