Skip to main content

rtci_stun/
password_algorithm.rs

1//! `PASSWORD-ALGORITHM` and `PASSWORD-ALGORITHMS` (RFC 8489 sections 14.11 and 14.12): the
2//! algorithm that turns a long-term password into the HMAC key, and the list a server offers.
3
4use crate::attributes::*;
5use crate::message::*;
6use shared::error::*;
7
8use std::fmt;
9
10/// MD5, the key of RFC 5389 (RFC 8489 section 18.5.1.1): for legacy systems only.
11pub const PASSWORD_ALGORITHM_MD5: u16 = 0x0001;
12/// SHA-256 (RFC 8489 section 18.5.1.2).
13pub const PASSWORD_ALGORITHM_SHA256: u16 = 0x0002;
14
15/// One entry of the STUN Password Algorithms registry with its parameters: the value of
16/// `PASSWORD-ALGORITHM`, and an element of `PASSWORD-ALGORITHMS`.
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
18pub struct PasswordAlgorithm {
19    /// The algorithm number ([`PASSWORD_ALGORITHM_MD5`], [`PASSWORD_ALGORITHM_SHA256`]).
20    pub algorithm: u16,
21    /// The algorithm's parameters; empty for MD5 and SHA-256.
22    pub parameters: Vec<u8>,
23}
24
25impl PasswordAlgorithm {
26    /// An algorithm without parameters.
27    #[must_use]
28    pub const fn new(algorithm: u16) -> Self {
29        Self {
30            algorithm,
31            parameters: Vec::new(),
32        }
33    }
34
35    /// Appends the algorithm number, the parameters' length and the parameters, zero-padded to
36    /// a 32-bit boundary.
37    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
38        let length =
39            u16::try_from(self.parameters.len()).map_err(|_| Error::ErrAttributeSizeOverflow)?;
40        out.extend_from_slice(&self.algorithm.to_be_bytes());
41        out.extend_from_slice(&length.to_be_bytes());
42        out.extend_from_slice(&self.parameters);
43        out.resize(
44            out.len() + nearest_padded_value_length(self.parameters.len()) - self.parameters.len(),
45            0,
46        );
47        Ok(())
48    }
49
50    /// Reads one algorithm from the front of `v`; returns it and the bytes it took, padding
51    /// included. The padding's content is ignored, and the last algorithm of a value may come
52    /// without it.
53    fn decode(v: &[u8]) -> Result<(Self, usize)> {
54        if v.len() < 4 {
55            return Err(Error::ErrUnexpectedEof);
56        }
57        let algorithm = u16::from_be_bytes([v[0], v[1]]);
58        let length = usize::from(u16::from_be_bytes([v[2], v[3]]));
59        let parameters = v.get(4..4 + length).ok_or(Error::ErrUnexpectedEof)?;
60        let taken = (4 + nearest_padded_value_length(length)).min(v.len());
61        Ok((
62            Self {
63                algorithm,
64                parameters: parameters.to_vec(),
65            },
66            taken,
67        ))
68    }
69}
70
71impl fmt::Display for PasswordAlgorithm {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self.algorithm {
74            PASSWORD_ALGORITHM_MD5 => write!(f, "MD5"),
75            PASSWORD_ALGORITHM_SHA256 => write!(f, "SHA-256"),
76            other => write!(f, "{other:#06x}"),
77        }
78    }
79}
80
81impl Setter for PasswordAlgorithm {
82    /// Adds PASSWORD-ALGORITHM to `m`.
83    fn add_to(&self, m: &mut Message) -> Result<()> {
84        let mut value = Vec::with_capacity(4 + self.parameters.len());
85        self.encode(&mut value)?;
86        m.add(ATTR_PASSWORD_ALGORITHM, &value);
87        Ok(())
88    }
89}
90
91impl Getter for PasswordAlgorithm {
92    /// Reads PASSWORD-ALGORITHM from `m`.
93    fn get_from(&mut self, m: &Message) -> Result<()> {
94        let v = m.get(ATTR_PASSWORD_ALGORITHM)?;
95        let (algorithm, taken) = Self::decode(&v)?;
96        if taken != v.len() {
97            return Err(Error::ErrAttributeSizeInvalid);
98        }
99        *self = algorithm;
100        Ok(())
101    }
102}
103
104/// The `PASSWORD-ALGORITHMS` attribute: the algorithms a server can derive the long-term key
105/// with, in its order of preference.
106#[derive(Debug, Clone, PartialEq, Eq, Default)]
107pub struct PasswordAlgorithms(pub Vec<PasswordAlgorithm>);
108
109impl PasswordAlgorithms {
110    /// The first algorithm of the list whose number is in `supported` (RFC 8489 section
111    /// 9.2.5: "the first algorithm supported on the list"), with the parameters the server
112    /// gave it.
113    #[must_use]
114    pub fn first_supported(&self, supported: &[u16]) -> Option<&PasswordAlgorithm> {
115        self.0.iter().find(|a| supported.contains(&a.algorithm))
116    }
117}
118
119impl Setter for PasswordAlgorithms {
120    /// Adds PASSWORD-ALGORITHMS to `m`.
121    fn add_to(&self, m: &mut Message) -> Result<()> {
122        let mut value = Vec::with_capacity(4 * self.0.len());
123        for algorithm in &self.0 {
124            algorithm.encode(&mut value)?;
125        }
126        m.add(ATTR_PASSWORD_ALGORITHMS, &value);
127        Ok(())
128    }
129}
130
131impl Getter for PasswordAlgorithms {
132    /// Reads PASSWORD-ALGORITHMS from `m`.
133    fn get_from(&mut self, m: &Message) -> Result<()> {
134        let v = m.get(ATTR_PASSWORD_ALGORITHMS)?;
135        let mut algorithms = vec![];
136        let mut rest = &v[..];
137        while !rest.is_empty() {
138            let (algorithm, taken) = PasswordAlgorithm::decode(rest)?;
139            algorithms.push(algorithm);
140            rest = &rest[taken..];
141        }
142        self.0 = algorithms;
143        Ok(())
144    }
145}
146
147#[cfg(test)]
148mod password_algorithm_test {
149    use super::*;
150
151    fn message_with(t: AttrType, value: &[u8]) -> Message {
152        let mut m = Message::new();
153        m.write_header();
154        m.add(t, value);
155        m
156    }
157
158    /// RFC 8489 section 14.12, Figure 9: algorithm number, parameters length, parameters
159    /// padded with zeros to a 32-bit boundary.
160    #[test]
161    fn test_password_algorithm_is_number_length_and_padded_parameters() -> Result<()> {
162        let mut m = Message::new();
163        m.write_header();
164        PasswordAlgorithm::new(PASSWORD_ALGORITHM_SHA256).add_to(&mut m)?;
165        assert_eq!(m.get(ATTR_PASSWORD_ALGORITHM)?, [0x00, 0x02, 0x00, 0x00]);
166
167        let with_parameters = PasswordAlgorithm {
168            algorithm: 0x8001,
169            parameters: vec![1, 2, 3, 4, 5],
170        };
171        let mut m = Message::new();
172        m.write_header();
173        with_parameters.add_to(&mut m)?;
174        assert_eq!(
175            m.get(ATTR_PASSWORD_ALGORITHM)?,
176            [0x80, 0x01, 0x00, 0x05, 1, 2, 3, 4, 5, 0, 0, 0]
177        );
178        let mut got = PasswordAlgorithm::default();
179        got.get_from(&m)?;
180        assert_eq!(got, with_parameters);
181        Ok(())
182    }
183
184    /// RFC 8489 section 14.12: the padding bits are ignored by the receiver.
185    #[test]
186    fn test_password_algorithm_padding_is_ignored_on_receipt() -> Result<()> {
187        let m = message_with(
188            ATTR_PASSWORD_ALGORITHM,
189            &[0x80, 0x01, 0x00, 0x01, 9, 0xff, 0xff, 0xff],
190        );
191        let mut got = PasswordAlgorithm::default();
192        got.get_from(&m)?;
193        assert_eq!(got.algorithm, 0x8001);
194        assert_eq!(got.parameters, [9]);
195        Ok(())
196    }
197
198    /// RFC 8489 section 14.11, Figure 8: the list is the algorithms one after another, each
199    /// padded.
200    #[test]
201    fn test_password_algorithms_is_a_list_in_the_servers_order() -> Result<()> {
202        let list = PasswordAlgorithms(vec![
203            PasswordAlgorithm {
204                algorithm: 0x8001,
205                parameters: vec![7, 7],
206            },
207            PasswordAlgorithm::new(PASSWORD_ALGORITHM_SHA256),
208            PasswordAlgorithm::new(PASSWORD_ALGORITHM_MD5),
209        ]);
210        let mut m = Message::new();
211        m.write_header();
212        list.add_to(&mut m)?;
213        assert_eq!(
214            m.get(ATTR_PASSWORD_ALGORITHMS)?,
215            [
216                0x80, 0x01, 0x00, 0x02, 7, 7, 0, 0, // an algorithm with two parameter bytes
217                0x00, 0x02, 0x00, 0x00, // SHA-256
218                0x00, 0x01, 0x00, 0x00, // MD5
219            ]
220        );
221        let mut got = PasswordAlgorithms::default();
222        got.get_from(&m)?;
223        assert_eq!(got, list);
224        assert_eq!(
225            got.first_supported(&[PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256]),
226            Some(&PasswordAlgorithm::new(PASSWORD_ALGORITHM_SHA256)),
227            "the first supported one in the server's order, not the client's"
228        );
229        assert_eq!(got.first_supported(&[0x7777]), None);
230        Ok(())
231    }
232
233    /// A parameters length that runs past the value is not an algorithm.
234    #[test]
235    fn test_password_algorithm_with_truncated_parameters_is_refused() {
236        for value in [&[0x00, 0x02][..], &[0x00, 0x02, 0x00, 0x08, 1, 2, 3, 4][..]] {
237            let m = message_with(ATTR_PASSWORD_ALGORITHM, value);
238            assert!(PasswordAlgorithm::default().get_from(&m).is_err());
239            let m = message_with(ATTR_PASSWORD_ALGORITHMS, value);
240            assert!(PasswordAlgorithms::default().get_from(&m).is_err());
241        }
242    }
243}