Skip to content
Myr

sanitize.rs

This file

Path

src/sanitize.rs

176 lines · 5.5 KiB · Rust

Last changed by

fix: Better sanitizingThayne McCombsbefore adoption24198d9

History of this file

Take it

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 1–2why, one step back
1//! TTY-output sanitization to prevent terminal escape injection via filenames.
2

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 3why, one step back
3use std::fmt::{Display, Formatter, Write};

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 4–24why, one step back
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]8fn needs_escape(c: char) -> bool {9 if c == '\t' {10 return false;11 }12 c.is_control()13 || matches!(c,14 '\u{00AD}' // soft hyphen (invisible)15 | '\u{180E}' // Mongolian vowel separator16 | '\u{200B}'..='\u{200F}' // zero-width + LRM/RLM17 | '\u{202A}'..='\u{202E}' // bidi embedding/override18 | '\u{2060}'..='\u{206F}' // word joiner, invisibles, deprecated formats19 | '\u{FEFF}' // BOM / zero-width no-break space20 | '\u{FFF9}'..='\u{FFFB}' // interlinear annotation21 | '\u{E0000}'..='\u{E007F}' // language tags22 )23}24

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 25–29why, one step back
25/// Write the sanitized contents of `raw` to `f`.
26pub 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() {

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 30–32why, one step back
30 if needs_escape(c) {
31 let v = c as u32;32 if v <= 0xFF {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 33why, one step back
33 write!(f, "\\x{v:02X}")?;

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

line 34why, one step back
34 } else {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 35why, one step back
35 write!(f, "\\u{{{v:04X}}}")?;

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 36–37why, one step back
36 }
37 } else {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 38why, one step back
38 f.write_char(c)?;

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 39–40why, one step back
39 }
40 }

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 41why, one step back
41 Ok(())

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 42–43why, one step back
42}
43

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 44–64why, one step back
44// TODO: add something to sanitize paths directly instead of as strings.
4546/// A wrapper type that sanitizes the output to Display47pub(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}5354impl<'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

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

line 65why, one step back
65/// Sanitize for terminal output only; raw bytes pass through on pipes/files.

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 66–69why, one step back
66pub fn sanitize_for_term(raw: &str, is_terminal: bool) -> SanitizedStr<'_> {
67 SanitizedStr {68 raw,69 is_safe: !is_terminal,

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 70–76why, one step back
70 }
71}7273#[cfg(test)]74mod tests {75 use super::*;76

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 77–84why, one step back
77 fn sanitize_string(s: &str) -> String {
78 SanitizedStr {79 raw: s,80 is_safe: false,81 }82 .to_string()83 }84

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 85–94why, one step back
85 #[test]
86 fn preserves_safe_content() {87 for s in [88 "hello.txt",89 "résumé.pdf",90 "文档.txt",91 "🦀.rs",92 "a\tb",93 "a\u{FFFD}b",94 ] {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 95why, one step back
95 assert_eq!(sanitize_string(s), s);

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 96–101why, one step back
96 }
97 }9899 #[test]100 fn strips_osc52_clipboard_payload() {101 let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 102why, one step back
102 let safe = sanitize_string(attack);

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 103–108why, one step back
103 assert!(!safe.contains('\x1b'));
104 assert_eq!(safe, "innocent\\x1B]52;c;cHduZWQ=\\x1B\\.txt");105 }106107 #[test]108 fn strips_cr_output_forgery() {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 109why, one step back
109 assert_eq!(sanitize_string("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 110–114why, one step back
110 }
111112 #[test]113 fn strips_osc8_hyperlink_injection() {114 let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 115why, one step back
115 assert!(!sanitize_string(attack).contains('\x1b'));

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 116–119why, one step back
116 }
117118 #[test]119 fn strips_del() {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 120why, one step back
120 assert_eq!(sanitize_string("a\x7fb"), "a\\x7Fb");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 121–124why, one step back
121 }
122123 #[test]124 fn strips_bel_and_null() {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 125–126why, one step back
125 assert_eq!(sanitize_string("a\x07b"), "a\\x07b");
126 assert_eq!(sanitize_string("a\0b"), "a\\x00b");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 127–131why, one step back
127 }
128129 #[test]130 fn escape_preserves_information() {131 let s = "name\x1bX\x07Y.txt";

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 132why, one step back
132 assert_eq!(sanitize_string(s), "name\\x1BX\\x07Y.txt");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 133–137why, one step back
133 }
134135 #[test]136 fn strips_c1_csi_and_osc_initiators() {137 // U+009B is CSI, U+009D is OSC; dangerous on 8-bit-control terminals.

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 138–139why, one step back
138 assert_eq!(sanitize_string("\u{9b}31m"), "\\x9B31m");
139 assert_eq!(sanitize_string("\u{9d}0;pwned\u{9c}"), "\\x9D0;pwned\\x9C");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 140–145why, one step back
140 }
141142 #[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!(

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 146why, one step back
146 sanitize_string("safe\u{202E}fil\u{202D}gnp.exe"),

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 147–149why, one step back
147 "safe\\u{202E}fil\\u{202D}gnp.exe"
148 );149 // Zero-width space and BOM are also format chars used to disguise filenames.

fix: Better sanitizingThayne McCombsbefore adoption24198d9

lines 150–151why, one step back
150 assert_eq!(sanitize_string("a\u{200B}b"), "a\\u{200B}b");
151 assert_eq!(sanitize_string("\u{FEFF}name"), "\\u{FEFF}name");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 152–162why, one step back
152 }
153154 #[test]155 fn keeps_legitimate_unicode_features() {156 // Variation selectors (U+FE0F, U+E0100..) modify preceding glyphs in CJK/emoji157 // and are legitimate in filenames. Private-use chars are used by icon fonts.158 for s in [159 "heart\u{2764}\u{FE0F}.txt",160 "icon\u{E000}.cfg",161 "cjk\u{6F22}\u{E0101}.txt",162 ] {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 163why, one step back
163 assert_eq!(sanitize_string(s), s);

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 164–170why, one step back
164 }
165 }166167 #[test]168 fn maybe_sanitize_passthrough_when_not_terminal() {169 let attack = "x\x1by";170 // Pipe context: bytes pass through unchanged (zero-copy).

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 171why, one step back
171 let out = sanitize_for_term(attack, false).to_string();

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 172–173why, one step back
172 assert_eq!(out, attack);
173 // TTY context: escapes apply.

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 174why, one step back
174 assert_eq!(sanitize_for_term(attack, true).to_string(), "x\\x1By");

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

lines 175–176why, one step back
175 }
176}