Skip to main content

rtci_sdp/attribute/
security.rs

1//! `a=fingerprint` (RFC 8122), `a=setup` (RFC 4145), `a=tls-id` (RFC 8842) and
2//! `a=identity` (RFC 8827).
3
4use std::fmt;
5
6use shared::error::Result;
7
8use super::{TypedAttribute, string_attribute};
9use crate::grammar::{self, invalid, syntax};
10use crate::util::ConnectionRole;
11
12/// `a=fingerprint:<hash-func> <fingerprint>` (RFC 8122 section 5).
13///
14/// ```text
15/// fingerprint-attribute = "fingerprint" ":" hash-func SP fingerprint
16/// hash-func             = "sha-1" / "sha-224" / "sha-256" / "sha-384" / "sha-512"
17///                       / "md5" / "md2" / token
18/// fingerprint           = 2UHEX *(":" 2UHEX)
19/// ```
20///
21/// Two things are wider or narrower than that grammar. Lower-case hexadecimal digits are
22/// accepted (`UHEX` is upper case only, and some endpoints write lower case); compare
23/// fingerprints by [`Fingerprint::bytes`], not as text. And for the hash functions the
24/// grammar names, the fingerprint must have the length of that hash: a `sha-256`
25/// fingerprint that is not 32 bytes cannot match any certificate.
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub struct Fingerprint {
28    /// The hash function, as written. RFC 8122 writes them in lower case; compare without
29    /// regard to case.
30    pub hash_function: String,
31    /// The digest.
32    pub bytes: Vec<u8>,
33}
34
35impl Fingerprint {
36    /// The digest length of a hash function the RFC 8122 grammar names.
37    fn digest_len(hash_function: &str) -> Option<usize> {
38        Some(match hash_function.to_ascii_lowercase().as_str() {
39            "md2" | "md5" => 16,
40            "sha-1" => 20,
41            "sha-224" => 28,
42            "sha-256" => 32,
43            "sha-384" => 48,
44            "sha-512" => 64,
45            _ => return None,
46        })
47    }
48}
49
50impl TypedAttribute for Fingerprint {
51    const NAME: &'static str = "fingerprint";
52
53    fn parse(value: &str) -> Result<Self> {
54        let Some((hash_function, fingerprint)) = value.split_once(' ') else {
55            return Err(syntax("a=fingerprint", value));
56        };
57        if !grammar::is_token(hash_function) {
58            return Err(syntax("a=fingerprint", value));
59        }
60        let mut bytes = Vec::with_capacity(fingerprint.len() / 3 + 1);
61        for pair in fingerprint.split(':') {
62            match pair.as_bytes() {
63                [high, low] if high.is_ascii_hexdigit() && low.is_ascii_hexdigit() => {
64                    let digit = |b: u8| (b as char).to_digit(16).unwrap_or(0) as u8;
65                    bytes.push(digit(*high) << 4 | digit(*low));
66                }
67                _ => return Err(syntax("a=fingerprint", value)),
68            }
69        }
70        if Self::digest_len(hash_function).is_some_and(|len| len != bytes.len()) {
71            return Err(invalid("a=fingerprint length", value));
72        }
73        Ok(Fingerprint {
74            hash_function: hash_function.to_owned(),
75            bytes,
76        })
77    }
78}
79
80impl fmt::Display for Fingerprint {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "{} ", self.hash_function)?;
83        for (i, byte) in self.bytes.iter().enumerate() {
84            if i > 0 {
85                f.write_str(":")?;
86            }
87            write!(f, "{byte:02X}")?;
88        }
89        Ok(())
90    }
91}
92
93/// `a=setup:<role>` (RFC 4145 section 4): `active`, `passive`, `actpass` or `holdconn`.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct Setup(pub ConnectionRole);
96
97impl TypedAttribute for Setup {
98    const NAME: &'static str = "setup";
99
100    fn parse(value: &str) -> Result<Self> {
101        match ConnectionRole::from(value) {
102            ConnectionRole::Unspecified => Err(syntax("a=setup", value)),
103            role => Ok(Setup(role)),
104        }
105    }
106}
107
108impl fmt::Display for Setup {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "{}", self.0)
111    }
112}
113
114string_attribute!(
115    /// `a=tls-id:<id>` (RFC 8842 section 4): `20*255(tls-id-char)`,
116    /// `tls-id-char = ALPHA / DIGIT / "+" / "/" / "-" / "_"`.
117    TlsId,
118    "tls-id",
119    "a=tls-id",
120    |v| (20..=255).contains(&v.len())
121        && v.bytes()
122            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'-' | b'_'))
123);
124
125/// `a=identity:<assertion> *(SP <extension>)` (RFC 8827 section 5).
126///
127/// ```text
128/// identity-assertion       = identity-assertion-value *(SP identity-extension)
129/// identity-assertion-value = base64
130/// identity-extension       = extension-name [ "=" extension-value ]
131/// extension-name           = token
132/// extension-value          = 1*(%x01-09 / %x0b-0c / %x0e-3a / %x3c-ff)
133/// ```
134///
135/// This is the syntax only: the engine does not implement identity providers.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Identity {
138    /// The assertion, base64 text as written (it decodes to a JSON object).
139    pub assertion: String,
140    /// The extensions, as `(name, value)`, in order.
141    pub extensions: Vec<(String, Option<String>)>,
142}
143
144impl TypedAttribute for Identity {
145    const NAME: &'static str = "identity";
146
147    fn parse(value: &str) -> Result<Self> {
148        let mut fields = grammar::fields("a=identity", value)?.into_iter();
149        let assertion = fields.next().unwrap_or_default();
150        if !grammar::is_base64(assertion) {
151            return Err(syntax("a=identity", "(assertion)"));
152        }
153        let mut extensions = Vec::new();
154        for extension in fields {
155            let (name, extension_value) = match extension.split_once('=') {
156                Some((name, v)) => (name, Some(v)),
157                None => (extension, None),
158            };
159            if !grammar::is_token(name)
160                || !extension_value.is_none_or(|v| !v.is_empty() && !v.contains(';'))
161            {
162                return Err(syntax("a=identity extension", extension));
163            }
164            extensions.push((name.to_owned(), extension_value.map(str::to_owned)));
165        }
166        Ok(Identity {
167            assertion: assertion.to_owned(),
168            extensions,
169        })
170    }
171}
172
173impl fmt::Display for Identity {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.write_str(&self.assertion)?;
176        for (name, value) in &self.extensions {
177            write!(f, " {name}")?;
178            if let Some(value) = value {
179                write!(f, "={value}")?;
180            }
181        }
182        Ok(())
183    }
184}