Skip to content
Myr

fix: sanitize escape sequence injection

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by curious-rabbit · committed by curious-rabbit · parent 90e73d7 · Browse files · 6 files+257 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+257 added−18 removed

  • other:+257 added−18 removed

6 files+257 added−18 removed

modified:src/exec/mod.rs+18 added-8 removed
61 unmodified lines
62 let cmd = CommandTemplate::new(args)?;63 if cmd.number_of_tokens() > 1 {64 bail!("Only one placeholder allowed for batch commands");65 }66 if cmd.args[0].has_tokens() {67 bail!("First argument of exec-batch is expected to be a fixed executable");68 }66 Ok(cmd)67 })68 .collect::<Result<Vec<_>>>()?,69 })
104 unmodified lines
174 if self.limit > 0 && self.count >= self.limit {175 self.finish()?;176 }177181 let arg = self.path_arg.generate(path, separator);178 let arg = self.path_arg.generate_for_exec(path, separator);179 if !self180 .cmd181 .args_would_fit(iter::once(&arg).chain(&self.post_args))182 {
58 unmodified lines
241 if args.is_empty() {242 bail!("No executable provided for --exec or --exec-batch");243 }244245 // The first argument is the command to execute and must be a fixed string;246 // allowing a placeholder here would turn every matched file into an execve target.247 if args[0].has_tokens() {248 bail!("First argument of --exec/--exec-batch must be a fixed executable, not a placeholder");249 }250251 // If a placeholder token was not supplied, append one at the end of the command.252 if !has_placeholder {253 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));254 }
9 unmodified lines
264 ///265 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be266 /// build.267 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {265 let mut cmd = Command::new(self.args[0].generate(input, path_separator));268 let mut cmd = Command::new(self.args[0].generate_for_exec(input, path_separator));269 for arg in &self.args[1..] {267 cmd.try_arg(arg.generate(input, path_separator))?;270 cmd.try_arg(arg.generate_for_exec(input, path_separator))?;271 }272 Ok(cmd)273 }274}
101 unmodified lines
376 }377378 #[test]379 fn tokens_with_literal_braces_and_placeholder() {377 let template = CommandTemplate::new(vec!["{{{},end}"]).unwrap();378 assert_eq!(generate_str(&template, "foo"), vec!["{foo,end}"]);380 let template = CommandTemplate::new(vec!["echo", "{{{},end}"]).unwrap();381 assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);382 }383384 #[test]385 fn tokens_multiple() {
46 unmodified lines
432 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());433 }434435 #[test]436 fn placeholder_as_executable_rejected() {437 assert!(CommandSet::new(vec![vec!["{}"]]).is_err());438 assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_err());439 assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());440 }441442 #[test]443 fn generate_custom_path_separator() {444 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);445 macro_rules! check {446 ($input:expr, $expected:expr) => {
37 unmodified lines
modified:src/fmt/mod.rs+124 added-1 removed
22 unmodified lines
23 BasenameNoExt,24 Text(String),25}2627impl Token {28 fn is_path_derived(&self) -> bool {29 matches!(30 self,31 Token::Placeholder32 | Token::Basename33 | Token::Parent34 | Token::NoExt35 | Token::BasenameNoExt36 )37 }38}3940impl Display for Token {41 fn fmt(&self, f: &mut Formatter) -> fmt::Result {42 match *self {43 Token::Placeholder => f.write_str("{}")?,
78 unmodified lines
122 /// Generate a result string from this template. If path_separator is Some, then it will replace123 /// the path separator in all placeholder tokens. Fixed text and tokens are not affected by124 /// path separator substitution.125 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {126 self.generate_impl(path.as_ref(), path_separator, false)127 }128129 /// Like `generate`, but prepends `./` when a path-derived token produces a leading `-`,130 /// so the target of `--exec` does not see it as an option.131 pub fn generate_for_exec(132 &self,133 path: impl AsRef<Path>,134 path_separator: Option<&str>,135 ) -> OsString {136 self.generate_impl(path.as_ref(), path_separator, true)137 }138139 fn generate_impl(140 &self,141 path: &Path,142 path_separator: Option<&str>,143 protect_leading_dash: bool,144 ) -> OsString {145 use Token::*;114 let path = path.as_ref();146147 match *self {148 Self::Tokens(ref tokens) => {149 let mut s = OsString::new();
14 unmodified lines
164 }165 Text(string) => s.push(string),166 }167 }168169 if protect_leading_dash170 && tokens.first().is_some_and(|t| t.is_path_derived())171 && s.as_encoded_bytes().first() == Some(&b'-')172 {173 let mut prefixed = OsString::from("./");174 prefixed.push(s);175 return prefixed;176 }177178 s179 }180 Self::Text(ref text) => OsString::from(text),181 }
136 unmodified lines
318 noExt=a/folder/file \319 basenameNoExt=file }"320 );321 }322323 fn tmpl(s: &str) -> FormatTemplate {324 FormatTemplate::parse(s)325 }326327 #[test]328 fn exec_basename_with_leading_dash_is_guarded() {329 let out = tmpl("{/}")330 .generate_for_exec(Path::new("./some/dir/-rf"), None)331 .into_string()332 .unwrap();333 assert_eq!(out, "./-rf");334 }335336 #[test]337 fn exec_basename_no_ext_with_leading_dash_is_guarded() {338 let out = tmpl("{/.}")339 .generate_for_exec(Path::new("./some/dir/-evil.txt"), None)340 .into_string()341 .unwrap();342 assert_eq!(out, "./-evil");343 }344345 #[test]346 fn exec_parent_with_leading_dash_is_guarded() {347 let out = tmpl("{//}")348 .generate_for_exec(Path::new("-startdir/inner/file.txt"), None)349 .into_string()350 .unwrap();351 assert_eq!(out, "./-startdir/inner");352 }353354 #[test]355 fn exec_plain_placeholder_already_safe() {356 let out = tmpl("{}")357 .generate_for_exec(Path::new("./some/dir/-rf"), None)358 .into_string()359 .unwrap();360 assert_eq!(out, "./some/dir/-rf");361 }362363 #[test]364 fn exec_user_literal_dash_prefix_not_rewritten() {365 let out = tmpl("-{/}")366 .generate_for_exec(Path::new("./some/dir/normal.txt"), None)367 .into_string()368 .unwrap();369 assert_eq!(out, "-normal.txt");370 }371372 #[test]373 fn exec_user_literal_dash_before_dash_basename() {374 let out = tmpl("-{/}")375 .generate_for_exec(Path::new("./some/dir/-name"), None)376 .into_string()377 .unwrap();378 assert_eq!(out, "--name");379 }380381 #[test]382 fn exec_suffix_after_placeholder_preserves_guard() {383 let out = tmpl("{/}.bak")384 .generate_for_exec(Path::new("./some/dir/-foo"), None)385 .into_string()386 .unwrap();387 assert_eq!(out, "./-foo.bak");388 }389390 #[test]391 fn format_mode_does_not_protect_leading_dash() {392 let out = tmpl("{/}")393 .generate(Path::new("./some/dir/-rf"), None)394 .into_string()395 .unwrap();396 assert_eq!(out, "-rf");397 }398399 #[test]400 fn exec_empty_result_not_prefixed() {401 let out = tmpl("{/}").generate_for_exec(Path::new(""), None);402 assert!(out.is_empty());403 }404}
modified:src/error.rs+10 added-1 removed
1use std::io::IsTerminal;23use crate::sanitize::sanitize_for_terminal;45pub fn print_error(msg: impl Into<String>) {6 let msg = msg.into();7 if std::io::stderr().is_terminal() {8 eprintln!("[fd error]: {}", sanitize_for_terminal(&msg));9 } else {2 eprintln!("[fd error]: {}", msg.into());10 eprintln!("[fd error]: {msg}");11 }12}
modified:src/main.rs+8 added-1 removed
9 unmodified lines
10mod fmt;11mod hyperlink;12mod output;13mod regex_helper;14mod sanitize;15mod walk;1617use std::env;18use std::io::IsTerminal;
46 unmodified lines
65 Ok(exit_code) => {66 exit_code.exit();67 }68 Err(err) => {69 // Gap fix: anyhow errors bubbled from run() may embed user paths/args.70 let formatted = format!("{err:#}");71 if std::io::stderr().is_terminal() {72 eprintln!("[fd error]: {}", sanitize::sanitize_for_terminal(&formatted));73 } else {68 eprintln!("[fd error]: {err:#}");74 eprintln!("[fd error]: {formatted}");75 }76 ExitCode::GeneralError.exit();77 }78 }79}
429 unmodified lines
modified:src/output.rs+19 added-7 removed
5 unmodified lines
6use crate::config::Config;7use crate::dir_entry::DirEntry;8use crate::fmt::FormatTemplate;9use crate::hyperlink::PathUrl;10use crate::sanitize::sanitize_for_terminal;1112fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14}1516/// Sanitize a string for terminal output only; raw bytes pass through on pipes.17fn maybe_sanitize<'a>(s: &'a str, config: &Config) -> Cow<'a, str> {18 if config.interactive_terminal {19 sanitize_for_terminal(s)20 } else {21 Cow::Borrowed(s)22 }23}2425// TODO: this function is performance critical and can probably be optimized26pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) -> io::Result<()> {27 let mut has_hyperlink = false;28 if config.hyperlink
56 unmodified lines
85 entry.stripped_path(config),86 config.path_separator.as_deref(),87 );88 // TODO: support writing raw bytes on unix?79 write!(stdout, "{}", output.to_string_lossy())89 let s = output.to_string_lossy();90 write!(stdout, "{}", maybe_sanitize(&s, config))91}9293// TODO: this function is performance critical and can probably be optimized94fn print_entry_colorized<W: Write>(
1 unmodified line
96 entry: &DirEntry,97 config: &Config,98 ls_colors: &LsColors,99) -> io::Result<()> {89 // Split the path between the parent and the last component100 let mut offset = 0;101 let path = entry.stripped_path(config);102 let path_str = path.to_string_lossy();103
17 unmodified lines
121 let style = ls_colors122 .style_for_indicator(Indicator::Directory)123 .map(Style::to_nu_ansi_term_style)124 .unwrap_or_default();125 let safe_parent = maybe_sanitize(&parent_str, config);115 write!(stdout, "{}", style.paint(parent_str))?;126 write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;127 }128129 let style = entry130 .style(ls_colors)131 .map(Style::to_nu_ansi_term_style)132 .unwrap_or_default();133 let safe_basename = maybe_sanitize(&path_str[offset..], config);122 write!(stdout, "{}", style.paint(&path_str[offset..]))?;134 write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;135136 print_trailing_slash(137 stdout,138 entry,
15 unmodified lines
154 let mut path_string = path.to_string_lossy();155 if let Some(ref separator) = config.path_separator {156 *path_string.to_mut() = replace_path_separator(&path_string, separator);157 }158 let safe = maybe_sanitize(&path_string, config);146 write!(stdout, "{path_string}")?;159 write!(stdout, "{safe}")?;160 print_trailing_slash(stdout, entry, config, None)161}162163#[cfg(not(unix))]
13 unmodified lines
177) -> io::Result<()> {178 use std::os::unix::ffi::OsStrExt;179180 if config.interactive_terminal || config.path_separator.is_some() {168 // Fall back to the base implementation181 print_entry_uncolorized_base(stdout, entry, config)182 } else {171 // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes183 // Piped output: raw bytes so invalid UTF-8 filenames reach downstream tools intact.184 stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;185 print_trailing_slash(stdout, entry, config, None)186 }187}
added:src/sanitize.rs+78 added
1//! TTY-output sanitization to prevent terminal escape injection via filenames.23use std::borrow::Cow;45#[inline]6fn is_dangerous_control(c: char) -> bool {7 // C0 (except HT), DEL, and C1 controls (gap fix: U+0080..=U+009F can act8 // as single-byte CSI/OSC initiators on 8-bit-control terminals).9 matches!(c, '\x00'..='\x08' | '\x0A'..='\x1F' | '\x7F' | '\u{80}'..='\u{9F}')10}1112/// Replace control characters with `?` (matches `ls -q`). Borrows on the fast path.13pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {14 if !s.chars().any(is_dangerous_control) {15 return Cow::Borrowed(s);16 }17 Cow::Owned(18 s.chars()19 .map(|c| if is_dangerous_control(c) { '?' } else { c })20 .collect(),21 )22}2324#[cfg(test)]25mod tests {26 use super::*;2728 #[test]29 fn preserves_safe_content() {30 // Plain text, unicode, tab, and existing U+FFFD all pass through without allocation.31 for s in ["hello.txt", "résumé.pdf", "文档.txt", "🦀.rs", "a\tb", "a\u{FFFD}b"] {32 assert!(matches!(sanitize_for_terminal(s), Cow::Borrowed(_)), "{s:?}");33 assert_eq!(sanitize_for_terminal(s), s);34 }35 }3637 #[test]38 fn strips_osc52_clipboard_payload() {39 let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";40 let safe = sanitize_for_terminal(attack);41 assert!(!safe.contains('\x1b'));42 assert_eq!(safe, "innocent?]52;c;cHduZWQ=?\\.txt");43 }4445 #[test]46 fn strips_cr_output_forgery() {47 assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A?FAKE OUTPUT");48 }4950 #[test]51 fn strips_osc8_hyperlink_injection() {52 let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";53 assert!(!sanitize_for_terminal(attack).contains('\x1b'));54 }5556 #[test]57 fn strips_del() {58 assert_eq!(sanitize_for_terminal("a\x7fb"), "a?b");59 }6061 #[test]62 fn strips_bel_and_null() {63 assert_eq!(sanitize_for_terminal("a\x07b"), "a?b");64 assert_eq!(sanitize_for_terminal("a\0b"), "a?b");65 }6667 #[test]68 fn strips_newline() {69 assert_eq!(sanitize_for_terminal("a\nb"), "a?b");70 }7172 #[test]73 fn strips_c1_csi_and_osc_initiators() {74 // U+009B is CSI, U+009D is OSC; dangerous on 8-bit-control terminals.75 assert_eq!(sanitize_for_terminal("\u{9b}31m"), "?31m");76 assert_eq!(sanitize_for_terminal("\u{9d}0;pwned\u{9c}"), "?0;pwned?");77 }78}