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
28pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
39 match parse_with_tree_sitter(script, false) {
41 Ok(commands) if !commands.is_empty() => return Ok(commands),
42 Ok(_) => {} Err(e) => {
44 tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
45 }
46 }
47
48 parse_with_basic_tokenization(script)
50}
51
52pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
56 parse_with_tree_sitter(script, true)
57}
58
59pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
69 enum ShellQuote {
70 Single,
71 Double,
72 }
73
74 let mut quote: Option<ShellQuote> = None;
75 let mut characters = command.chars();
76
77 while let Some(character) = characters.next() {
78 match quote {
79 Some(ShellQuote::Single) => {
80 if character == '\'' {
81 quote = None;
82 }
83 }
84 Some(ShellQuote::Double) => match character {
85 '"' => quote = None,
86 '$' | '`' => return true,
87 '\\'
88 if characters.next().is_none() => {
94 return true;
95 }
96 _ => {}
97 },
98 None => match character {
99 '\'' => quote = Some(ShellQuote::Single),
100 '"' => quote = Some(ShellQuote::Double),
101 '\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
102 _ => {}
103 },
104 }
105 }
106
107 quote.is_some()
108}
109
110pub fn contains_dynamic_find_syntax(script: &str) -> bool {
113 if let Ok(commands) = parse_shell_commands_tree_sitter(script)
114 && commands.iter().any(|command| {
115 command
116 .first()
117 .map(|program| base_command_name(program) == "find")
118 .unwrap_or(false)
119 && command.iter().any(|word| contains_dynamic_shell_syntax(word))
120 })
121 {
122 return true;
123 }
124
125 let has_find_word = script.split_whitespace().any(|word| {
129 let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
130 base_command_name(command) == "find"
131 });
132 has_find_word && contains_dynamic_shell_syntax(script)
133}
134
135pub fn has_only_output_redirections(script: &str) -> bool {
139 if contains_dynamic_shell_syntax(script) {
140 return false;
141 }
142 if contains_background_operator(script) {
143 return false;
144 }
145
146 let Ok(tree) = BashTree::parse(script) else {
147 return false;
148 };
149 if tree.has_error() {
150 return false;
151 }
152
153 let mut saw_redirection = false;
154 if !collect_output_redirections(tree.root(), &mut saw_redirection) {
155 return false;
156 }
157 saw_redirection
158}
159
160pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
163 use anyhow::{Context, anyhow, ensure};
164 if !script.contains(['<', '>']) {
165 return Ok(());
166 }
167 let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
168 ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
169 let mut pending = vec![tree.root()];
170 while let Some(node) = pending.pop() {
171 if node.kind() == "file_redirect" {
172 let text = node.text();
173 let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
174 let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
175 for destination in node.field_children("destination") {
176 let raw = destination.text();
177 ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
178 let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
179 ensure!(words.len() == 1, "redirection destination must be one literal path");
180 let path = words.first().context("missing redirection destination")?;
181 if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
182 continue;
183 }
184 ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
189 if path == "/dev/null" {
191 continue;
192 }
193 vtcode_commons::paths::validate_path_safety(path)
194 .with_context(|| format!("unsafe shell redirection destination: {path}"))?;
195 }
196 }
197 pending.extend(node.named_children());
198 }
199 Ok(())
200}
201
202fn contains_background_operator(script: &str) -> bool {
203 let chars = script.chars().collect::<Vec<_>>();
204 let mut index = 0;
205 let mut in_single_quote = false;
206 let mut in_double_quote = false;
207
208 while index < chars.len() {
209 let character = chars[index];
210 if character == '\'' && !in_double_quote {
211 in_single_quote.toggle();
212 index += 1;
213 continue;
214 }
215 if character == '"' && !in_single_quote {
216 in_double_quote.toggle();
217 index += 1;
218 continue;
219 }
220 if in_single_quote || in_double_quote {
221 index += 1;
222 continue;
223 }
224
225 if character == '&' {
226 let previous = index.checked_sub(1).and_then(|position| chars.get(position));
227 let next = chars.get(index + 1);
228 if next == Some(&'&') {
229 index += 2;
230 continue;
231 }
232 let part_of_allowed_operator = next == Some(&'&')
233 || next == Some(&'>')
234 || previous == Some(&'>')
235 || previous == Some(&'|')
236 || previous == Some(&'<');
237 if !part_of_allowed_operator {
238 return true;
239 }
240 }
241 index += 1;
242 }
243
244 false
245}
246
247fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
248 match node.kind() {
249 "file_redirect" => {
250 *saw_redirection = true;
251 if !is_output_redirection(node.text()) {
252 return false;
253 }
254 }
255 "heredoc_redirect" | "herestring_redirect" => return false,
256 _ => {}
257 }
258
259 node.children()
260 .iter()
261 .all(|child| collect_output_redirections(*child, saw_redirection))
262}
263
264fn is_output_redirection(text: &str) -> bool {
265 let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
266 if redirect.starts_with("&>") {
267 return !redirect.starts_with("&>-");
268 }
269 if let Some(destination) = redirect.strip_prefix(">&") {
270 return destination.trim().chars().all(|character| character.is_ascii_digit());
271 }
272
273 redirect.starts_with('>') && !redirect.starts_with(">&-")
274}
275
276fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
278 let tree = BashTree::parse(script)?;
279
280 let mut commands = Vec::new();
281 if reject_syntax_errors && tree.has_error() {
282 return Err("Shell script contains syntax errors".to_string());
283 }
284
285 collect_commands_from_node(tree.root(), &mut commands);
289
290 Ok(commands)
291}
292
293fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
294 match node.kind() {
295 "command" | "simple_command" => {
296 if let Some(cmd) = extract_command_from_node(node)
297 && !cmd.is_empty()
298 {
299 commands.push(cmd);
300 }
301 }
302 _ => {
303 for child in node.children() {
304 collect_commands_from_node(child, commands);
305 }
306 }
307 }
308}
309
310fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
312 let mut command = Vec::new();
313
314 if node.kind() == "pipeline" {
316 for child in node.children() {
317 if child.kind() == "command" || child.kind() == "simple_command" {
318 return extract_command_from_node(child);
319 }
320 }
321 }
322
323 for child in node.children() {
325 if child.kind() == "command_name" {
326 let trimmed = child.text().trim();
327 if !trimmed.is_empty() {
328 command.push(trimmed.to_string());
329 }
330 continue;
331 }
332
333 if matches!(child.kind(), "variable_assignment" | "concatenation") {
341 let trimmed = child.text().trim();
342 if !trimmed.is_empty() {
343 command.push(trimmed.to_string());
344 }
345 continue;
346 }
347
348 if matches!(
349 child.kind(),
350 "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
351 ) {
352 let trimmed = child.text().trim();
353 if !trimmed.is_empty() {
354 command.push(trimmed.to_string());
355 }
356 }
357 }
358
359 if command.is_empty() { None } else { Some(command) }
360}
361
362fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
364 let mut commands = Vec::new();
365 let mut current_command = String::new();
366 let mut in_quotes = false;
367 let mut quote_char = ' ';
368 let mut escaped = false;
369
370 for ch in script.chars() {
371 if escaped {
372 current_command.push(ch);
373 escaped = false;
374 continue;
375 }
376
377 match ch {
378 '\\' => {
379 escaped = true;
380 }
381 '\'' | '"' if !in_quotes => {
382 in_quotes = true;
383 quote_char = ch;
384 }
385 c if c == quote_char && in_quotes => {
386 in_quotes = false;
387 }
388 '&' | '|' | ';' if !in_quotes => {
389 if !current_command.trim().is_empty()
390 && let Ok(cmd) = tokenize_command(¤t_command)
391 {
392 commands.push(cmd);
393 }
394 current_command.clear();
395 }
396 _ => current_command.push(ch),
397 }
398 }
399
400 if !current_command.trim().is_empty()
401 && let Ok(cmd) = tokenize_command(¤t_command)
402 {
403 commands.push(cmd);
404 }
405
406 Ok(commands)
407}
408
409fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
412 shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
413}
414
415pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
423 if command.is_empty() {
424 return None;
425 }
426
427 let cmd_name = command[0].as_str();
428 let base_cmd = std::path::Path::new(cmd_name)
429 .file_name()
430 .and_then(|osstr| osstr.to_str())
431 .unwrap_or("");
432
433 if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
434 return None;
435 }
436
437 for window in command.windows(2) {
439 if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
440 let script = &window[1];
441 return parse_shell_commands(script).ok();
442 }
443 }
444
445 None
446}
447
448use anyhow::{anyhow, bail};
451
452pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
458 let mut idx = 0usize;
459 let bytes = rest.as_bytes();
460 if bytes.first() == Some(&b'-') {
461 idx += 1;
462 }
463 while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
464 idx += 1;
465 }
466 let quote = match bytes.get(idx) {
467 Some(b'\'') | Some(b'"') => bytes[idx],
468 _ => return None,
469 };
470 idx += 1;
471 let delim_start = idx;
472 while idx < bytes.len() && bytes[idx] != quote {
473 idx += 1;
474 }
475 if idx >= bytes.len() || idx == delim_start {
476 return None;
477 }
478 let delim = rest[delim_start..idx].to_string();
479 idx += 1; Some((delim, idx))
481}
482
483pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
488 let bytes = rest.as_bytes();
489 let mut idx = 0usize;
490 while idx <= bytes.len() {
491 let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
492 let line = rest[idx..line_end].trim_end_matches('\r');
493 let next = if line_end < bytes.len() {
494 line_end + 1
495 } else {
496 bytes.len()
497 };
498 if line == delim {
499 return Some(next);
500 }
501 if line_end >= bytes.len() {
502 return None;
503 }
504 idx = next;
505 }
506 None
507}
508
509fn consume_bytes(
512 chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
513 max_bytes: usize,
514 fallback: usize,
515) -> usize {
516 let mut consumed = 0usize;
517 let mut end = fallback;
518 while consumed < max_bytes
519 && let Some((idx, ch)) = chars.next()
520 {
521 consumed += ch.len_utf8();
522 end = idx + ch.len_utf8();
523 }
524 end
525}
526
527#[derive(Clone, Copy, Eq, PartialEq)]
529enum QuoteState {
530 None,
531 Single,
532 Double,
533}
534
535#[derive(Clone, Copy, Debug, PartialEq, Eq)]
537pub(crate) enum SubstitutionKind {
538 Backtick,
539 DollarParen,
540}
541
542impl SubstitutionKind {
543 fn label(self) -> &'static str {
544 match self {
545 Self::Backtick => "backtick",
546 Self::DollarParen => "'$('",
547 }
548 }
549}
550
551pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
556 anyhow!(
557 "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
558 kind.label()
559 )
560}
561
562pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
565 let mut segments = Vec::new();
566 let mut state = QuoteState::None;
567 let mut escaped = false;
568 let mut segment_start = 0usize;
569 let mut pending_heredoc: Option<String> = None;
573 let mut chars = command.char_indices().peekable();
574
575 while let Some((idx, ch)) = chars.next() {
576 match state {
577 QuoteState::Single => {
578 if ch == '\'' {
579 state = QuoteState::None;
580 }
581 }
582 QuoteState::Double => {
583 if escaped {
584 escaped = false;
585 continue;
586 }
587
588 match ch {
589 '\\' => escaped = true,
590 '"' => state = QuoteState::None,
591 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
592 '$' if matches!(chars.peek(), Some((_, '('))) => {
593 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
594 }
595 _ => {}
596 }
597 }
598 QuoteState::None => {
599 if escaped {
600 escaped = false;
601 if ch == ';' {
606 bail!("Escaped command chaining detected");
607 }
608 continue;
609 }
610
611 match ch {
612 '\\' => escaped = true,
613 '\'' => state = QuoteState::Single,
614 '"' => state = QuoteState::Double,
615 '<' if matches!(chars.peek(), Some((_, '<'))) => {
621 let _ = chars.next(); let rest: String = chars.clone().map(|(_, c)| c).collect();
623 if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
624 let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
625 pending_heredoc = Some(delim);
626 }
627 }
628 '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
629 '$' if matches!(chars.peek(), Some((_, '('))) => {
630 return Err(substitution_error(SubstitutionKind::DollarParen, idx));
631 }
632 ';' => bail!("Unquoted command chaining detected"),
633 '\n' => {
634 if let Some(delim) = pending_heredoc.take() {
639 let rest: String = chars.clone().map(|(_, c)| c).collect();
640 if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
641 push_segment(command, segment_start, idx, &mut segments);
644 segment_start = consume_bytes(&mut chars, skip, command.len());
645 continue;
646 }
647 }
648 bail!(
649 "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
650 );
651 }
652 '|' | '&' => {
653 push_segment(command, segment_start, idx, &mut segments);
654 segment_start = idx + ch.len_utf8();
655 if let Some((next_idx, next_ch)) = chars.peek().copied()
656 && next_ch == ch
657 {
658 let _next = chars.next();
659 segment_start = next_idx + next_ch.len_utf8();
660 }
661 }
662 _ => {}
663 }
664 }
665 }
666 }
667
668 push_segment(command, segment_start, command.len(), &mut segments);
669 Ok(segments)
670}
671
672fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
673 let segment = command[start..end].trim();
674 if !segment.is_empty() {
675 segments.push(segment.to_string());
676 }
677}
678
679pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
681 let segment_lower = segment.to_ascii_lowercase();
682 if segment_lower.starts_with(":(){:|:&};:") {
683 return Some(":(){:|:&};:");
684 }
685
686 let tokens =
687 shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
688 let first = tokens.first()?;
689 let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
690
691 match command_name.as_str() {
692 "rmdir" => Some("rmdir"),
693 "wget" => Some("wget"),
694 "curl" => Some("curl"),
695 "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
696 "chown"
697 if tokens.iter().skip(1).any(|arg| {
698 let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
699 arg == "root" || arg.starts_with("root:")
700 }) =>
701 {
702 Some("chown root")
703 }
704 _ => None,
705 }
706}
707
708fn strip_wrapping_quotes(token: &str) -> &str {
709 token
710 .strip_prefix('\'')
711 .and_then(|token| token.strip_suffix('\''))
712 .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
713 .unwrap_or(token)
714}
715
716fn base_command_name(command: &str) -> &str {
717 std::path::Path::new(command)
718 .file_name()
719 .and_then(|name| name.to_str())
720 .unwrap_or(command)
721}
722#[cfg(test)]
723mod tests;