Skip to main content

rtci_stun/
nonce_cookie.rs

1//! The nonce cookie and the STUN Security Features it carries (RFC 8489 sections 9.2, 9.2.1
2//! and 18.1).
3//!
4//! A server that implements RFC 8489 starts every NONCE with `obMatJos2` followed by the
5//! base64 encoding of 24 feature bits. The NONCE is covered by the message integrity of the
6//! client's next request, so an attacker on the path cannot strip a feature (drop
7//! PASSWORD-ALGORITHMS to force MD5, say) without the client seeing that the cookie promised
8//! it: that is the bid-down protection, applied by
9//! [`LongTermCredentials`](crate::long_term::LongTermCredentials).
10
11use base64::prelude::*;
12
13/// What a nonce that carries the cookie starts with.
14pub const NONCE_COOKIE_PREFIX: &str = "obMatJos2";
15/// The length of the nonce cookie: the prefix and four base64 characters.
16pub const NONCE_COOKIE_LEN: usize = 13;
17
18/// The 24 STUN Security Feature bits of a nonce cookie.
19///
20/// The three bytes are one 24-bit number in network order, and the features are numbered
21/// from its least significant end: RFC 8489 section 18.1 as corrected by its verified erratum
22/// 6290 ("Bit 0 is the rightmost bit"). The nonce of the RFC's own test vector (appendix
23/// B.1), `obMatJos2AAAC...`, is `0x000002`: bit 1, username anonymity, and the vector duly
24/// carries USERHASH.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
26pub struct SecurityFeatures(u32);
27
28impl SecurityFeatures {
29    /// No feature.
30    pub const NONE: Self = Self(0);
31    /// Bit 0, "Password algorithms": the server sends PASSWORD-ALGORITHMS.
32    pub const PASSWORD_ALGORITHMS: Self = Self(1);
33    /// Bit 1, "Username anonymity": the client sends USERHASH in place of USERNAME.
34    pub const USERNAME_ANONYMITY: Self = Self(1 << 1);
35
36    /// The features of the cookie `nonce` starts with, or `None` when it does not start with a
37    /// nonce cookie (a server that predates RFC 8489).
38    #[must_use]
39    pub fn from_nonce(nonce: &str) -> Option<Self> {
40        let encoded = nonce
41            .strip_prefix(NONCE_COOKIE_PREFIX)?
42            .as_bytes()
43            .get(..NONCE_COOKIE_LEN - NONCE_COOKIE_PREFIX.len())?;
44        let bits = BASE64_STANDARD.decode(encoded).ok()?;
45        let bits: [u8; 3] = bits.try_into().ok()?;
46        Some(Self(u32::from_be_bytes([0, bits[0], bits[1], bits[2]])))
47    }
48
49    /// These features and those of `other`.
50    #[must_use]
51    pub const fn with(self, other: Self) -> Self {
52        Self(self.0 | other.0)
53    }
54
55    /// Whether every feature of `other` is set.
56    #[must_use]
57    pub const fn contains(self, other: Self) -> bool {
58        self.0 & other.0 == other.0
59    }
60
61    /// Whether the "Password algorithms" bit is set.
62    #[must_use]
63    pub const fn password_algorithms(self) -> bool {
64        self.contains(Self::PASSWORD_ALGORITHMS)
65    }
66
67    /// Whether the "Username anonymity" bit is set.
68    #[must_use]
69    pub const fn username_anonymity(self) -> bool {
70        self.contains(Self::USERNAME_ANONYMITY)
71    }
72
73    /// The 24 bits as a number: feature bit N of the registry is `1 << N`.
74    #[must_use]
75    pub const fn bits(self) -> u32 {
76        self.0
77    }
78
79    /// The nonce cookie for these features: what a server puts ahead of its own nonce value.
80    #[must_use]
81    pub fn cookie(self) -> String {
82        let bytes = self.0.to_be_bytes();
83        format!(
84            "{NONCE_COOKIE_PREFIX}{}",
85            BASE64_STANDARD.encode(&bytes[1..])
86        )
87    }
88}
89
90#[cfg(test)]
91mod nonce_cookie_test {
92    use super::*;
93
94    /// RFC 8489 section 9.2: the cookie is "obMatJos2" and the base64 of the three feature
95    /// bytes; section 18.1 with erratum 6290: password algorithms is bit 0, username anonymity
96    /// bit 1, counted from the least significant end.
97    #[test]
98    fn test_security_features_are_read_from_the_nonce_cookie() {
99        // 0x00 0x00 0x01 is "AAAB", 0x00 0x00 0x02 is "AAAC", 0x00 0x00 0x03 is "AAAD".
100        let password = SecurityFeatures::from_nonce("obMatJos2AAABserver-part").unwrap();
101        assert!(password.password_algorithms() && !password.username_anonymity());
102        // The nonce of RFC 8489 appendix B.1, whose request carries USERHASH.
103        let anonymity =
104            SecurityFeatures::from_nonce("obMatJos2AAACf//499k954d6OL34oL9FSTvy64sA").unwrap();
105        assert!(!anonymity.password_algorithms() && anonymity.username_anonymity());
106        let both = SecurityFeatures::from_nonce("obMatJos2AAAD").unwrap();
107        assert!(both.password_algorithms() && both.username_anonymity());
108        // An unassigned bit is neither.
109        let other = SecurityFeatures::from_nonce("obMatJos2gAAAserver-part").unwrap();
110        assert!(!other.password_algorithms() && !other.username_anonymity());
111        assert_eq!(other.bits(), 0x80_0000);
112        let none = SecurityFeatures::from_nonce("obMatJos2AAAAf//499k954d6OL34oL9FSTvy64sA");
113        assert_eq!(none, Some(SecurityFeatures::NONE));
114
115        assert_eq!(
116            SecurityFeatures::PASSWORD_ALGORITHMS.cookie(),
117            "obMatJos2AAAB"
118        );
119        assert_eq!(
120            SecurityFeatures::PASSWORD_ALGORITHMS
121                .with(SecurityFeatures::USERNAME_ANONYMITY)
122                .cookie(),
123            "obMatJos2AAAD"
124        );
125        assert_eq!(SecurityFeatures::NONE.cookie().len(), NONCE_COOKIE_LEN);
126    }
127
128    /// A nonce of a server that predates RFC 8489 has no cookie, whatever it looks like.
129    #[test]
130    fn test_a_nonce_without_the_cookie_has_no_security_features() {
131        for nonce in [
132            "",
133            "f//499k954d6OL34oL9FSTvy64sA",
134            "obMatJos2",
135            "obMatJos2AAA",
136            "obMatJos2A*ABxyz",
137            "xobMatJos2AAAB",
138        ] {
139            assert_eq!(SecurityFeatures::from_nonce(nonce), None, "{nonce:?}");
140        }
141    }
142}