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
297fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
299 if scanner_crash_shape(script) {
304 return Err("shell script matches the tree-sitter-bash #337 scanner crash shape".to_string());
305 }
306 let tree = BashTree::parse(script)?;
307
308 let mut commands = Vec::new();
309 if reject_syntax_errors && tree.has_error() {
310 return Err("Shell script contains syntax errors".to_string());
311 }
312
313 collect_commands_from_node(tree.root(), &mut commands);
317
318 Ok(commands)
319}
320
321fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
322 match node.kind() {
323 "command" | "simple_command" => {
324 if let Some(cmd) = extract_command_from_node(node)
325 && !cmd.is_empty()
326 {
327 commands.push(cmd);
328 }
329 }
330 _ => {
331 for child in node.children() {
332 collect_commands_from_node(child, commands);
333 }
334 }
335 }
336}
337
338fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
340 let mut command = Vec::new();
341
342 if node.kind() == "pipeline" {
344 for child in node.children() {
345 if child.kind() == "command" || child.kind() == "simple_command" {
346 return extract_command_from_node(child);
347 }
348 }
349 }
350
351 for child in node.children() {
353 if child.kind() == "command_name" {
354 let trimmed = child.text().trim();
355 if !trimmed.is_empty() {
356 command.push(trimmed.to_string());
357 }
358 continue;
359 }
360
361 if matches!(child.kind(), "variable_assignment" | "concatenation") {
369 let trimmed = child.text().trim();
370 if !trimmed.is_empty() {
371 command.push(trimmed.to_string());
372 }
373 continue;
374 }
375
376 if matches!(
377 child.kind(),
378 "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
379 ) {
380 let trimmed = child.text().trim();
381 if !trimmed.is_empty() {
382 command.push(trimmed.to_string());
383 }
384 }
385 }
386
387 if command.is_empty() { None } else { Some(command) }
388}
389
390fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
392 let mut commands = Vec::new();
393 let mut current_command = String::new();
394 let mut in_quotes = false;
395 let mut quote_char = ' ';
396 let mut escaped = false;
397
398 for ch in script.chars() {
399 if escaped {
400 current_command.push(ch);
401 escaped = false;
402 continue;
403 }
404
405 match ch {
406 '\\' => {
407 escaped = true;
408 }
409 '\'' | '"' if !in_quotes => {
410 in_quotes = true;
411 quote_char = ch;
412 }
413 c if c == quote_char && in_quotes => {
414 in_quotes = false;
415 }
416 '&' | '|' | ';' if !in_quotes => {
417 if !current_command.trim().is_empty()
418 && let Ok(cmd) = tokenize_command(¤t_command)
419 {
420 commands.push(cmd);
421 }
422 current_command.clear();
423 }
424 _ => current_command.push(ch),
425 }
426 }
427
428 if !current_command.trim().is_empty()
429 && let Ok(cmd) = tokenize_command(¤t_command)
430 {
431 commands.push(cmd);
432 }
433
434 Ok(commands)
435}
436
437fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
440 shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
441}
442
443pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
451 if command.is_empty() {
452 return None;
453 }
454
455 let cmd_name = command[0].as_str();
456 let base_cmd = std::path::Path::new(cmd_name)
457 .file_name()
458 .and_then(|osstr| osstr.to_str())
459 .unwrap_or("");
460
461 if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
462 return None;
463 }
464
465 for window in command.windows(2) {
467 if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
468 let script = &window[1];
469 return parse_shell_commands(script).ok();
470 }
471 }
472
473 None
474}
475
476use anyhow::{anyhow, bail};
479
480pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
486 let mut idx = 0usize;
487 let bytes = rest.as_bytes();
488 if bytes.first() == Some(&b'-') {
489 idx += 1;
490 }
491 while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
492 idx += 1;
493 }
494 let quote = match bytes.get(idx) {
495 Some(b'\'') | Some(b'"') => bytes[idx],
496 _ => return None,
497 };
498 idx += 1;
499 let delim_start = idx;
500 while idx < bytes.len() && bytes[idx] != quote {
501 idx += 1;
502 }
503 if idx >= bytes.len() || idx == delim_start {
504 return None;
505 }
506 let delim = rest[delim_start..idx].to_string();
507 idx += 1; Some((delim, idx))
509}
510
511pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
516 let bytes = rest.as_bytes();
517 let mut idx = 0usize;
518 while idx <= bytes.len() {
519 let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
520 let line = rest[idx..line_end].trim_end_matches('\r');
521 let next = if line_end < bytes.len() {
522 line_end + 1
523 } else {
524 bytes.len()
525 };
526 if line == delim {
527 return Some(next);
528 }
529 if line_end >= bytes.len() {
530 return None;
531 }
532 idx = next;
533 }
534 None
535}
536
537fn consume_bytes(
540 chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
541 max_bytes: usize,
542 fallback: usize,
543) -> usize {
544 let mut consumed = 0usize;
545 let mut end = fallback;
546 while consumed < max_bytes
547 && let Some((idx, ch)) = chars.next()
548 {
549 consumed += ch.len_utf8();
550 end = idx + ch.len_utf8();
551 }
552 end
553}
554
555#[derive(Clone, Copy, Eq, PartialEq)]
557enum QuoteState {
558 None,
559 Single,
560 Double,
561}
562
563#[derive(Clone, Copy, Debug, PartialEq, Eq)]
565pub(crate) enum SubstitutionKind {
566 Backtick,
567 DollarParen,
568}
569
570impl SubstitutionKind {
571 fn label(self) -> &'static str {
572 match self {
573 Self::Backtick => "backtick",
574 Self::DollarParen => "'$('",
575 }
576 }
577}
578
579pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
584 anyhow!(
585 "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
586 kind.label()
587 )
588}
589
590pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
593 let mut segments = Vec::new();
594 let mut state = QuoteState::None;
595 let mut escaped = false;
596 let mut segment_start = 0usize;
597 let mut pending_heredoc: Option<String> = None;
601 let mut chars = command.char_indices().peekable();
602
603 while let Some((idx, ch)) = chars.next() {
604 match state {
605 QuoteState::Single => {
606 if ch == '\'' {
607 state = QuoteState::None;
608 }
609 }
610 QuoteState::Double => {
611 if escaped {
612 escaped = false;
613 continue;
614 }
615
616 match ch {
617 '\\' => escaped = true,
618 '"' => state = QuoteState::None,
619 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
620 '$' if matches!(chars.peek(), Some((_, '('))) => {
621 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
622 }
623 _ => {}
624 }
625 }
626 QuoteState::None => {
627 if escaped {
628 escaped = false;
629 if ch == ';' {
634 bail!("Escaped command chaining detected");
635 }
636 continue;
637 }
638
639 match ch {
640 '\\' => escaped = true,
641 '\'' => state = QuoteState::Single,
642 '"' => state = QuoteState::Double,
643 '<' if matches!(chars.peek(), Some((_, '<'))) => {
649 let _ = chars.next(); let rest: String = chars.clone().map(|(_, c)| c).collect();
651 if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
652 let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
653 pending_heredoc = Some(delim);
654 }
655 }
656 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
657 '$' if matches!(chars.peek(), Some((_, '('))) => {
658 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
659 }
660 ';' => bail!("Unquoted command chaining detected"),
661 '\n' => {
662 if let Some(delim) = pending_heredoc.take() {
667 let rest: String = chars.clone().map(|(_, c)| c).collect();
668 if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
669 push_segment(command, segment_start, idx, &mut segments);
672 segment_start = consume_bytes(&mut chars, skip, command.len());
673 continue;
674 }
675 }
676 bail!(
677 "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
678 );
679 }
680 '|' | '&' => {
681 push_segment(command, segment_start, idx, &mut segments);
682 segment_start = idx + ch.len_utf8();
683 if let Some((next_idx, next_ch)) = chars.peek().copied()
684 && next_ch == ch
685 {
686 let _next = chars.next();
687 segment_start = next_idx + next_ch.len_utf8();
688 }
689 }
690 _ => {}
691 }
692 }
693 }
694 }
695
696 push_segment(command, segment_start, command.len(), &mut segments);
697 Ok(segments)
698}
699
700fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
701 let segment = command[start..end].trim();
702 if !segment.is_empty() {
703 segments.push(segment.to_string());
704 }
705}
706
707pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
709 let segment_lower = segment.to_ascii_lowercase();
710 if segment_lower.starts_with(":(){:|:&};:") {
711 return Some(":(){:|:&};:");
712 }
713
714 let tokens =
715 shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
716 let first = tokens.first()?;
717 let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
718
719 match command_name.as_str() {
720 "rmdir" => Some("rmdir"),
721 "wget" => Some("wget"),
722 "curl" => Some("curl"),
723 "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
724 "chown"
725 if tokens.iter().skip(1).any(|arg| {
726 let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
727 arg == "root" || arg.starts_with("root:")
728 }) =>
729 {
730 Some("chown root")
731 }
732 _ => None,
733 }
734}
735
736fn strip_wrapping_quotes(token: &str) -> &str {
737 token
738 .strip_prefix('\'')
739 .and_then(|token| token.strip_suffix('\''))
740 .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
741 .unwrap_or(token)
742}
743
744fn base_command_name(command: &str) -> &str {
745 std::path::Path::new(command)
746 .file_name()
747 .and_then(|name| name.to_str())
748 .unwrap_or(command)
749}
750#[cfg(test)]
751mod crash_regression {
752 use super::*;
753
754 #[test]
758 fn parse_survives_brace_plus_astral_input() {
759 let parsed = parse_shell_commands("{\u{2FA8E}");
760 assert!(parsed.is_ok(), "parse must not fail: {parsed:?}");
761
762 let parsed = parse_shell_commands("echo {\u{2FA8E}} && echo done").expect("two commands");
765 assert_eq!(parsed.len(), 2, "both commands must survive: {parsed:?}");
766 assert!(parsed[0].contains(&"echo".to_string()), "first command tokens: {parsed:?}");
767 assert_eq!(parsed[1].last().map(String::as_str), Some("done"));
768 }
769
770 #[test]
771 fn strict_parse_rejects_crash_shape_instead_of_crashing() {
772 let result = parse_shell_commands_tree_sitter("{\u{2FA8E}");
776 assert!(result.is_err(), "strict path must reject, not crash: {result:?}");
777 }
778
779 #[test]
780 fn scanner_crash_shape_matches_issue_337_shape() {
781 assert!(scanner_crash_shape("{\u{2FA8E}"));
782 assert!(scanner_crash_shape("echo {a}\u{1F574}"));
783 assert!(scanner_crash_shape("{x} \u{1F847}"));
784 assert!(!scanner_crash_shape("\u{2FA8E}{"));
786 assert!(!scanner_crash_shape("{hello}"));
788 assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
790 }
791}
792
793#[cfg(test)]
794mod tests;