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

1//! TTY-output sanitization to prevent terminal escape injection via filenames.23use std::fmt::{Display, Formatter, Write};45/// 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}2425/// 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() {30        if needs_escape(c) {31            let v = c as u32;32            if v <= 0xFF {33                write!(f, "\\x{v:02X}")?;34            } else {35                write!(f, "\\u{{{v:04X}}}")?;36            }37        } else {38            f.write_char(c)?;39        }40    }41    Ok(())42}4344// 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}6465/// Sanitize for terminal output only; raw bytes pass through on pipes/files.66pub fn sanitize_for_term(raw: &str, is_terminal: bool) -> SanitizedStr<'_> {67    SanitizedStr {68        raw,69        is_safe: !is_terminal,70    }71}7273#[cfg(test)]74mod tests {75    use super::*;7677    fn sanitize_string(s: &str) -> String {78        SanitizedStr {79            raw: s,80            is_safe: false,81        }82        .to_string()83    }8485    #[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        ] {95            assert_eq!(sanitize_string(s), s);96        }97    }9899    #[test]100    fn strips_osc52_clipboard_payload() {101        let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";102        let safe = sanitize_string(attack);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() {109        assert_eq!(sanitize_string("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");110    }111112    #[test]113    fn strips_osc8_hyperlink_injection() {114        let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";115        assert!(!sanitize_string(attack).contains('\x1b'));116    }117118    #[test]119    fn strips_del() {120        assert_eq!(sanitize_string("a\x7fb"), "a\\x7Fb");121    }122123    #[test]124    fn strips_bel_and_null() {125        assert_eq!(sanitize_string("a\x07b"), "a\\x07b");126        assert_eq!(sanitize_string("a\0b"), "a\\x00b");127    }128129    #[test]130    fn escape_preserves_information() {131        let s = "name\x1bX\x07Y.txt";132        assert_eq!(sanitize_string(s), "name\\x1BX\\x07Y.txt");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.138        assert_eq!(sanitize_string("\u{9b}31m"), "\\x9B31m");139        assert_eq!(sanitize_string("\u{9d}0;pwned\u{9c}"), "\\x9D0;pwned\\x9C");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!(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.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    }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        ] {163            assert_eq!(sanitize_string(s), s);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).171        let out = sanitize_for_term(attack, false).to_string();172        assert_eq!(out, attack);173        // TTY context: escapes apply.174        assert_eq!(sanitize_for_term(attack, true).to_string(), "x\\x1By");175    }176}