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