Skip to main content

rtci_stun/
integrity.rs

1//! `MESSAGE-INTEGRITY` and `MESSAGE-INTEGRITY-SHA256` (RFC 8489 sections 14.5 and 14.6), and
2//! the keys of the two credential mechanisms (sections 9.1.1, 9.2.2 and 18.5.1).
3//!
4//! Both attributes carry an HMAC over the message up to the attribute, computed with the
5//! header's length field set as if the message ended at the attribute. They differ in the
6//! hash (SHA-1, SHA-256) and in that the SHA-256 one may be truncated where a usage allows it.
7//!
8//! A receiver does not read attributes directly off a message it has only run
9//! [`MessageIntegrity::check`](crate::integrity::MessageIntegrity::check) on: whatever follows the integrity attribute is not covered by
10//! it. Use [`Validator`](crate::validated::Validator), whose result exposes only what was
11//! authenticated.
12
13#[cfg(test)]
14mod integrity_test;
15
16use crate::attributes::*;
17use crate::message::*;
18use crate::opaque::opaque_string;
19use crate::password_algorithm::{PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256};
20use crypto::{CryptoError, HashAlgorithm, HmacAlgorithm, RTCCrypto, SecretVec, constant_time_eq};
21use shared::error::*;
22use std::fmt;
23
24// separator for credentials.
25pub(crate) const CREDENTIALS_SEP: &str = ":";
26
27/// Which of the two integrity attributes protects a message.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum IntegrityAlgorithm {
30    /// `MESSAGE-INTEGRITY`: HMAC-SHA1, 20 bytes.
31    Sha1,
32    /// `MESSAGE-INTEGRITY-SHA256`: HMAC-SHA256, 32 bytes unless a usage allows truncation.
33    Sha256,
34}
35
36impl IntegrityAlgorithm {
37    /// The attribute that carries this algorithm's HMAC.
38    #[must_use]
39    pub const fn attr_type(self) -> AttrType {
40        match self {
41            Self::Sha1 => ATTR_MESSAGE_INTEGRITY,
42            Self::Sha256 => ATTR_MESSAGE_INTEGRITY_SHA256,
43        }
44    }
45
46    /// The length of the untruncated HMAC in bytes.
47    #[must_use]
48    pub const fn tag_len(self) -> usize {
49        match self {
50            Self::Sha1 => MESSAGE_INTEGRITY_SIZE,
51            Self::Sha256 => MESSAGE_INTEGRITY_SHA256_SIZE,
52        }
53    }
54
55    const fn hmac(self) -> HmacAlgorithm {
56        match self {
57            Self::Sha1 => HmacAlgorithm::Sha1,
58            Self::Sha256 => HmacAlgorithm::Sha256,
59        }
60    }
61}
62
63/// The length of a `MESSAGE-INTEGRITY` value in bytes.
64pub const MESSAGE_INTEGRITY_SIZE: usize = 20;
65/// The length of an untruncated `MESSAGE-INTEGRITY-SHA256` value in bytes.
66pub const MESSAGE_INTEGRITY_SHA256_SIZE: usize = 32;
67/// The shortest `MESSAGE-INTEGRITY-SHA256` value RFC 8489 section 14.6 allows, in bytes.
68pub const MESSAGE_INTEGRITY_SHA256_MIN_SIZE: usize = 16;
69
70fn crypto_error(error: CryptoError) -> Error {
71    Error::Crypto(error.to_string())
72}
73
74/// The HMAC input of an integrity attribute that starts at `start` in `m.raw` and whose value
75/// takes `value_len` bytes: the message up to the attribute, with the header's length field
76/// pointing to the end of the attribute (RFC 8489 sections 14.5 and 14.6).
77///
78/// Returned as the adjusted length field, the two bytes ahead of it and the bytes after it.
79fn hmac_input(m: &Message, start: usize, value_len: usize) -> Result<([u8; 2], &[u8], &[u8])> {
80    if start < MESSAGE_HEADER_SIZE || m.raw.len() < start {
81        return Err(Error::ErrUnexpectedHeaderEof);
82    }
83    let length = start - MESSAGE_HEADER_SIZE
84        + ATTRIBUTE_HEADER_SIZE
85        + nearest_padded_value_length(value_len);
86    let length = u16::try_from(length).map_err(|_| Error::ErrPacketTooBig)?;
87    Ok((length.to_be_bytes(), &m.raw[..2], &m.raw[4..start]))
88}
89
90/// Appends the integrity attribute of `algorithm` to `m`, its HMAC cut to `tag_len` bytes.
91fn add_integrity(
92    m: &mut Message,
93    algorithm: IntegrityAlgorithm,
94    tag_len: usize,
95    key: &[u8],
96    crypto: &dyn RTCCrypto,
97) -> Result<()> {
98    for a in &m.attributes.0 {
99        // FINGERPRINT is the last attribute of a message (RFC 8489 section 14.7), so no
100        // integrity attribute is added after it.
101        if a.typ == ATTR_FINGERPRINT {
102            return Err(Error::ErrFingerprintBeforeIntegrity);
103        }
104    }
105    let start = MESSAGE_HEADER_SIZE + m.length as usize;
106    let mut tag = vec![0_u8; algorithm.tag_len()];
107    {
108        let (length, type_field, rest) = hmac_input(m, start, tag_len)?;
109        // A STUN message is authenticated once, so the MAC is keyed here rather than held. On
110        // a per-packet path the keyed object belongs in the surrounding state instead.
111        crypto
112            .new_hmac(algorithm.hmac(), key)
113            .and_then(|mut mac| mac.sign(&[type_field, &length, rest], &mut tag))
114            .map_err(crypto_error)?;
115    }
116    m.add(algorithm.attr_type(), &tag[..tag_len]);
117    Ok(())
118}
119
120/// Checks the first integrity attribute of `algorithm` in `m`, whose value must be at least
121/// `min_tag_len` bytes.
122pub(crate) fn check_integrity(
123    m: &Message,
124    algorithm: IntegrityAlgorithm,
125    min_tag_len: usize,
126    key: &[u8],
127    crypto: &dyn RTCCrypto,
128) -> Result<()> {
129    let index = m
130        .position(algorithm.attr_type())
131        .ok_or(Error::ErrAttributeNotFound)?;
132    let value = &m.attributes.0[index].value;
133    let full = algorithm.tag_len();
134    // RFC 8489 section 14.6: at most the whole HMAC, at least the usage's minimum, a multiple
135    // of 4. MESSAGE-INTEGRITY is never truncated, so its minimum is its whole length.
136    if value.len() > full || value.len() < min_tag_len || !value.len().is_multiple_of(PADDING) {
137        return Err(Error::ErrIntegrityMismatch);
138    }
139    let (length, type_field, rest) = hmac_input(m, m.attribute_offset(index), value.len())?;
140    let input: [&[u8]; 3] = [type_field, &length, rest];
141    let mut mac = crypto
142        .new_hmac(algorithm.hmac(), key)
143        .map_err(crypto_error)?;
144    let result = if value.len() == full {
145        mac.verify(&input, value)
146    } else {
147        let mut tag = vec![0_u8; full];
148        mac.sign(&input, &mut tag).and_then(|()| {
149            if constant_time_eq(&tag[..value.len()], value) {
150                Ok(())
151            } else {
152                Err(CryptoError::AuthenticationFailed)
153            }
154        })
155    };
156    match result {
157        Ok(()) => Ok(()),
158        Err(CryptoError::AuthenticationFailed | CryptoError::InvalidTagLength { .. }) => {
159            Err(Error::ErrIntegrityMismatch)
160        }
161        Err(error) => Err(crypto_error(error)),
162    }
163}
164
165/// The key of the long-term credential mechanism for a password algorithm of the STUN
166/// Password Algorithms registry (RFC 8489 sections 9.2.2 and 18.5.1):
167///
168/// ```text
169/// key = H(username ":" OpaqueString(realm) ":" OpaqueString(password))
170/// ```
171///
172/// with H = MD5 ([`PASSWORD_ALGORITHM_MD5`], 16 bytes; for legacy systems only, section
173/// 18.5.1.1) or SHA-256 ([`PASSWORD_ALGORITHM_SHA256`], 32 bytes). The username is
174/// OpaqueString-processed as well, as the USERNAME attribute requires (section 14.3); an empty
175/// part is used as it is.
176///
177/// # Errors
178///
179/// Fails for an algorithm other than those two, for a username, realm or password that
180/// OpaqueString does not allow, and when the provider fails.
181pub fn long_term_key(
182    algorithm: u16,
183    username: &str,
184    realm: &str,
185    password: &str,
186    crypto: &dyn RTCCrypto,
187) -> Result<Vec<u8>> {
188    let (hash, key_len) = match algorithm {
189        PASSWORD_ALGORITHM_MD5 => (HashAlgorithm::Md5, 16),
190        PASSWORD_ALGORITHM_SHA256 => (HashAlgorithm::Sha256, 32),
191        other => {
192            return Err(Error::Other(format!(
193                "password algorithm {other:#06x} is not supported"
194            )));
195        }
196    };
197    let credentials = SecretVec::new(
198        [
199            opaque_or_empty(username)?,
200            opaque_or_empty(realm)?,
201            opaque_or_empty(password)?,
202        ]
203        .join(CREDENTIALS_SEP)
204        .into_bytes(),
205    );
206    let key = crypto
207        .hash(hash, credentials.as_ref())
208        .map_err(crypto_error)?;
209    if key.len() != key_len {
210        return Err(Error::Crypto(format!(
211            "provider returned an invalid digest length: {}",
212            key.len()
213        )));
214    }
215    Ok(key)
216}
217
218fn opaque_or_empty(s: &str) -> Result<String> {
219    if s.is_empty() {
220        Ok(String::new())
221    } else {
222        opaque_string(s).map(|s| s.into_owned())
223    }
224}
225
226// MessageIntegrity represents MESSAGE-INTEGRITY attribute.
227//
228// RFC 8489 Section 14.5
229#[derive(Clone)]
230/// The `MESSAGE-INTEGRITY` key: an HMAC-SHA1 is computed over the message with it.
231///
232/// Built from a short-term password, or from a long-term username/realm/password triple.
233pub struct MessageIntegrity<'a> {
234    key: SecretVec,
235    crypto: &'a dyn RTCCrypto,
236}
237
238impl<'a> fmt::Display for MessageIntegrity<'a> {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(
241            f,
242            "MESSAGE-INTEGRITY key: [REDACTED; {} bytes]",
243            self.key.len()
244        )
245    }
246}
247
248impl<'a> Setter for MessageIntegrity<'a> {
249    // add_to adds MESSAGE-INTEGRITY attribute to message.
250    //
251    // CPU costly, see BenchmarkMessageIntegrity_AddTo.
252    fn add_to(&self, m: &mut Message) -> Result<()> {
253        add_integrity(
254            m,
255            IntegrityAlgorithm::Sha1,
256            MESSAGE_INTEGRITY_SIZE,
257            self.key.as_ref(),
258            self.crypto,
259        )
260    }
261}
262
263impl<'a> MessageIntegrity<'a> {
264    /// Creates a raw-key integrity attribute with an explicit crypto provider.
265    #[must_use]
266    pub fn new_raw_integrity_with_provider(
267        key: impl Into<Vec<u8>>,
268        crypto: &'a dyn RTCCrypto,
269    ) -> Self {
270        Self {
271            key: SecretVec::new(key.into()),
272            crypto,
273        }
274    }
275
276    /// Creates a short-term integrity attribute with an explicit crypto provider.
277    ///
278    /// The password's bytes are the key as they are: it must already be OpaqueString-processed
279    /// (RFC 8489 section 9.1.1). That holds for every ICE password, which is ASCII by its
280    /// grammar; for a password of any other origin use [`short_term`](Self::short_term).
281    #[must_use]
282    pub fn new_short_term_integrity_with_provider(
283        password: String,
284        crypto: &'a dyn RTCCrypto,
285    ) -> Self {
286        Self::new_raw_integrity_with_provider(password.into_bytes(), crypto)
287    }
288
289    /// Creates a short-term integrity attribute: `key = OpaqueString(password)` (RFC 8489
290    /// section 9.1.1).
291    ///
292    /// # Errors
293    ///
294    /// Fails for a password OpaqueString does not allow (RFC 8265 section 4.2).
295    pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
296        let key = opaque_string(password)?.into_owned().into_bytes();
297        Ok(Self::new_raw_integrity_with_provider(key, crypto))
298    }
299
300    /// Creates a long-term integrity attribute with an explicit crypto provider, with the MD5
301    /// key of RFC 8489 section 9.2.2 (realm and password OpaqueString-processed).
302    pub fn new_long_term_integrity_with_provider(
303        username: String,
304        realm: String,
305        password: String,
306        crypto: &'a dyn RTCCrypto,
307    ) -> Result<Self> {
308        let key = MessageIntegrity::long_term_integrity_key(username, realm, password, crypto)?;
309        Ok(Self::new_raw_integrity_with_provider(key, crypto))
310    }
311
312    /// Creates a long-term integrity key with an explicit crypto provider: the MD5 key of RFC
313    /// 8489 section 9.2.2. [`long_term_key`] takes the password algorithm.
314    pub fn long_term_integrity_key(
315        username: String,
316        realm: String,
317        password: String,
318        crypto: &'a dyn RTCCrypto,
319    ) -> Result<Vec<u8>> {
320        let password = SecretVec::new(password.into_bytes());
321        let password = std::str::from_utf8(password.as_ref())
322            .map_err(|_| Error::Other("the password is not UTF-8".to_owned()))?;
323        long_term_key(PASSWORD_ALGORITHM_MD5, &username, &realm, password, crypto)
324    }
325
326    /// Check checks MESSAGE-INTEGRITY attribute: the first one in `m`, over the message up to
327    /// it. Attributes after it are not covered, whatever they are.
328    ///
329    /// A receiver that goes on to read the message uses
330    /// [`Validator`](crate::validated::Validator) instead, which runs this check and then
331    /// exposes only the attributes it covers (RFC 8489 section 9).
332    ///
333    /// CPU costly, see BenchmarkMessageIntegrity_Check.
334    pub fn check(m: &mut Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
335        check_integrity(
336            m,
337            IntegrityAlgorithm::Sha1,
338            MESSAGE_INTEGRITY_SIZE,
339            key,
340            crypto,
341        )
342    }
343}
344
345/// The `MESSAGE-INTEGRITY-SHA256` key: an HMAC-SHA256 is computed over the message with it
346/// (RFC 8489 section 14.6).
347///
348/// The value is the whole 32-byte HMAC unless the usage allows truncation
349/// ([`with_tag_len`](Self::with_tag_len)).
350#[derive(Clone)]
351pub struct MessageIntegritySha256<'a> {
352    key: SecretVec,
353    tag_len: usize,
354    crypto: &'a dyn RTCCrypto,
355}
356
357impl<'a> fmt::Display for MessageIntegritySha256<'a> {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        write!(
360            f,
361            "MESSAGE-INTEGRITY-SHA256 key: [REDACTED; {} bytes]",
362            self.key.len()
363        )
364    }
365}
366
367impl<'a> Setter for MessageIntegritySha256<'a> {
368    /// Adds MESSAGE-INTEGRITY-SHA256 to `m`. It goes after MESSAGE-INTEGRITY when both are
369    /// sent, and ahead of FINGERPRINT.
370    fn add_to(&self, m: &mut Message) -> Result<()> {
371        add_integrity(
372            m,
373            IntegrityAlgorithm::Sha256,
374            self.tag_len,
375            self.key.as_ref(),
376            self.crypto,
377        )
378    }
379}
380
381impl<'a> MessageIntegritySha256<'a> {
382    /// An integrity attribute with `key` as the HMAC key.
383    #[must_use]
384    pub fn new_raw(key: impl Into<Vec<u8>>, crypto: &'a dyn RTCCrypto) -> Self {
385        Self {
386            key: SecretVec::new(key.into()),
387            tag_len: MESSAGE_INTEGRITY_SHA256_SIZE,
388            crypto,
389        }
390    }
391
392    /// The short-term credential form: `key = OpaqueString(password)` (RFC 8489 section
393    /// 9.1.1).
394    ///
395    /// # Errors
396    ///
397    /// Fails for a password OpaqueString does not allow.
398    pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
399        let key = opaque_string(password)?.into_owned().into_bytes();
400        Ok(Self::new_raw(key, crypto))
401    }
402
403    /// The long-term credential form, with the key of `password_algorithm`
404    /// ([`long_term_key`]).
405    ///
406    /// # Errors
407    ///
408    /// As [`long_term_key`].
409    pub fn long_term(
410        password_algorithm: u16,
411        username: &str,
412        realm: &str,
413        password: &str,
414        crypto: &'a dyn RTCCrypto,
415    ) -> Result<Self> {
416        let key = long_term_key(password_algorithm, username, realm, password, crypto)?;
417        Ok(Self::new_raw(key, crypto))
418    }
419
420    /// Sends the first `tag_len` bytes of the HMAC instead of all 32, for a usage that allows
421    /// truncation.
422    ///
423    /// # Errors
424    ///
425    /// RFC 8489 section 14.6: the value is 16 to 32 bytes and a multiple of 4.
426    pub fn with_tag_len(mut self, tag_len: usize) -> Result<Self> {
427        if !(MESSAGE_INTEGRITY_SHA256_MIN_SIZE..=MESSAGE_INTEGRITY_SHA256_SIZE).contains(&tag_len)
428            || !tag_len.is_multiple_of(PADDING)
429        {
430            return Err(Error::ErrAttributeSizeInvalid);
431        }
432        self.tag_len = tag_len;
433        Ok(self)
434    }
435
436    /// Checks the first MESSAGE-INTEGRITY-SHA256 of `m`, which must be the whole 32-byte HMAC.
437    ///
438    /// As with [`MessageIntegrity::check`], a receiver that goes on to read the message uses
439    /// [`Validator`](crate::validated::Validator).
440    ///
441    /// # Errors
442    ///
443    /// `ErrAttributeNotFound` without the attribute, `ErrIntegrityMismatch` when it does not
444    /// match or is truncated.
445    pub fn check(m: &Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
446        Self::check_truncated(m, MESSAGE_INTEGRITY_SHA256_SIZE, key, crypto)
447    }
448
449    /// Checks the first MESSAGE-INTEGRITY-SHA256 of `m` for a usage that allows truncation
450    /// down to `min_tag_len` bytes (never fewer than 16).
451    ///
452    /// # Errors
453    ///
454    /// As [`check`](Self::check); a value shorter than `min_tag_len` is a mismatch.
455    pub fn check_truncated(
456        m: &Message,
457        min_tag_len: usize,
458        key: &[u8],
459        crypto: &dyn RTCCrypto,
460    ) -> Result<()> {
461        check_integrity(
462            m,
463            IntegrityAlgorithm::Sha256,
464            min_tag_len.max(MESSAGE_INTEGRITY_SHA256_MIN_SIZE),
465            key,
466            crypto,
467        )
468    }
469}