Merge pull request #1976 from curious-rabbit/master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thayne McCombs · committed by GitHub · parents 95dc645, 66be848 · Browse files · 9 files·+256 added−23 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- fix: sanitize escape sequence injection
Diff stats
9 files+256 added−23 removed
- tests:+1 added−1 removed
- other:+255 added−22 removed
Provenance
- Commit
b126064- Tree
e4e2434- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
95dc645- Parent 2
66be848
9 files changed+256 added−23 removed
modified:src/exec/mod.rs+23 added-10 removed
41 unmodified lines42 Ok(CommandSet {43 mode: ExecutionMode::OneByOne,44 commands: input45 .into_iter()46- .map(CommandTemplate::new)46+ .map(|args| CommandTemplate::new(args, ExecutionMode::OneByOne))47 .collect::<Result<_>>()?,48 })49 }50 7 unmodified lines58 mode: ExecutionMode::Batch,59 commands: input60 .into_iter()61 .map(|args| {62- let cmd = CommandTemplate::new(args)?;62+ let cmd = CommandTemplate::new(args, ExecutionMode::Batch)?;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 })146 unmodified lines216 args: Vec<FormatTemplate>,217 }218 219 impl CommandTemplate {223- fn new<I, S>(input: I) -> Result<CommandTemplate>220+ fn new<I, S>(input: I, mode: ExecutionMode) -> Result<CommandTemplate>221 where222 I: IntoIterator<Item = S>,223 S: AsRef<str>,224 {16 unmodified lines241 if args.is_empty() {242 bail!("No executable provided for --exec or --exec-batch");243 }244 245+ // A placeholder as the executable is meaningful for `--exec` but never for `--exec-batch`.246+ if mode == ExecutionMode::Batch && args[0].has_tokens() {247+ bail!("First argument of --exec-batch must be a fixed executable, not a placeholder");248+ }249+250 // If a placeholder token was not supplied, append one at the end of the command.251 if !has_placeholder {252 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));253 }112 unmodified lines366 }367 368 #[test]369 fn tokens_with_literal_braces() {368- let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();370+ let template =371+ CommandTemplate::new(vec!["{{}}", "{{", "{.}}"], ExecutionMode::OneByOne).unwrap();372 assert_eq!(373 generate_str(&template, "foo"),374 vec!["{}", "{", "{.}", "foo"]375 );376 }377 378 #[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 =381+ CommandTemplate::new(vec!["echo", "{{{},end}"], ExecutionMode::OneByOne).unwrap();382+ assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);383 }384 385 #[test]386 fn tokens_multiple() {37 unmodified lines424 }425 426 #[test]427 fn template_no_args() {424- assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());428+ assert!(429+ CommandTemplate::new::<Vec<_>, &'static str>(vec![], ExecutionMode::OneByOne).is_err()430+ );431 }432 433 #[test]434 fn command_set_no_args() {435 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());436 }437 438 #[test]439+ fn placeholder_as_executable_rejected() {440+ assert!(CommandSet::new(vec![vec!["{}"]]).is_ok());441+ assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_ok());442+ assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());443+ }444+445+ #[test]446 fn generate_custom_path_separator() {447 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);448 macro_rules! check {449 ($input:expr, $expected:expr) => {37 unmodified linesmodified:src/dir_entry.rs+36 added-2 removed
52 unmodified lines53 }54 }55 56 /// Returns the path as it should be presented to the user.57+ /// When stripping `./` would leave the path starting with `-`, keep the original58+ /// (with `./`) so downstream tools don't interpret it as an option.59 pub fn stripped_path(&self, config: &Config) -> &Path {60+ let path = self.path();61 if config.strip_cwd_prefix {59- strip_current_dir(self.path())62+ let stripped = strip_current_dir(path);63+ if starts_with_dash(stripped) {64+ path65+ } else {66+ stripped67+ }68 } else {61- self.path()69+ path70 }71 }72 73 /// Returns the path as it should be presented to the user.34 unmodified lines108 .as_ref()109 }110 }111 112+fn starts_with_dash(path: &Path) -> bool {113+ path.as_os_str().as_encoded_bytes().first() == Some(&b'-')114+}115+116 impl PartialEq for DirEntry {117 #[inline]118 fn eq(&self, other: &Self) -> bool {119 self.path() == other.path()44 unmodified lines164 fn metadata(&self) -> Option<Metadata> {165 self.metadata().cloned()166 }167 }168+169+#[cfg(test)]170+mod tests {171+ use super::starts_with_dash;172+ use std::path::Path;173+174+ #[test]175+ fn dash_prefixed_paths_detected() {176+ assert!(starts_with_dash(Path::new("-rf")));177+ assert!(starts_with_dash(Path::new("--delete")));178+ assert!(starts_with_dash(Path::new("-")));179+ }180+181+ #[test]182+ fn safe_paths_not_flagged() {183+ assert!(!starts_with_dash(Path::new("foo")));184+ assert!(!starts_with_dash(Path::new("./foo")));185+ assert!(!starts_with_dash(Path::new("sub/-rf")));186+ assert!(!starts_with_dash(Path::new("")));187+ assert!(!starts_with_dash(Path::new(" -rf")));188+ }189+}modified:src/error.rs+7 added-1 removed
1+use std::io::IsTerminal;2+3+use crate::sanitize::maybe_sanitize;4+5 pub fn print_error(msg: impl Into<String>) {6+ let msg = msg.into();7+ let safe = maybe_sanitize(&msg, std::io::stderr().is_terminal());2- eprintln!("[fd error]: {}", msg.into());8+ eprintln!("[fd error]: {safe}");9 }modified:src/main.rs+2 added-1 removed
9 unmodified lines10 mod fmt;11 mod hyperlink;12 mod output;13 mod regex_helper;14+mod sanitize;15 mod walk;16 17 use std::env;18 use std::io::IsTerminal;46 unmodified lines65 Ok(exit_code) => {66 exit_code.exit();67 }68 Err(err) => {68- eprintln!("[fd error]: {err:#}");69+ crate::error::print_error(format!("{err:#}"));70 ExitCode::GeneralError.exit();71 }72 }73 }482 unmodified linesmodified:src/output.rs+14 added-7 removed
5 unmodified lines6 use crate::config::Config;7 use crate::dir_entry::DirEntry;8 use crate::fmt::FormatTemplate;9 use crate::hyperlink::PathUrl;10+use crate::sanitize::maybe_sanitize;11 12 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14 }61 unmodified lines76 entry.stripped_path(config),77 config.path_separator.as_deref(),78 );79 // TODO: support writing raw bytes on unix?79- write!(stdout, "{}", output.to_string_lossy())80+ let s = output.to_string_lossy();81+ write!(82+ stdout,83+ "{}",84+ maybe_sanitize(&s, config.interactive_terminal)85+ )86 }87 88 // TODO: this function is performance critical and can probably be optimized89 fn print_entry_colorized<W: Write>(1 unmodified line91 entry: &DirEntry,92 config: &Config,93 ls_colors: &LsColors,94 ) -> io::Result<()> {89- // Split the path between the parent and the last component95 let mut offset = 0;96 let path = entry.stripped_path(config);97 let path_str = path.to_string_lossy();98 17 unmodified lines116 let style = ls_colors117 .style_for_indicator(Indicator::Directory)118 .map(Style::to_nu_ansi_term_style)119 .unwrap_or_default();120+ let safe_parent = maybe_sanitize(&parent_str, config.interactive_terminal);115- write!(stdout, "{}", style.paint(parent_str))?;121+ write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;122 }123 124 let style = entry125 .style(ls_colors)126 .map(Style::to_nu_ansi_term_style)127 .unwrap_or_default();128+ let safe_basename = maybe_sanitize(&path_str[offset..], config.interactive_terminal);122- write!(stdout, "{}", style.paint(&path_str[offset..]))?;129+ write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;130 131 print_trailing_slash(132 stdout,133 entry,15 unmodified lines149 let mut path_string = path.to_string_lossy();150 if let Some(ref separator) = config.path_separator {151 *path_string.to_mut() = replace_path_separator(&path_string, separator);152 }153+ let safe = maybe_sanitize(&path_string, config.interactive_terminal);146- write!(stdout, "{path_string}")?;154+ write!(stdout, "{safe}")?;155 print_trailing_slash(stdout, entry, config, None)156 }157 158 #[cfg(not(unix))]13 unmodified lines172 ) -> io::Result<()> {173 use std::os::unix::ffi::OsStrExt;174 175 if config.interactive_terminal || config.path_separator.is_some() {168- // Fall back to the base implementation176 print_entry_uncolorized_base(stdout, entry, config)177 } else {171- // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes178+ // Piped output: raw bytes so invalid UTF-8 filenames reach downstream tools intact.179 stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;180 print_trailing_slash(stdout, entry, config, None)181 }182 }added:src/sanitize.rs+168 added
1+//! TTY-output sanitization to prevent terminal escape injection via filenames.2+3+use std::borrow::Cow;4+use std::fmt::Write;5+6+/// True for any char that is neither printable nor permitted whitespace (only HT).7+/// Covers C0/C1/DEL, bidi overrides, zero-width and format chars, and tag chars.8+#[inline]9+fn needs_escape(c: char) -> bool {10+ if c == '\t' {11+ return false;12+ }13+ c.is_control()14+ || matches!(c,15+ '\u{00AD}' // soft hyphen (invisible)16+ | '\u{180E}' // Mongolian vowel separator17+ | '\u{200B}'..='\u{200F}' // zero-width + LRM/RLM18+ | '\u{202A}'..='\u{202E}' // bidi embedding/override19+ | '\u{2060}'..='\u{206F}' // word joiner, invisibles, deprecated formats20+ | '\u{FEFF}' // BOM / zero-width no-break space21+ | '\u{FFF9}'..='\u{FFFB}' // interlinear annotation22+ | '\u{E0000}'..='\u{E007F}' // language tags23+ )24+}25+26+/// Returns a `Cow<str>` borrowing `s` when no escaping is needed, otherwise an owned27+/// escaped copy. Use this when an owned `&str`/`String` is required (e.g. ANSI paint).28+pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {29+ if !s.chars().any(needs_escape) {30+ return Cow::Borrowed(s);31+ }32+ let mut out = String::with_capacity(s.len());33+ for c in s.chars() {34+ if needs_escape(c) {35+ let v = c as u32;36+ if v <= 0xFF {37+ let _ = write!(out, "\\x{v:02X}");38+ } else {39+ let _ = write!(out, "\\u{{{v:04X}}}");40+ }41+ } else {42+ out.push(c);43+ }44+ }45+ Cow::Owned(out)46+}47+48+/// Sanitize for terminal output only; raw bytes pass through on pipes/files.49+pub fn maybe_sanitize<'a>(s: &'a str, is_terminal: bool) -> Cow<'a, str> {50+ if is_terminal {51+ sanitize_for_terminal(s)52+ } else {53+ Cow::Borrowed(s)54+ }55+}56+57+#[cfg(test)]58+mod tests {59+ use super::*;60+61+ #[test]62+ fn preserves_safe_content() {63+ for s in [64+ "hello.txt",65+ "résumé.pdf",66+ "文档.txt",67+ "🦀.rs",68+ "a\tb",69+ "a\u{FFFD}b",70+ ] {71+ assert!(72+ matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),73+ "{s:?}"74+ );75+ assert_eq!(sanitize_for_terminal(s), s);76+ }77+ }78+79+ #[test]80+ fn strips_osc52_clipboard_payload() {81+ let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";82+ let safe = sanitize_for_terminal(attack);83+ assert!(!safe.contains('\x1b'));84+ assert_eq!(safe, "innocent\\x1B]52;c;cHduZWQ=\\x1B\\.txt");85+ }86+87+ #[test]88+ fn strips_cr_output_forgery() {89+ assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");90+ }91+92+ #[test]93+ fn strips_osc8_hyperlink_injection() {94+ let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";95+ assert!(!sanitize_for_terminal(attack).contains('\x1b'));96+ }97+98+ #[test]99+ fn strips_del() {100+ assert_eq!(sanitize_for_terminal("a\x7fb"), "a\\x7Fb");101+ }102+103+ #[test]104+ fn strips_bel_and_null() {105+ assert_eq!(sanitize_for_terminal("a\x07b"), "a\\x07b");106+ assert_eq!(sanitize_for_terminal("a\0b"), "a\\x00b");107+ }108+109+ #[test]110+ fn strips_newline() {111+ assert_eq!(sanitize_for_terminal("a\nb"), "a\\x0Ab");112+ }113+114+ #[test]115+ fn escape_preserves_information() {116+ let s = "name\x1bX\x07Y.txt";117+ assert_eq!(sanitize_for_terminal(s), "name\\x1BX\\x07Y.txt");118+ }119+120+ #[test]121+ fn strips_c1_csi_and_osc_initiators() {122+ // U+009B is CSI, U+009D is OSC; dangerous on 8-bit-control terminals.123+ assert_eq!(sanitize_for_terminal("\u{9b}31m"), "\\x9B31m");124+ assert_eq!(125+ sanitize_for_terminal("\u{9d}0;pwned\u{9c}"),126+ "\\x9D0;pwned\\x9C"127+ );128+ }129+130+ #[test]131+ fn strips_bidi_overrides_and_zero_width() {132+ // Trojan-Source style RLO/LRO that flip rendered order of filename text.133+ assert_eq!(134+ sanitize_for_terminal("safe\u{202E}fil\u{202D}gnp.exe"),135+ "safe\\u{202E}fil\\u{202D}gnp.exe"136+ );137+ // Zero-width space and BOM are also format chars used to disguise filenames.138+ assert_eq!(sanitize_for_terminal("a\u{200B}b"), "a\\u{200B}b");139+ assert_eq!(sanitize_for_terminal("\u{FEFF}name"), "\\u{FEFF}name");140+ }141+142+ #[test]143+ fn keeps_legitimate_unicode_features() {144+ // Variation selectors (U+FE0F, U+E0100..) modify preceding glyphs in CJK/emoji145+ // and are legitimate in filenames. Private-use chars are used by icon fonts.146+ for s in [147+ "heart\u{2764}\u{FE0F}.txt",148+ "icon\u{E000}.cfg",149+ "cjk\u{6F22}\u{E0101}.txt",150+ ] {151+ assert!(152+ matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),153+ "{s:?}"154+ );155+ }156+ }157+158+ #[test]159+ fn maybe_sanitize_passthrough_when_not_terminal() {160+ let attack = "x\x1by";161+ // Pipe context: bytes pass through unchanged (zero-copy).162+ let out = maybe_sanitize(attack, false);163+ assert!(matches!(out, Cow::Borrowed(_)));164+ assert_eq!(out, attack);165+ // TTY context: escapes apply.166+ assert_eq!(maybe_sanitize(attack, true), "x\\x1By");167+ }168+}modified:tests/tests.rs+1 added-1 removed
1979 unmodified lines1980 );1981 1982 te.assert_failure_with_error(1983 &["foo", "--exec-batch", "echo {}"],1984- "error: First argument of exec-batch is expected to be a fixed executable\n\1984+ "error: First argument of --exec-batch must be a fixed executable, not a placeholder\n\1985 \n\1986 Usage: fd [OPTIONS] [pattern] [path]...\n\1987 \n\1988 For more information, try '--help'.\n\890 unmodified linesmodified:Cargo.toml+1 added-1 removed
93 unmodified lines9495969798989910010110213 unmodified lines93 unmodified lines[features]use-jemalloc = ["tikv-jemallocator"]completions = ["clap_complete"]base = ["use-jemalloc"]default = ["use-jemalloc", "completions"]default = ["completions"]
[package.metadata.binstall]pkg-url = "{ repo }/releases/download/v{ version }/{ name }-v{ version }-{ target }.{ archive-format }"bin-dir = "{ bin }-v{ version }-{ target }/{ bin }{ binary-ext }"13 unmodified linesmodified:CHANGELOG.md+4 added
3 unmodified lines4 - Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)5 - Add `--exact` option to match the entire filename exactly (literal, non-substring).6 7 ## Bugfixes8+- Sanitize control characters and bidirectional override characters in filenames9+ when output goes to a terminal, to prevent terminal escape-sequence injection.10+ Also reject a placeholder as the executable for `--exec-batch`, while still11+ allowing it for `--exec`.12 - Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).13 - Fire the "search pattern contains a path separator" diagnostic for any pattern containing `/`, not just patterns that happen to name an existing directory. Preserves the legacy Windows behaviour that also flags native `\` separators when the pattern resolves to a real directory. See #1873.14 - Also fire the "search pattern contains a path separator" diagnostic for `--and` patterns, not only the primary positional pattern. `--and` patterns are matched against the file name just like the primary pattern, so a path separator in them silently returned zero results. See #1873.15 - Fix bug where passing "-" as a directory argument didn't actually search that directory, see #849 (@Sean-Kenneth-Doherty).852 unmodified lines