fix: Better sanitizing
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This refactors the sanitization code somewhat, to provide a couple benefits: - Ensure we sanitize output in error messages (#2119), while not escaping newlines from error messages. - Avoids some unnecessary allocations and string copies - Makes `print_error` a little nicer to use. As a macro, it avoids needing a separate call to `format!`. The main downside is added complexity.
authored by Thayne McCombs · committed by Thayne McCombs · parent b422e5d · Browse files · 10 files·+209 added−90 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Fixes: #2119
Diff stats
10 files+209 added−90 removed
- tests:+51 added−5 removed
- other:+158 added−85 removed
Provenance
- Commit
24198d9- Tree
ba25013- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
Thayne McCombs <astrothayne@gmail.com>- Parent
b422e5d
10 files changed+209 added−90 removed
modified:src/exec/command.rs+5 added-6 removed
1 unmodified line2 use std::io::Write;3 4 use argmax::Command;5 6-use crate::error::print_error;6 use crate::exit_codes::ExitCode;7 8 struct Outputs {9 stdout: Vec<u8>,89 unmodified lines99 100 pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {101 match (cmd, err) {102 (Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {104- print_error(format!(105- "Command not found: {}",106- cmd.get_program().to_string_lossy()107- ));103+ print_error!(104+ "Command not found: {:?}",105+ cmd.get_program().to_string_lossy().as_ref()106+ );107 ExitCode::GeneralError108 }109 (_, err) => {111- print_error(format!("Problem while executing command: {err}"));110+ print_error!("Problem while executing command: {}", err);111 ExitCode::GeneralError112 }113 }114 }modified:src/exec/job.rs+2 added-3 removed
1 use crate::config::Config;2-use crate::error::print_error;2 use crate::exit_codes::{ExitCode, merge_exitcodes};3 use crate::walk::WorkerResult;4 5 use super::CommandSet;16 unmodified lines22 let dir_entry = match result {23 WorkerResult::Entry(dir_entry) => dir_entry,24 WorkerResult::Error(err) => {25 if config.show_filesystem_errors {27- print_error(err.to_string());26+ print_error!("{}", err);27 }28 continue;29 }30 };21 unmodified lines52 .filter_map(|worker_result| match worker_result {53 WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),54 WorkerResult::Error(err) => {55 if config.show_filesystem_errors {57- print_error(err.to_string());56+ print_error!("{}", err);57 }58 None59 }60 });3 unmodified linesmodified:src/cli.rs+6 added-5 removed
9 unmodified lines10 #[cfg(feature = "completions")]11 use clap_complete::Shell;12 use normpath::PathExt;13 14-use crate::error::print_error;14 use crate::exec::CommandSet;15 use crate::filesystem;16 #[cfg(unix)]17 use crate::filter::OwnerFilter;691 unmodified lines709 .filter_map(|path| {710 if filesystem::is_existing_directory(path) {711 Some(self.normalize_path(path))712 } else {713+ // We use debug for the path to make it more readable if it has special characters714+ // Should we use a more reliable escape?714- print_error(format!(715- "Search path '{}' is not a directory.",716- path.to_string_lossy()717- ));715+ print_error!(716+ "Search path {:?} is not a directory.",717+ path.to_string_lossy().as_ref()718+ );719 None720 }721 })722 .collect())251 unmodified linesmodified:src/error.rs+50 added-2 removed
1-pub fn print_error(msg: impl std::fmt::Display) {2- eprintln!("[fd error]: {msg}");1+use std::fmt::Display;2+use std::io;3+4+use crate::sanitize::write_sanitized;5+6+/// Print an error message using a format string, sanitizing any arguments if necessary7+macro_rules! print_error {8+ ($fmt:literal, $($arg:expr),*) => {9+ eprintln!(concat!("[fd error]: ", $fmt), $($crate::error::SanitizeErr::sanitize($arg)),*)10+ }11 }12+13+/// Trait for specifying how to sanitize a type for error display, if needed.14+pub(crate) trait SanitizeErr {15+ type Sanitized: Display;16+17+ fn sanitize(self) -> Self::Sanitized;18+}19+20+impl SanitizeErr for &str {21+ type Sanitized = Self;22+23+ fn sanitize(self) -> Self {24+ self25+ }26+}27+28+impl SanitizeErr for io::Error {29+ type Sanitized = SanitizedError<io::Error>;30+31+ fn sanitize(self) -> Self::Sanitized {32+ SanitizedError(self)33+ }34+}35+36+impl SanitizeErr for ignore::Error {37+ type Sanitized = SanitizedError<ignore::Error>;38+39+ fn sanitize(self) -> Self::Sanitized {40+ SanitizedError(self)41+ }42+}43+44+pub struct SanitizedError<E>(E);45+46+impl<E: std::error::Error> Display for SanitizedError<E> {47+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {48+ let raw = self.0.to_string();49+ write_sanitized(f, &raw)50+ }51+}modified:src/main.rs+11 added-6 removed
1+// needs to be first because it defines a macro2+#[macro_use]3+mod error;4+5 mod cli;6 mod config;7 mod dir_entry;4-mod error;8 mod exec;9 mod exit_codes;10 mod filesystem;11 mod filetypes;56 unmodified lines68 Ok(exit_code) => {69 exit_code.exit();70 }71 Err(err) => {69- crate::error::print_error(format!("{err:#}"));72+ // NB: we use eprintln directly instead of print_error!() because73+ // we sanitize anyhow errors at the generation site74+ eprintln!("[fd error]: {:#}", err);75 ExitCode::GeneralError.exit();76 }77 }78 }57 unmodified lines136 fn set_working_dir(opts: &Opts) -> Result<()> {137 if let Some(ref base_directory) = opts.base_directory {138 if !filesystem::is_existing_directory(base_directory) {139 return Err(anyhow!(135- "The '--base-directory' path '{}' is not a directory.",136- base_directory.to_string_lossy()140+ "The '--base-directory' path {:?} is not a directory.",141+ base_directory.to_string_lossy().as_ref()142 ));143 }144 env::set_current_dir(base_directory).with_context(|| {145 format!(141- "Could not set '{}' as the current working directory",142- base_directory.to_string_lossy()146+ "Could not set {:?} as the current working directory",147+ base_directory.to_string_lossy().as_ref()148 )149 })?;150 }151 Ok(())409 unmodified linesmodified:src/output.rs+21 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;10+use crate::sanitize::sanitize_for_term;11 12 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14 }65 unmodified lines80 let s = output.to_string_lossy();81 write!(82 stdout,83 "{}",84- maybe_sanitize(&s, config.interactive_terminal)84+ sanitize_for_term(&s, config.interactive_terminal)85 )86 }87 88 // TODO: this function is performance critical and can probably be optimized27 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);121- write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;120+ let safe_parent = sanitize_for_term(&parent_str, config.interactive_terminal);121+ // We explicitly use prefix/suffix instead of paint so that we can use Sanitized122+ write!(123+ stdout,124+ "{}{}{}",125+ style.prefix(),126+ safe_parent,127+ style.suffix()128+ )?;129 }130 131 let style = entry132 .style(ls_colors)133 .map(Style::to_nu_ansi_term_style)134 .unwrap_or_default();128- let safe_basename = maybe_sanitize(&path_str[offset..], config.interactive_terminal);129- write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;135+ let safe_basename = sanitize_for_term(&path_str[offset..], config.interactive_terminal);136+ // We explicitly use prefix/suffix instead of paint so that we can use Sanitized137+ write!(138+ stdout,139+ "{}{}{}",140+ style.prefix(),141+ safe_basename,142+ style.suffix()143+ )?;144 145 print_trailing_slash(146 stdout,147 entry,15 unmodified lines163 let mut path_string = path.to_string_lossy();164 if let Some(ref separator) = config.path_separator {165 *path_string.to_mut() = replace_path_separator(&path_string, separator);166 }153- let safe = maybe_sanitize(&path_string, config.interactive_terminal);167+ let safe = sanitize_for_term(&path_string, config.interactive_terminal);168 write!(stdout, "{safe}")?;169 print_trailing_slash(stdout, entry, config, None)170 }171 25 unmodified linesmodified:src/sanitize.rs+59 added-51 removed
1 //! TTY-output sanitization to prevent terminal escape injection via filenames.2 3-use std::borrow::Cow;4-use std::fmt::Write;3+use std::fmt::{Display, Formatter, Write};4 5 /// True for any char that is neither printable nor permitted whitespace (only HT).6 /// Covers C0/C1/DEL, bidi overrides, zero-width and format chars, and tag chars.7 #[inline]13 unmodified lines21 | '\u{E0000}'..='\u{E007F}' // language tags22 )23 }24 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() {25+/// Write the sanitized contents of `raw` to `f`.26+pub fn write_sanitized(f: &mut std::fmt::Formatter<'_>, raw: &str) -> std::fmt::Result {27+ // Would it be faster to do a pass to see if we don't need an escape and write28+ // the whole string first? Maybe with a faster check just for non-control ASCII?29+ for c in raw.chars() {30 if needs_escape(c) {31 let v = c as u32;32 if v <= 0xFF {37- let _ = write!(out, "\\x{v:02X}");33+ write!(f, "\\x{v:02X}")?;34 } else {39- let _ = write!(out, "\\u{{{v:04X}}}");35+ write!(f, "\\u{{{v:04X}}}")?;36 }37 } else {42- out.push(c);38+ f.write_char(c)?;39 }40 }45- Cow::Owned(out)41+ Ok(())42 }43 44+// TODO: add something to sanitize paths directly instead of as strings.45+46+/// A wrapper type that sanitizes the output to Display47+pub(crate) struct SanitizedStr<'a> {48+ raw: &'a str,49+ /// If true, the content is safe to output without sanitizing,50+ /// either because it is trusted, or because it isn't going to a terminal.51+ is_safe: bool,52+}53+54+impl<'a> Display for SanitizedStr<'a> {55+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {56+ if self.is_safe {57+ // We don't need to sanitize anything, just forward58+ self.raw.fmt(f)59+ } else {60+ write_sanitized(f, self.raw)61+ }62+ }63+}64+65 /// 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)66+pub fn sanitize_for_term(raw: &str, is_terminal: bool) -> SanitizedStr<'_> {67+ SanitizedStr {68+ raw,69+ is_safe: !is_terminal,70 }71 }72 73 #[cfg(test)]74 mod tests {75 use super::*;76 77+ fn sanitize_string(s: &str) -> String {78+ SanitizedStr {79+ raw: s,80+ is_safe: false,81+ }82+ .to_string()83+ }84+85 #[test]86 fn preserves_safe_content() {87 for s in [88 "hello.txt",2 unmodified lines91 "🦀.rs",92 "a\tb",93 "a\u{FFFD}b",94 ] {71- assert!(72- matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),73- "{s:?}"74- );75- assert_eq!(sanitize_for_terminal(s), s);95+ assert_eq!(sanitize_string(s), s);96 }97 }98 99 #[test]100 fn strips_osc52_clipboard_payload() {101 let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";82- let safe = sanitize_for_terminal(attack);102+ let safe = sanitize_string(attack);103 assert!(!safe.contains('\x1b'));104 assert_eq!(safe, "innocent\\x1B]52;c;cHduZWQ=\\x1B\\.txt");105 }106 107 #[test]108 fn strips_cr_output_forgery() {89- assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");109+ assert_eq!(sanitize_string("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");110 }111 112 #[test]113 fn strips_osc8_hyperlink_injection() {114 let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";95- assert!(!sanitize_for_terminal(attack).contains('\x1b'));115+ assert!(!sanitize_string(attack).contains('\x1b'));116 }117 118 #[test]119 fn strips_del() {100- assert_eq!(sanitize_for_terminal("a\x7fb"), "a\\x7Fb");120+ assert_eq!(sanitize_string("a\x7fb"), "a\\x7Fb");121 }122 123 #[test]124 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");125+ assert_eq!(sanitize_string("a\x07b"), "a\\x07b");126+ assert_eq!(sanitize_string("a\0b"), "a\\x00b");127 }128 129 #[test]110- fn strips_newline() {111- assert_eq!(sanitize_for_terminal("a\nb"), "a\\x0Ab");112- }113-114- #[test]130 fn escape_preserves_information() {131 let s = "name\x1bX\x07Y.txt";117- assert_eq!(sanitize_for_terminal(s), "name\\x1BX\\x07Y.txt");132+ assert_eq!(sanitize_string(s), "name\\x1BX\\x07Y.txt");133 }134 135 #[test]136 fn strips_c1_csi_and_osc_initiators() {137 // 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- );138+ assert_eq!(sanitize_string("\u{9b}31m"), "\\x9B31m");139+ assert_eq!(sanitize_string("\u{9d}0;pwned\u{9c}"), "\\x9D0;pwned\\x9C");140 }141 142 #[test]143 fn strips_bidi_overrides_and_zero_width() {144 // Trojan-Source style RLO/LRO that flip rendered order of filename text.145 assert_eq!(134- sanitize_for_terminal("safe\u{202E}fil\u{202D}gnp.exe"),146+ sanitize_string("safe\u{202E}fil\u{202D}gnp.exe"),147 "safe\\u{202E}fil\\u{202D}gnp.exe"148 );149 // 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");150+ assert_eq!(sanitize_string("a\u{200B}b"), "a\\u{200B}b");151+ assert_eq!(sanitize_string("\u{FEFF}name"), "\\u{FEFF}name");152 }153 154 #[test]155 fn keeps_legitimate_unicode_features() {3 unmodified lines159 "heart\u{2764}\u{FE0F}.txt",160 "icon\u{E000}.cfg",161 "cjk\u{6F22}\u{E0101}.txt",162 ] {151- assert!(152- matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),153- "{s:?}"154- );163+ assert_eq!(sanitize_string(s), s);164 }165 }166 167 #[test]168 fn maybe_sanitize_passthrough_when_not_terminal() {169 let attack = "x\x1by";170 // Pipe context: bytes pass through unchanged (zero-copy).162- let out = maybe_sanitize(attack, false);163- assert!(matches!(out, Cow::Borrowed(_)));171+ let out = sanitize_for_term(attack, false).to_string();172 assert_eq!(out, attack);173 // TTY context: escapes apply.166- assert_eq!(maybe_sanitize(attack, true), "x\\x1By");174+ assert_eq!(sanitize_for_term(attack, true).to_string(), "x\\x1By");175 }176 }modified:src/walk.rs+4 added-5 removed
15 unmodified lines16 use regex::bytes::Regex;17 18 use crate::config::Config;19 use crate::dir_entry::DirEntry;20-use crate::error::print_error;20 use crate::exec;21 use crate::exit_codes::{ExitCode, merge_exitcodes};22 use crate::filesystem;23 use crate::output;200 unmodified lines224 }225 }226 WorkerResult::Error(err) => {227 if self.config.show_filesystem_errors {229- print_error(err.to_string());228+ print_error!("{}", err);229 }230 }231 }232 }18 unmodified lines251 fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {252 if let Err(e) = output::print_entry(&mut self.stdout, entry, self.config)253 && e.kind() != ::std::io::ErrorKind::BrokenPipe254 {256- print_error(format!("Could not write to output: {e}"));255+ print_error!("Could not write to output: {}", e);256 return Err(ExitCode::GeneralError);257 }258 259 if self.interrupt_flag.load(Ordering::Relaxed) {115 unmodified lines375 let result = builder.add_ignore(global_ignore_file);376 match result {377 Some(ignore::Error::Partial(_)) => (),378 Some(err) => {380- print_error(format!("Malformed pattern in global ignore file. {err}."));379+ print_error!("Malformed pattern in global ignore file. {}.", err);380 }381 None => (),382 }383 }3 unmodified lines387 let result = builder.add_ignore(ignore_file);388 match result {389 Some(ignore::Error::Partial(_)) => (),390 Some(err) => {392- print_error(format!("Malformed pattern in custom ignore file. {err}."));391+ print_error!("Malformed pattern in custom ignore file. {}.", err);392 }393 None => (),394 }395 }348 unmodified linesmodified:tests/testenv/mod.rs+16 added
194 unmodified lines195 }196 Ok(broken_symlink_link)197 }198 199+ pub fn create_symlink<P: AsRef<Path>>(200+ &mut self,201+ target: P,202+ link_path: P,203+ ) -> io::Result<PathBuf> {204+ let root = self.test_root();205+ let target_path = root.join(target);206+ let link_path = root.join(link_path);207+ #[cfg(unix)]208+ unix::fs::symlink(&target_path, &link_path)?;209+ #[cfg(windows)]210+ windows::fs::symlink_file(&target_path, &link_path)?;211+212+ Ok(link_path)213+ }214+215 /// Get the root directory for the tests.216 pub fn test_root(&self) -> PathBuf {217 self.temp_dir.path().to_path_buf()218 }142 unmodified linesmodified:tests/tests.rs+35 added-5 removed
343 unmodified lines344 te.assert_output(&["a.foo", "real", "fake"], "real/a.foo");345 346 te.assert_error(347 &["a.foo", "real", "fake"],348- "[fd error]: Search path 'fake' is not a directory.",348+ "[fd error]: Search path \"fake\" is not a directory.",349 );350 351 te.assert_output(352 &["", "real", "fake"],8 unmodified lines361 );362 363 te.assert_error(364 &["", "real", "fake1", "fake2"],365- "[fd error]: Search path 'fake1' is not a directory.366- [fd error]: Search path 'fake2' is not a directory.",365+ "[fd error]: Search path \"fake1\" is not a directory.366+ [fd error]: Search path \"fake2\" is not a directory.",367 );368 369 te.assert_failure_with_error(370 &["", "fake1", "fake2"],371- "[fd error]: Search path 'fake1' is not a directory.372- [fd error]: Search path 'fake2' is not a directory.371+ "[fd error]: Search path \"fake1\" is not a directory.372+ [fd error]: Search path \"fake2\" is not a directory.373 [fd error]: No valid search paths given.",374 );375 }376 2509 unmodified lines2886 let te = TestEnv::new(&["include"], &["CACHEDIR.TAG", "top", "include/foo"]);2887 let expected = "";2888 te.assert_output(&["--ignore-contain=CACHEDIR.TAG", "."], expected);2889 }2890+2891+// The error message is probably OS-specific.2892+// This is also somewhat fragile as it depends on the error message2893+// from creating an executable, and the debug formatting of strings2894+// could possibly change in the future.2895+#[cfg(unix)]2896+#[test]2897+fn test_sanitize_exec_error_msg() {2898+ let mut te = TestEnv::new(&[], &[]);2899+ te.create_broken_symlink("Hello\x1b\r World!\x7fwith\u{9b}\u{1F600}\u{200B}a\u{FEFF}b")2900+ .expect("failed to create symlink");2901+2902+ te.assert_error(&["Hello", "--exec", "{}"], 2903+ "[fd error]: Command not found: \"./Hello\\u{1b}\\r World!\\u{7f}with\\u{9b}\u{1F600}\\u{200b}a\\u{feff}b\""2904+ );2905+}2906+2907+// Windows doesn't let us make files containing \x1b so only test on unix2908+#[cfg(unix)]2909+#[test]2910+fn test_sanitize_recursive_link_msg() {2911+ let mut te = TestEnv::new(&["loop"], &[]);2912+ te.create_symlink("loop", "loop/foo\x1bb")2913+ .expect("failed to create symlink");2914+2915+ te.assert_error(2916+ &["--follow", "--show-errors", "foo"],2917+ "[fd error]: File system loop found: ./loop/foo\\x1Bb points to an ancestor ./loop",2918+ );2919+}