Skip to main content

mrk/
sanitize.rs

1//! Text and links made safe to write to a terminal, which interprets the escape sequences an untrusted input can carry.
2use crate::text::expand_tabs;
3
4pub(crate) const MAX_LINK_BYTES: usize = 2048;
5const WEB_SCHEMES: [&str; 3] = ["http", "https", "mailto"];
6/// Each ends on the slash that starts the path, so a `file:` link names no host but this machine.
7const LOCAL_FILE_PREFIXES: [&str; 2] = ["file:///", "file://localhost/"];
8
9/// The text with every character a terminal could interpret or that disguises text removed: C0 and C1 controls, DEL,
10/// bidi marks, overrides and isolates, the zero-width space, the word joiner and the invisible format characters around
11/// it, the byte order mark and tag characters.
12/// A tab becomes spaces, the line and paragraph separators a space.
13pub fn text(raw: &str) -> String {
14    clean(raw, false)
15}
16
17/// `text` for a message of several lines: the newlines are kept.
18pub fn lines(raw: &str) -> String {
19    clean(raw, true)
20}
21
22/// Tabs expand once the rest is removed, so a tab after a dropped newline stops where the joined line puts it.
23fn clean(raw: &str, keeps_newlines: bool) -> String {
24    let is_kept_as_written = |character: char| character == '\t' || (keeps_newlines && character == '\n');
25    let mut kept = String::with_capacity(raw.len());
26    kept.extend(raw.chars().filter_map(|character| if is_kept_as_written(character) { Some(character) } else { printed(character) }));
27    if kept.contains('\t') { expand_tabs(&kept, 0).into_owned() } else { kept }
28}
29
30/// Overrides, isolates and the marks (LRM, RLM, ALM) reorder what a line shows; the zero-width space, the word joiner,
31/// the invisible operators, the deprecated format characters, the Mongolian vowel separator, the interlinear
32/// annotation marks, the musical format characters, the byte order mark and tag characters hide inside a name. The
33/// joiners stay: emoji sequences and Persian or Indic words need them.
34fn is_invisible_control(character: char) -> bool {
35    matches!(
36        character,
37        '\u{202a}'..='\u{202e}'
38            | '\u{2066}'..='\u{2069}'
39            | '\u{200b}'
40            | '\u{200e}'
41            | '\u{200f}'
42            | '\u{061c}'
43            | '\u{2060}'..='\u{2064}'
44            | '\u{206a}'..='\u{206f}'
45            | '\u{180e}'
46            | '\u{fff9}'..='\u{fffb}'
47            | '\u{1d173}'..='\u{1d17a}'
48            | '\u{feff}'
49            | '\u{e0000}'..='\u{e007f}'
50    )
51}
52
53/// The characters a terminal could interpret or that disguise text: C0 and C1 controls, DEL and the invisible controls
54/// above. `sanitize` removes them, so they take no cell.
55pub(crate) fn is_forbidden(character: char) -> bool {
56    character.is_control() || is_invisible_control(character)
57}
58
59/// What `sanitize` writes for `character`: nothing when it is forbidden, a space for the line and paragraph
60/// separators, which would break a line the layout never counted, else the character itself.
61pub(crate) fn printed(character: char) -> Option<char> {
62    match character {
63        _ if is_forbidden(character) => None,
64        '\u{2028}' | '\u{2029}' => Some(' '),
65        _ => Some(character),
66    }
67}
68
69fn percent_encode(raw: &str) -> String {
70    raw.bytes().map(|byte| if byte.is_ascii_graphic() { char::from(byte).to_string() } else { format!("%{byte:02X}") }).collect()
71}
72
73fn percent_decode(raw: &str) -> Vec<u8> {
74    let bytes = raw.as_bytes();
75    let mut decoded = Vec::with_capacity(bytes.len());
76    let mut index = 0;
77    while let Some(&byte) = bytes.get(index) {
78        let escaped = bytes.get(index + 1..index + 3).filter(|_| byte == b'%').and_then(hex_byte);
79        decoded.push(escaped.unwrap_or(byte));
80        index += if escaped.is_some() { 3 } else { 1 };
81    }
82    decoded
83}
84
85fn hex_byte(digits: &[u8]) -> Option<u8> {
86    let digits = std::str::from_utf8(digits).ok().filter(|digits| digits.bytes().all(|digit| digit.is_ascii_hexdigit()))?;
87    u8::from_str_radix(digits, 16).ok()
88}
89
90pub(crate) fn scheme(target: &str) -> Option<&str> {
91    let (scheme, _) = target.split_once(':')?;
92    let starts_with_letter = scheme.starts_with(|character: char| character.is_ascii_alphabetic());
93    let is_valid = starts_with_letter && scheme.chars().all(|character| character.is_ascii_alphanumeric() || "+-.".contains(character));
94    is_valid.then_some(scheme)
95}
96
97/// A `file:` link to another host (`file://host/share`, `file:////host/share`, `file:///\\host\share`) opens an SMB share
98/// on some systems, which sends it the user's credentials.
99fn is_local_file(target: &str) -> bool {
100    let path = LOCAL_FILE_PREFIXES.iter().find_map(|prefix| {
101        let head = target.get(..prefix.len())?;
102        head.eq_ignore_ascii_case(prefix).then(|| &target[prefix.len()..])
103    });
104    path.is_some_and(|path| is_plain_path(&percent_decode(path)))
105}
106
107/// Openers decode the path and resolve `.` and `..` before reading it, so `/a/..//host/share` reaches a share:
108/// decoded once, the path must hold no backslash and only named segments, a trailing slash aside.
109fn is_plain_path(path: &[u8]) -> bool {
110    let mut segments = path.strip_suffix(b"/").unwrap_or(path).split(|&byte| byte == b'/');
111    let has_only_names = path.is_empty() || segments.all(|segment| !matches!(segment, b"" | b"." | b".."));
112    has_only_names && !path.contains(&b'\\')
113}
114
115fn is_allowed(target: &str) -> bool {
116    match scheme(target) {
117        Some(scheme) if scheme.eq_ignore_ascii_case("file") => is_local_file(target),
118        Some(scheme) => WEB_SCHEMES.iter().any(|allowed| scheme.eq_ignore_ascii_case(allowed)),
119        None => false,
120    }
121}
122
123/// The OSC 8 target for a link, or `None` when the link must not be clickable: longer than 2,048 bytes,
124/// with a scheme other than http, https, mailto and file (so relative paths and `javascript:` are dropped),
125/// or a `file:` link to another host.
126pub fn link(raw: &str) -> Option<String> {
127    let target = percent_encode(&text(raw));
128    let is_short = target.len() <= MAX_LINK_BYTES;
129    (is_short && is_allowed(&target)).then_some(target)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn plain_text_is_unchanged() {
138        assert_eq!(text("Hello, wörld 漢字 ✔"), "Hello, wörld 漢字 ✔");
139    }
140
141    #[test]
142    fn escape_and_bell_are_removed() {
143        assert_eq!(text("a\x1bb\x07c"), "abc");
144    }
145
146    #[test]
147    fn a_csi_sequence_loses_its_escape_and_cannot_style() {
148        assert_eq!(text("\x1b[31mred\x1b[0m"), "[31mred[0m");
149    }
150
151    #[test]
152    fn an_osc_52_clipboard_write_is_defused() {
153        let clean = text("\x1b]52;c;ZWNobyBwd25lZA==\x07after");
154
155        assert!(!clean.contains('\x1b') && !clean.contains('\x07'));
156        assert_eq!(clean, "]52;c;ZWNobyBwd25lZA==after");
157    }
158
159    #[test]
160    fn a_retitle_ended_by_string_terminator_is_defused() {
161        assert_eq!(text("\x1b]0;pwned\x1b\\x"), "]0;pwned\\x");
162    }
163
164    #[test]
165    fn c1_controls_are_removed() {
166        assert_eq!(text("a\u{9b}31mb\u{9d}0;t\u{9c}c\u{80}\u{9f}"), "a31mb0;tc");
167    }
168
169    #[test]
170    fn delete_and_other_c0_controls_are_removed() {
171        assert_eq!(text("a\x7fb\x00c\x08d\re\nf\x0bg"), "abcdefg");
172    }
173
174    #[test]
175    fn bidi_overrides_and_isolates_are_removed() {
176        assert_eq!(text("a\u{202a}b\u{202b}c\u{202c}d\u{202d}e\u{202e}f\u{2066}g\u{2067}h\u{2068}i\u{2069}j"), "abcdefghij");
177    }
178
179    #[test]
180    fn bidi_marks_and_the_zero_width_space_are_removed() {
181        assert_eq!(text("a\u{200b}b\u{200e}c\u{200f}d\u{061c}e"), "abcde");
182    }
183
184    #[test]
185    fn invisible_joiners_marks_and_tags_are_removed() {
186        assert_eq!(text("a\u{2060}b\u{feff}c\u{e0001}d\u{e0041}\u{e007f}e"), "abcde");
187    }
188
189    #[test]
190    fn invisible_operators_deprecated_formats_and_musical_formats_are_removed() {
191        let invisible = ["\u{2061}", "\u{2064}", "\u{206a}", "\u{206f}", "\u{180e}", "\u{fff9}", "\u{fffb}", "\u{1d173}", "\u{1d17a}"];
192
193        assert_eq!(text(&format!("rm{}", invisible.concat())), "rm");
194    }
195
196    #[test]
197    fn line_and_paragraph_separators_become_spaces() {
198        assert_eq!(text("a\u{2028}b\u{2029}c"), "a b c");
199    }
200
201    #[test]
202    fn joiners_and_other_format_characters_are_kept() {
203        assert_eq!(text("a\u{200c}b\u{200d}c\u{00ad}d"), "a\u{200c}b\u{200d}c\u{00ad}d");
204    }
205
206    #[test]
207    fn a_tab_becomes_the_spaces_up_to_the_next_tab_stop() {
208        assert_eq!(text("a\tb"), "a   b");
209    }
210
211    #[test]
212    fn lines_keep_their_newlines_and_lose_everything_else() {
213        assert_eq!(lines("a\x1b]0;t\x07\r\nb\u{9b}\n"), "a]0;t\nb\n");
214    }
215
216    #[test]
217    fn web_mail_and_file_links_pass() {
218        for target in ["https://example.com/a?b=c#d", "http://x.y", "mailto:me@example.com", "file:///tmp/a.md", "HTTPS://EXAMPLE.COM"] {
219            assert_eq!(link(target).as_deref(), Some(target), "{target}");
220        }
221    }
222
223    #[test]
224    fn file_links_pass_only_for_this_machine() {
225        for target in ["file:///C:/notes.md", "file://localhost/tmp/a.md", "FILE://LocalHost/tmp/a.md"] {
226            assert_eq!(link(target).as_deref(), Some(target), "{target}");
227        }
228        for target in ["file://evil.host/share/x", "file:////evil.host/share", "file:///\\\\evil.host\\share", "file:/tmp/a.md", "file:"] {
229            assert_eq!(link(target), None, "{target}");
230        }
231    }
232
233    #[test]
234    fn an_encoded_slash_or_backslash_cannot_name_another_host() {
235        for target in ["file:///%5C%5Cevil.host%5Cshare", "file:///%2f%2Fevil.host/x", "file:///tmp/a%5cb"] {
236            assert_eq!(link(target), None, "{target}");
237        }
238    }
239
240    #[test]
241    fn a_dot_or_empty_segment_cannot_climb_to_another_host() {
242        for target in
243            ["file:///.//host/share/x", "file:///%2e%2e//host/share/x", "file:///a/..//host/share/x", "file:///a//b", "file:///a/./b"]
244        {
245            assert_eq!(link(target), None, "{target}");
246        }
247    }
248
249    #[test]
250    fn a_plain_path_with_dots_in_names_or_a_trailing_slash_passes() {
251        for target in ["file:///", "file:///tmp/", "file:///tmp/.config/a.b.md", "file:///tmp/a%20b"] {
252            assert_eq!(link(target).as_deref(), Some(target), "{target}");
253        }
254    }
255
256    #[test]
257    fn a_bad_escape_is_kept_as_written() {
258        assert_eq!(percent_decode("a%zz%4"), b"a%zz%4");
259        assert_eq!(percent_decode("%2e%2E%+1"), b"..%+1");
260    }
261
262    #[test]
263    fn every_tab_becomes_spaces_wherever_it_sits() {
264        assert_eq!(text("\ta\x1b\tb\t"), "    a   b   ");
265        assert_eq!(lines("ab\tc\nabcd\te"), "ab  c\nabcd    e");
266    }
267
268    #[test]
269    fn a_tab_after_a_removed_newline_stops_on_the_joined_line() {
270        assert_eq!(text("a\nb\tc"), "ab  c");
271    }
272
273    #[test]
274    fn javascript_and_unknown_schemes_are_dropped() {
275        for target in ["javascript:alert(1)", "JavaScript:alert(1)", "data:text/html,x", "vbscript:x", "ssh://host", "x-man-page://ls"] {
276            assert_eq!(link(target), None, "{target}");
277        }
278    }
279
280    #[test]
281    fn links_without_a_scheme_are_dropped() {
282        for target in ["docs/readme.md", "#section", "//example.com", "", ":nothing", "1http://x"] {
283            assert_eq!(link(target), None, "{target:?}");
284        }
285    }
286
287    #[test]
288    fn a_leading_space_does_not_smuggle_a_scheme() {
289        assert_eq!(link(" javascript:alert(1)"), None);
290    }
291
292    #[test]
293    fn a_link_cannot_close_the_hyperlink_or_inject_a_sequence() {
294        assert_eq!(link("https://x.y/\x1b\\\x1b]52;c;AAAA\x07").as_deref(), Some("https://x.y/\\]52;c;AAAA"));
295    }
296
297    #[test]
298    fn spaces_and_non_ascii_are_percent_encoded() {
299        assert_eq!(link("https://x.y/a b/é").as_deref(), Some("https://x.y/a%20b/%C3%A9"));
300    }
301
302    #[test]
303    fn a_link_at_the_cap_passes_and_one_byte_over_is_dropped() {
304        let prefix = "https://x.y/";
305        let at_cap = format!("{prefix}{}", "a".repeat(MAX_LINK_BYTES - prefix.len()));
306        let over_cap = format!("{at_cap}a");
307
308        assert_eq!(link(&at_cap).as_deref(), Some(at_cap.as_str()));
309        assert_eq!(link(&over_cap), None);
310    }
311
312    #[test]
313    fn percent_encoding_counts_toward_the_cap() {
314        let long = format!("https://x.y/{}", "é".repeat(400));
315
316        assert_eq!(link(&long), None);
317    }
318}