Debian Codegraph @

src/output/sanitize.rs

raw
1 //! Safely displays various data types from untrusted sources.
2
3 use std::fmt;
4
5 use sequoia_openpgp::{
6 packet::{
7 UserID,
8 signature::subpacket::NotationData,
9 },
10 };
11
12 /// Safely displays values.
13 ///
14 /// This type MUST be used to display attacker controlled strings,
15 /// such as:
16 ///
17 /// - user IDs
18 /// - literal data's file name
19 /// - regular expressions
20 /// - notation data, both name and value
21 /// - preferred key server
22 /// - policy URI
23 /// - signer's user ID
24 /// - reason for revocation
25 pub struct Safe<T>(pub T);
26
27 impl fmt::Display for Safe<&UserID> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 Safe(self.0.value()).fmt(f)
30 }
31 }
32
33 impl fmt::Display for Safe<&str> {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 // XXX: Better detect dodgy strings and better sanitize them.
36 // I bet there is a crate for that. For now, this is better
37 // than the status quo, and it encodes intent.
38 if self.0.chars().any(char::is_control) {
39 write!(f, "{:?}", self.0)
40 } else {
41 write!(f, "{}", self.0)
42 }
43 }
44 }
45
46 impl fmt::Display for Safe<&[u8]> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 Safe(String::from_utf8_lossy(&self.0[..])).fmt(f)
49 }
50 }
51
52 impl fmt::Display for Safe<&Vec<u8>> {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 Safe(self.0.as_slice()).fmt(f)
55 }
56 }
57
58 impl fmt::Display for Safe<std::borrow::Cow<'_, str>> {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 Safe(&self.0[..]).fmt(f)
61 }
62 }
63
64 impl fmt::Display for Safe<&String> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 Safe(&self.0[..]).fmt(f)
67 }
68 }
69
70 impl fmt::Display for Safe<String> {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 Safe(&self.0[..]).fmt(f)
73 }
74 }
75
76 impl fmt::Display for Safe<&NotationData> {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{}: {}", Safe(self.0.name()), Safe(self.0.value()))
79 }
80 }