Skip to main content

rtci_stun/
validated.rs

1//! Receiving a STUN message safely: the checks of RFC 8489 sections 6.3, 9 and 14.7 in one
2//! place, with a result that only shows what the checks cover.
3//!
4//! # Why
5//!
6//! `MESSAGE-INTEGRITY` and `MESSAGE-INTEGRITY-SHA256` authenticate the message *up to* the
7//! attribute. Anything after it can be appended by anyone on the path without breaking the
8//! HMAC, which is why RFC 8489 section 9 says attributes that follow an integrity attribute
9//! MUST be ignored (FINGERPRINT, and MESSAGE-INTEGRITY-SHA256 after MESSAGE-INTEGRITY,
10//! excepted). A receiver that checks the HMAC and then reads attributes with
11//! [`Message::get`](crate::message::Message::get),
12//! [`Message::contains`](crate::message::Message::contains) or a
13//! [`Getter`](crate::message::Getter) on the original
14//! message does not ignore them: an ICE-CONTROLLED appended after the integrity attribute of
15//! a genuine Binding request would be obeyed.
16//!
17//! # How
18//!
19//! Run every received message through a [`Validator`](crate::validated::Validator) and read attributes only from the
20//! [`ValidatedMessage`](crate::validated::ValidatedMessage) it returns. That message holds the attributes ahead of the first
21//! integrity attribute and nothing else, so an appended attribute cannot be read by mistake.
22//!
23//! ```
24//! use rtci_stun::attributes::*;
25//! use rtci_stun::fingerprint::FINGERPRINT;
26//! use rtci_stun::integrity::MessageIntegrity;
27//! use rtci_stun::message::*;
28//! use rtci_stun::textattrs::TextAttribute;
29//! use rtci_stun::validated::{Rejection, Validator};
30//!
31//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
32//! let provider = rtci_stun::crypto::default_provider()?;
33//! let crypto = provider.crypto();
34//!
35//! // The peer's request: USERNAME inside the integrity, then FINGERPRINT.
36//! let mut request = Message::new();
37//! request.build(&[
38//!     Box::new(BINDING_REQUEST),
39//!     Box::new(TransactionId::new()),
40//!     Box::new(TextAttribute::new(ATTR_USERNAME, "local:remote".to_owned())),
41//!     Box::new(MessageIntegrity::short_term("password", crypto)?),
42//!     Box::new(FINGERPRINT),
43//! ])?;
44//!
45//! // What this usage understands: STUN's own attributes plus ICE's.
46//! let known = [&STUN_ATTRIBUTES[..], &[ATTR_PRIORITY, ATTR_USE_CANDIDATE]].concat();
47//! let validator = Validator::new().require_fingerprint().known_attributes(&known);
48//!
49//! let mut received = Message::new();
50//! received.unmarshal_binary(&request.raw)?;
51//! match validator.authenticate(&received, b"password", crypto) {
52//!     Ok(valid) => {
53//!         // `valid` derefs to a `Message` with the covered attributes only.
54//!         assert!(valid.contains(ATTR_USERNAME));
55//!     }
56//!     Err(Rejection::UnknownAttributes(unknown)) => {
57//!         // A request: answer 420 (`unknown_attributes_response`). Anything else: drop it.
58//!         # let _ = unknown;
59//!     }
60//!     Err(_) => { /* drop it */ }
61//! }
62//! # Ok(())
63//! # }
64//! # example().unwrap();
65//! ```
66//!
67//! A message that carries no integrity by design (a Binding indication, the response of a
68//! public STUN server, a 401 challenge) goes through
69//! [`Validator::unauthenticated`](crate::validated::Validator::unauthenticated), which
70//! applies the same rule: if someone put an integrity attribute in it, what follows is still
71//! not shown.
72
73#[cfg(test)]
74mod validated_test;
75
76use crate::attributes::*;
77use crate::error_code::CODE_UNKNOWN_ATTRIBUTE;
78use crate::fingerprint::FINGERPRINT;
79use crate::integrity::{
80    IntegrityAlgorithm, MESSAGE_INTEGRITY_SHA256_MIN_SIZE, MESSAGE_INTEGRITY_SHA256_SIZE,
81    check_integrity,
82};
83use crate::message::*;
84use crate::uattrs::UnknownAttributes;
85use crypto::RTCCrypto;
86use shared::error::*;
87
88use std::fmt;
89use std::ops::Deref;
90
91/// Why a received message was not accepted.
92///
93/// RFC 8489 section 6.3: a message that fails the basic checks is silently discarded. The one
94/// case that has an answer is [`UnknownAttributes`](Self::UnknownAttributes) in a *request*,
95/// which is answered 420 ([`unknown_attributes_response`]).
96#[derive(Debug, Clone, PartialEq, Eq)]
97#[non_exhaustive]
98pub enum Rejection {
99    /// FINGERPRINT is required by the usage and the message has none.
100    FingerprintMissing,
101    /// FINGERPRINT has the wrong value or length, or is not the last attribute.
102    FingerprintMismatch,
103    /// The message has no integrity attribute, or not the one that was asked for.
104    IntegrityMissing,
105    /// The integrity attribute does not match the message and key, or is shorter than the
106    /// usage allows.
107    IntegrityMismatch,
108    /// The message has comprehension-required attributes the usage does not know, ahead of
109    /// its integrity attribute. They are listed in the order they appear.
110    UnknownAttributes(Vec<AttrType>),
111    /// The crypto provider failed.
112    Crypto(String),
113}
114
115impl fmt::Display for Rejection {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Self::FingerprintMissing => write!(f, "FINGERPRINT is missing"),
119            Self::FingerprintMismatch => write!(f, "FINGERPRINT does not match"),
120            Self::IntegrityMissing => write!(f, "the integrity attribute is missing"),
121            Self::IntegrityMismatch => write!(f, "the integrity attribute does not match"),
122            Self::UnknownAttributes(unknown) => write!(
123                f,
124                "unknown comprehension-required attributes: {}",
125                UnknownAttributes(unknown.clone())
126            ),
127            Self::Crypto(error) => write!(f, "crypto provider: {error}"),
128        }
129    }
130}
131
132impl std::error::Error for Rejection {}
133
134/// The checks a usage applies to every message it receives.
135///
136/// The default checks a FINGERPRINT that is present and knows no usage attributes; a usage
137/// states its own rules once and keeps the value:
138///
139/// * [`require_fingerprint`](Self::require_fingerprint): the usage sends FINGERPRINT in every
140///   message (ICE does, RFC 8445 section 7.1), so a message without one is not for it;
141/// * [`known_attributes`](Self::known_attributes): the comprehension-required attributes the
142///   usage understands; any other fails the message (RFC 8489 sections 6.3.1 to 6.3.4);
143/// * [`allow_truncated_sha256`](Self::allow_truncated_sha256): the usage allows a truncated
144///   MESSAGE-INTEGRITY-SHA256 (RFC 8489 section 14.6).
145#[derive(Debug, Clone, Copy)]
146pub struct Validator<'a> {
147    known: Option<&'a [AttrType]>,
148    fingerprint_required: bool,
149    min_sha256_len: usize,
150}
151
152impl Default for Validator<'_> {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158impl<'a> Validator<'a> {
159    /// A validator that checks FINGERPRINT when it is present, takes
160    /// MESSAGE-INTEGRITY-SHA256 only whole, and does not look for unknown attributes.
161    #[must_use]
162    pub const fn new() -> Self {
163        Self {
164            known: None,
165            fingerprint_required: false,
166            min_sha256_len: MESSAGE_INTEGRITY_SHA256_SIZE,
167        }
168    }
169
170    /// Refuses a message without FINGERPRINT ([`Rejection::FingerprintMissing`]).
171    #[must_use]
172    pub const fn require_fingerprint(mut self) -> Self {
173        self.fingerprint_required = true;
174        self
175    }
176
177    /// Refuses a message that carries a comprehension-required attribute outside `known`
178    /// ([`Rejection::UnknownAttributes`]). `known` is
179    /// [`STUN_ATTRIBUTES`] plus the usage's own.
180    #[must_use]
181    pub const fn known_attributes(mut self, known: &'a [AttrType]) -> Self {
182        self.known = Some(known);
183        self
184    }
185
186    /// Accepts a MESSAGE-INTEGRITY-SHA256 truncated to `min_len` bytes or more (never fewer
187    /// than 16, RFC 8489 section 14.6).
188    #[must_use]
189    pub const fn allow_truncated_sha256(mut self, min_len: usize) -> Self {
190        self.min_sha256_len = if min_len < MESSAGE_INTEGRITY_SHA256_MIN_SIZE {
191            MESSAGE_INTEGRITY_SHA256_MIN_SIZE
192        } else {
193            min_len
194        };
195        self
196    }
197
198    /// Checks a message that must be authenticated with `key`.
199    ///
200    /// RFC 8489 sections 9.1.3 and 9.2.4: MESSAGE-INTEGRITY-SHA256 is verified when the
201    /// message has it, MESSAGE-INTEGRITY otherwise.
202    /// [`ValidatedMessage::integrity`] says which, so a response can be sent with the same
203    /// one (section 9.1.3).
204    ///
205    /// # Errors
206    ///
207    /// The [`Rejection`] that says which check failed. In order: FINGERPRINT, integrity,
208    /// unknown attributes (RFC 8489 section 6.3).
209    pub fn authenticate(
210        &self,
211        m: &Message,
212        key: &[u8],
213        crypto: &dyn RTCCrypto,
214    ) -> std::result::Result<ValidatedMessage, Rejection> {
215        let algorithm = if m.contains(ATTR_MESSAGE_INTEGRITY_SHA256) {
216            IntegrityAlgorithm::Sha256
217        } else {
218            IntegrityAlgorithm::Sha1
219        };
220        self.authenticate_with(m, algorithm, key, crypto)
221    }
222
223    /// Checks a message that must be authenticated with `key` by the integrity attribute of
224    /// `algorithm`, whatever else it carries.
225    ///
226    /// This is the check for a response when the request carried one integrity attribute
227    /// (RFC 8489 section 9.1.4: "the algorithm in the response has to match") and for
228    /// everything after the first response (section 9.1.5).
229    ///
230    /// # Errors
231    ///
232    /// As [`authenticate`](Self::authenticate); a message without that attribute is
233    /// [`Rejection::IntegrityMissing`].
234    pub fn authenticate_with(
235        &self,
236        m: &Message,
237        algorithm: IntegrityAlgorithm,
238        key: &[u8],
239        crypto: &dyn RTCCrypto,
240    ) -> std::result::Result<ValidatedMessage, Rejection> {
241        let fingerprint = self.check_fingerprint(m)?;
242        if !m.contains(algorithm.attr_type()) {
243            return Err(Rejection::IntegrityMissing);
244        }
245        let min_len = match algorithm {
246            IntegrityAlgorithm::Sha1 => algorithm.tag_len(),
247            IntegrityAlgorithm::Sha256 => self.min_sha256_len,
248        };
249        match check_integrity(m, algorithm, min_len, key, crypto) {
250            Ok(()) => {}
251            Err(Error::ErrIntegrityMismatch) => return Err(Rejection::IntegrityMismatch),
252            Err(Error::ErrAttributeNotFound) => return Err(Rejection::IntegrityMissing),
253            Err(error) => return Err(Rejection::Crypto(error.to_string())),
254        }
255        self.finish(m, Some(algorithm), fingerprint)
256    }
257
258    /// Checks a message that is not authenticated: FINGERPRINT and unknown attributes only.
259    ///
260    /// For a usage or a message without credentials: a Binding indication, the response of a
261    /// public STUN server, the 401 that starts the long-term mechanism. If the message does
262    /// carry an integrity attribute, it is not verified and
263    /// [`ValidatedMessage::integrity`] is `None`, but the attributes after it are still left
264    /// out, as RFC 8489 section 9 requires of every agent.
265    ///
266    /// # Errors
267    ///
268    /// The [`Rejection`] that says which check failed.
269    pub fn unauthenticated(&self, m: &Message) -> std::result::Result<ValidatedMessage, Rejection> {
270        let fingerprint = self.check_fingerprint(m)?;
271        self.finish(m, None, fingerprint)
272    }
273
274    /// RFC 8489 sections 7 and 14.7: a FINGERPRINT has the right value and is the last
275    /// attribute; whether one must be there is the usage's rule.
276    fn check_fingerprint(&self, m: &Message) -> std::result::Result<bool, Rejection> {
277        if !m.contains(ATTR_FINGERPRINT) {
278            return if self.fingerprint_required {
279                Err(Rejection::FingerprintMissing)
280            } else {
281                Ok(false)
282            };
283        }
284        FINGERPRINT
285            .check(m)
286            .map(|()| true)
287            .map_err(|_| Rejection::FingerprintMismatch)
288    }
289
290    fn finish(
291        &self,
292        m: &Message,
293        integrity: Option<IntegrityAlgorithm>,
294        fingerprint: bool,
295    ) -> std::result::Result<ValidatedMessage, Rejection> {
296        let covered = covered_message(m);
297        if let Some(known) = self.known {
298            let unknown = covered.unknown_required_attributes(known);
299            if !unknown.is_empty() {
300                return Err(Rejection::UnknownAttributes(unknown));
301            }
302        }
303        Ok(ValidatedMessage {
304            covered,
305            integrity,
306            fingerprint,
307        })
308    }
309}
310
311/// The part of `m` an agent may read: its header and the attributes ahead of its first
312/// integrity attribute, or all of them when it has none (RFC 8489 section 9). FINGERPRINT,
313/// which only says the message is STUN, is left out with the rest.
314fn covered_message(m: &Message) -> Message {
315    let cut = m
316        .attributes
317        .0
318        .iter()
319        .position(|a| {
320            a.typ == ATTR_MESSAGE_INTEGRITY
321                || a.typ == ATTR_MESSAGE_INTEGRITY_SHA256
322                || a.typ == ATTR_FINGERPRINT
323        })
324        .unwrap_or(m.attributes.0.len());
325    let end = m.attribute_offset(cut).min(m.raw.len());
326    let mut covered = Message {
327        typ: m.typ,
328        length: (end.saturating_sub(MESSAGE_HEADER_SIZE)) as u32,
329        transaction_id: m.transaction_id,
330        attributes: Attributes(m.attributes.0[..cut].to_vec()),
331        raw: m.raw[..end].to_vec(),
332    };
333    if covered.raw.len() >= MESSAGE_HEADER_SIZE {
334        covered.write_length();
335    }
336    covered
337}
338
339/// A received message that passed a [`Validator`], reduced to what its checks cover.
340///
341/// It dereferences to a [`Message`] that holds the header and the attributes ahead of the
342/// first integrity attribute: [`get`](Message::get), [`contains`](Message::contains) and every
343/// [`Getter`] work on it and cannot see an attribute that was appended after the integrity
344/// attribute. The integrity attributes and FINGERPRINT are not in it either; ask
345/// [`integrity`](Self::integrity) and [`has_fingerprint`](Self::has_fingerprint).
346#[derive(Debug, Clone, PartialEq)]
347pub struct ValidatedMessage {
348    covered: Message,
349    integrity: Option<IntegrityAlgorithm>,
350    fingerprint: bool,
351}
352
353impl ValidatedMessage {
354    /// The message, with the covered attributes only.
355    #[must_use]
356    pub fn message(&self) -> &Message {
357        &self.covered
358    }
359
360    /// Gives up the wrapper and returns the message with the covered attributes only.
361    #[must_use]
362    pub fn into_message(self) -> Message {
363        self.covered
364    }
365
366    /// The integrity attribute that was verified, or `None` for a message accepted through
367    /// [`Validator::unauthenticated`].
368    ///
369    /// A response to this message carries the same one and no other (RFC 8489 section
370    /// 9.1.3).
371    #[must_use]
372    pub fn integrity(&self) -> Option<IntegrityAlgorithm> {
373        self.integrity
374    }
375
376    /// Whether the message was authenticated.
377    #[must_use]
378    pub fn is_authenticated(&self) -> bool {
379        self.integrity.is_some()
380    }
381
382    /// Whether the message carried a (correct) FINGERPRINT.
383    #[must_use]
384    pub fn has_fingerprint(&self) -> bool {
385        self.fingerprint
386    }
387}
388
389impl Deref for ValidatedMessage {
390    type Target = Message;
391
392    fn deref(&self) -> &Message {
393        &self.covered
394    }
395}
396
397impl AsRef<Message> for ValidatedMessage {
398    fn as_ref(&self) -> &Message {
399        &self.covered
400    }
401}
402
403/// Builds the answer to a request that failed with [`Rejection::UnknownAttributes`]: an error
404/// response of the request's method and transaction id with ERROR-CODE 420 (Unknown
405/// Attribute) and the attributes in UNKNOWN-ATTRIBUTES (RFC 8489 sections 6.3.1 and 14.8).
406///
407/// `then` is applied after them: the integrity attribute when the request was authenticated
408/// (section 6.3.1.1), then FINGERPRINT where the usage sends it.
409///
410/// # Errors
411///
412/// Fails when `request` is not a request, or a setter fails.
413pub fn unknown_attributes_response(
414    request: &Message,
415    unknown: &[AttrType],
416    then: &[Box<dyn Setter + '_>],
417) -> Result<Message> {
418    if request.typ.class != CLASS_REQUEST {
419        return Err(Error::ErrUnexpectedClass);
420    }
421    let mut response = Message::new();
422    response.write_header();
423    response.set_type(MessageType::new(request.typ.method, CLASS_ERROR_RESPONSE));
424    request.transaction_id.add_to(&mut response)?;
425    CODE_UNKNOWN_ATTRIBUTE.add_to(&mut response)?;
426    UnknownAttributes(unknown.to_vec()).add_to(&mut response)?;
427    for setter in then {
428        setter.add_to(&mut response)?;
429        if response.length > u32::from(u16::MAX) {
430            return Err(Error::ErrPacketTooBig);
431        }
432    }
433    Ok(response)
434}