rtci_stun/long_term.rs
1//! The client side of the long-term credential mechanism (RFC 8489 section 9.2), as data and
2//! rules without I/O.
3//!
4//! [`LongTermCredentials`](crate::long_term::LongTermCredentials) holds what a client keeps for one server: the user name and
5//! password, and, once the server has challenged a request, the realm, the nonce, the password
6//! algorithm and whether the user name is sent hashed. It does three things:
7//!
8//! * [`challenge`](crate::long_term::LongTermCredentials::challenge) takes a 401 (Unauthenticated) or 438
9//! (Stale Nonce) error response and decides whether the request may be retried, applying
10//! the bid-down protection of the nonce cookie (section 9.2.5);
11//! * [`setter`](crate::long_term::LongTermCredentials::setter) adds the authentication attributes to a request:
12//! none before the first challenge (section 9.2.3.1), then USERNAME or USERHASH, REALM,
13//! NONCE, PASSWORD-ALGORITHMS and PASSWORD-ALGORITHM when the server offered algorithms, and
14//! the integrity attribute (sections 9.2.3.2 and 9.2.5);
15//! * [`check_response`](crate::long_term::LongTermCredentials::check_response) authenticates a response and
16//! says whether it is one to act on, a challenge, or one to discard (section 9.2.5).
17//!
18//! The transaction layer stays with the caller: a retry is a new transaction, a discarded
19//! response leaves the request's retransmissions running.
20
21#[cfg(test)]
22mod long_term_test;
23
24use crate::attributes::*;
25use crate::error_code::{CODE_STALE_NONCE, CODE_UNAUTHORIZED, ErrorCode, ErrorCodeAttribute};
26use crate::integrity::{
27 IntegrityAlgorithm, MessageIntegrity, MessageIntegritySha256, long_term_key,
28};
29use crate::message::*;
30use crate::nonce_cookie::SecurityFeatures;
31use crate::opaque::opaque_string;
32use crate::password_algorithm::{
33 PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256, PasswordAlgorithm, PasswordAlgorithms,
34};
35use crate::textattrs::TextAttribute;
36use crate::userhash::Userhash;
37use crate::validated::{Rejection, ValidatedMessage, Validator};
38use crypto::{RTCCrypto, SecretVec};
39use shared::error::*;
40
41use std::fmt;
42
43/// Why a 401 or 438 error response does not lead to a retry.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum ChallengeError {
47 /// The response is not an error response with code 401 or 438.
48 NotAChallenge,
49 /// The response has no REALM or no NONCE, or one of them is not text.
50 Incomplete,
51 /// The nonce cookie has the "Password algorithms" bit set but the response carries no
52 /// PASSWORD-ALGORITHMS: the attribute was removed on the way (a bid-down attack). RFC
53 /// 8489 section 9.2.5: the client MUST NOT retry.
54 BidDown,
55 /// PASSWORD-ALGORITHMS lists no algorithm this client supports. RFC 8489 section 9.2.5:
56 /// the client MUST NOT retry.
57 NoSupportedAlgorithm,
58 /// A 401 to a request that was already authenticated with the same user name, realm and
59 /// password algorithm: the credentials are wrong, and retrying without changing them is
60 /// what RFC 8489 section 9.2.5 forbids.
61 CredentialsRejected,
62 /// The realm, the user name or the password cannot be used (not an OpaqueString), or the
63 /// crypto provider failed.
64 Unusable(String),
65}
66
67impl fmt::Display for ChallengeError {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 match self {
70 Self::NotAChallenge => write!(f, "not a 401 or 438 error response"),
71 Self::Incomplete => write!(f, "the challenge has no REALM or no NONCE"),
72 Self::BidDown => write!(
73 f,
74 "the nonce cookie announces PASSWORD-ALGORITHMS and the response has none"
75 ),
76 Self::NoSupportedAlgorithm => {
77 write!(f, "the server offers no supported password algorithm")
78 }
79 Self::CredentialsRejected => write!(f, "the credentials were rejected"),
80 Self::Unusable(reason) => write!(f, "the credentials cannot be used: {reason}"),
81 }
82 }
83}
84
85impl std::error::Error for ChallengeError {}
86
87/// What a response to a request of this client is, once checked.
88#[derive(Debug, Clone, PartialEq)]
89pub enum LongTermResponse {
90 /// A success or error response authenticated with the client's key: act on it.
91 Authenticated(ValidatedMessage),
92 /// A 401 or 438 error response. It is not authenticated (the server cannot sign for
93 /// credentials it rejects); hand the original response to
94 /// [`LongTermCredentials::challenge`].
95 Challenge(ValidatedMessage),
96}
97
98/// What a server's challenge fixed: everything that is derived from the realm, the nonce and
99/// the offered algorithms.
100struct Session {
101 realm: String,
102 nonce: String,
103 /// PASSWORD-ALGORITHMS as the server sent it, echoed in every request.
104 algorithms: Option<PasswordAlgorithms>,
105 /// The algorithm chosen from it; `None` is RFC 5389's MD5 without PASSWORD-ALGORITHM.
106 algorithm: Option<PasswordAlgorithm>,
107 /// USERHASH in place of USERNAME.
108 userhash: Option<Userhash>,
109 key: SecretVec,
110}
111
112/// A client's long-term credentials for one server, and what the server's challenges added
113/// to them. See the [module documentation](self).
114pub struct LongTermCredentials {
115 username: String,
116 password: SecretVec,
117 supported: Vec<u16>,
118 session: Option<Session>,
119 /// The user name may go only as USERHASH ([`Self::with_username_anonymity_required`]).
120 anonymity_required: bool,
121}
122
123impl fmt::Debug for LongTermCredentials {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.debug_struct("LongTermCredentials")
126 .field("username", &self.username)
127 .field("password", &"[REDACTED]")
128 .field("realm", &self.realm())
129 .field("nonce", &self.nonce())
130 .field("password_algorithm", &self.password_algorithm())
131 .field("uses_userhash", &self.uses_userhash())
132 .finish()
133 }
134}
135
136impl LongTermCredentials {
137 /// Credentials that support the SHA-256 and MD5 password algorithms.
138 ///
139 /// # Errors
140 ///
141 /// RFC 8489 section 14.3: the user name is OpaqueString-processed; one the profile does
142 /// not allow is refused, as is such a password (section 9.2.2).
143 pub fn new(username: &str, password: &str) -> Result<Self> {
144 Ok(Self {
145 username: opaque_string(username)?.into_owned(),
146 password: SecretVec::new(opaque_string(password)?.into_owned().into_bytes()),
147 supported: vec![PASSWORD_ALGORITHM_SHA256, PASSWORD_ALGORITHM_MD5],
148 session: None,
149 anonymity_required: false,
150 })
151 }
152
153 /// With `required`, the user name never goes in a USERNAME attribute: a challenge whose
154 /// nonce cookie does not offer username anonymity (RFC 8489 section 9.2.5, USERHASH) is
155 /// refused as [`ChallengeError::Unusable`], and nothing with the credential is sent. For a
156 /// user name that reveals the user, over a transport that is not (D)TLS: RFC 8656 section
157 /// 21.1.6, "If the username reveals the identity of the user, the client MUST use the
158 /// USERHASH attribute ... or use (D)TLS".
159 #[must_use]
160 pub fn with_username_anonymity_required(mut self, required: bool) -> Self {
161 self.anonymity_required = required;
162 self
163 }
164
165 /// Restricts the password algorithms this client accepts from a server's
166 /// PASSWORD-ALGORITHMS, for instance to SHA-256 alone (RFC 8489 section 18.5.1.1 keeps
167 /// MD5 for legacy systems). Numbers other than
168 /// [`PASSWORD_ALGORITHM_SHA256`] and [`PASSWORD_ALGORITHM_MD5`] are dropped: there is no
169 /// key derivation for them.
170 ///
171 /// A server that sends no PASSWORD-ALGORITHMS is an RFC 5389 server, which has MD5 only;
172 /// a client that left MD5 out refuses its challenge
173 /// ([`ChallengeError::NoSupportedAlgorithm`]).
174 #[must_use]
175 pub fn with_password_algorithms(mut self, supported: &[u16]) -> Self {
176 self.supported = supported
177 .iter()
178 .copied()
179 .filter(|a| [PASSWORD_ALGORITHM_SHA256, PASSWORD_ALGORITHM_MD5].contains(a))
180 .collect();
181 self
182 }
183
184 /// The user name, OpaqueString-processed.
185 #[must_use]
186 pub fn username(&self) -> &str {
187 &self.username
188 }
189
190 /// The realm of the last challenge.
191 #[must_use]
192 pub fn realm(&self) -> Option<&str> {
193 self.session.as_ref().map(|s| s.realm.as_str())
194 }
195
196 /// The nonce of the last challenge.
197 #[must_use]
198 pub fn nonce(&self) -> Option<&str> {
199 self.session.as_ref().map(|s| s.nonce.as_str())
200 }
201
202 /// The password algorithm sent in PASSWORD-ALGORITHM, when the server offered a list.
203 #[must_use]
204 pub fn password_algorithm(&self) -> Option<&PasswordAlgorithm> {
205 self.session.as_ref().and_then(|s| s.algorithm.as_ref())
206 }
207
208 /// Whether requests carry USERHASH in place of USERNAME.
209 #[must_use]
210 pub fn uses_userhash(&self) -> bool {
211 self.session.as_ref().is_some_and(|s| s.userhash.is_some())
212 }
213
214 /// The integrity attribute requests carry and responses must carry, once challenged:
215 /// MESSAGE-INTEGRITY-SHA256 alone after a challenge with PASSWORD-ALGORITHMS (RFC 8489
216 /// section 9.2.5), MESSAGE-INTEGRITY otherwise.
217 #[must_use]
218 pub fn integrity(&self) -> Option<IntegrityAlgorithm> {
219 self.session.as_ref().map(|s| {
220 if s.algorithms.is_some() {
221 IntegrityAlgorithm::Sha256
222 } else {
223 IntegrityAlgorithm::Sha1
224 }
225 })
226 }
227
228 /// Forgets the server's challenge: the next request is a first request again.
229 pub fn reset(&mut self) {
230 self.session = None;
231 }
232
233 /// Takes the 401 (Unauthenticated) or 438 (Stale Nonce) error `response` to `request` and
234 /// prepares the retry (RFC 8489 section 9.2.5).
235 ///
236 /// On `Ok`, the realm, nonce, algorithm and key are replaced by the response's, and the
237 /// request is to be sent again in a new transaction with [`setter`](Self::setter).
238 ///
239 /// # Errors
240 ///
241 /// The [`ChallengeError`] that says why there is no retry. The state is unchanged then.
242 pub fn challenge(
243 &mut self,
244 request: &Message,
245 response: &Message,
246 crypto: &dyn RTCCrypto,
247 ) -> std::result::Result<(), ChallengeError> {
248 // Whatever follows an integrity attribute is not read (section 9), signed or not.
249 let response = Validator::new()
250 .unauthenticated(response)
251 .map_err(|_| ChallengeError::NotAChallenge)?;
252 let code = error_code_of(&response).ok_or(ChallengeError::NotAChallenge)?;
253 if code != CODE_UNAUTHORIZED && code != CODE_STALE_NONCE {
254 return Err(ChallengeError::NotAChallenge);
255 }
256 let realm = TextAttribute::get_from_as(&response, ATTR_REALM)
257 .map_err(|_| ChallengeError::Incomplete)?
258 .text;
259 let nonce = TextAttribute::get_from_as(&response, ATTR_NONCE)
260 .map_err(|_| ChallengeError::Incomplete)?
261 .text;
262 if realm.is_empty() || nonce.is_empty() {
263 return Err(ChallengeError::Incomplete);
264 }
265 let realm = opaque_string(&realm)
266 .map_err(|e| ChallengeError::Unusable(e.to_string()))?
267 .into_owned();
268
269 // The nonce cookie says which features the server uses; the attributes have to agree.
270 let features = SecurityFeatures::from_nonce(&nonce).unwrap_or(SecurityFeatures::NONE);
271 let mut algorithms = PasswordAlgorithms::default();
272 let algorithms = match algorithms.get_from(&response) {
273 Ok(()) => Some(algorithms),
274 Err(Error::ErrAttributeNotFound) => None,
275 Err(_) => return Err(ChallengeError::Incomplete),
276 };
277 if features.password_algorithms() && algorithms.is_none() {
278 return Err(ChallengeError::BidDown);
279 }
280 let algorithm = match &algorithms {
281 Some(list) => Some(
282 list.first_supported(&self.supported)
283 .cloned()
284 .ok_or(ChallengeError::NoSupportedAlgorithm)?,
285 ),
286 // An RFC 5389 server: the MD5 key, without PASSWORD-ALGORITHM.
287 None if self.supported.contains(&PASSWORD_ALGORITHM_MD5) => None,
288 None => return Err(ChallengeError::NoSupportedAlgorithm),
289 };
290
291 // A 401 to a request that carried these very credentials: they are wrong.
292 if code == CODE_UNAUTHORIZED
293 && let Some(session) = &self.session
294 && request_was_authenticated(request)
295 && session.realm == realm
296 && session.algorithm == algorithm
297 && session.userhash.is_some() == features.username_anonymity()
298 {
299 return Err(ChallengeError::CredentialsRejected);
300 }
301
302 if self.anonymity_required && !features.username_anonymity() {
303 return Err(ChallengeError::Unusable(
304 "the server offers no USERHASH and the user name may not be sent in the clear"
305 .to_owned(),
306 ));
307 }
308 let userhash = if features.username_anonymity() {
309 Some(
310 Userhash::new(&self.username, &realm, crypto)
311 .map_err(|e| ChallengeError::Unusable(e.to_string()))?,
312 )
313 } else {
314 None
315 };
316 let password = std::str::from_utf8(self.password.as_ref())
317 .map_err(|e| ChallengeError::Unusable(e.to_string()))?;
318 let key = long_term_key(
319 algorithm
320 .as_ref()
321 .map_or(PASSWORD_ALGORITHM_MD5, |a| a.algorithm),
322 &self.username,
323 &realm,
324 password,
325 crypto,
326 )
327 .map_err(|e| ChallengeError::Unusable(e.to_string()))?;
328
329 self.session = Some(Session {
330 realm,
331 nonce,
332 algorithms,
333 algorithm,
334 userhash,
335 key: SecretVec::new(key),
336 });
337 Ok(())
338 }
339
340 /// A [`Setter`] that adds the authentication attributes to a request. It goes after the
341 /// request's own attributes and ahead of FINGERPRINT.
342 ///
343 /// Before the first challenge it adds nothing: the first request carries no USERNAME,
344 /// USERHASH, REALM, NONCE, PASSWORD-ALGORITHMS, PASSWORD-ALGORITHM or integrity attribute
345 /// (RFC 8489 section 9.2.3.1).
346 #[must_use]
347 pub fn setter<'a>(&'a self, crypto: &'a dyn RTCCrypto) -> LongTermAuthentication<'a> {
348 LongTermAuthentication {
349 credentials: self,
350 crypto,
351 }
352 }
353
354 /// Checks a response to a request that was sent with [`setter`](Self::setter) after a
355 /// challenge, by the rules of RFC 8489 section 9.2.5. `validator` carries the usage's own
356 /// checks (FINGERPRINT, known attributes).
357 ///
358 /// * A 401 or 438 error response is a [`LongTermResponse::Challenge`]: such a response
359 /// need not be signed.
360 /// * Any other response must carry the integrity attribute the request carried, valid
361 /// under the client's key; then it is [`LongTermResponse::Authenticated`].
362 ///
363 /// # Errors
364 ///
365 /// The response is to be discarded as if it had never been received, so that the
366 /// request's retransmissions continue: [`Rejection::IntegrityMissing`] (which is what a
367 /// 400 without integrity attribute gets) or [`Rejection::IntegrityMismatch`], and, for a
368 /// response whose NONCE has a cookie with the "Password algorithms" bit but which has no
369 /// PASSWORD-ALGORITHMS, [`Rejection::IntegrityMissing`] as well: it is to be ignored.
370 /// When every response to a request was discarded this way, the transaction's failure is
371 /// an integrity violation, not a timeout; over a reliable transport it fails at once.
372 pub fn check_response(
373 &self,
374 response: &Message,
375 validator: &Validator<'_>,
376 crypto: &dyn RTCCrypto,
377 ) -> std::result::Result<LongTermResponse, Rejection> {
378 let unauthenticated = validator.unauthenticated(response);
379 if let Ok(view) = &unauthenticated
380 && response.typ.class == CLASS_ERROR_RESPONSE
381 && let Some(code) = error_code_of(view)
382 && (code == CODE_UNAUTHORIZED || code == CODE_STALE_NONCE)
383 {
384 return unauthenticated.map(LongTermResponse::Challenge);
385 }
386 // Before any challenge the client has no key: nothing can be authenticated.
387 let (Some(session), Some(algorithm)) = (&self.session, self.integrity()) else {
388 return Err(unauthenticated.err().unwrap_or(Rejection::IntegrityMissing));
389 };
390 let valid =
391 validator.authenticate_with(response, algorithm, session.key.as_ref(), crypto)?;
392 // "For all other responses": a cookie that announces PASSWORD-ALGORITHMS on a
393 // response without the attribute means the response was tampered with.
394 if let Ok(nonce) = TextAttribute::get_from_as(&valid, ATTR_NONCE)
395 && SecurityFeatures::from_nonce(&nonce.text).is_some_and(|f| f.password_algorithms())
396 && !valid.contains(ATTR_PASSWORD_ALGORITHMS)
397 {
398 return Err(Rejection::IntegrityMissing);
399 }
400 Ok(LongTermResponse::Authenticated(valid))
401 }
402}
403
404/// The code of the ERROR-CODE attribute of `m`, when it is an error response that has one.
405fn error_code_of(m: &Message) -> Option<ErrorCode> {
406 if m.typ.class != CLASS_ERROR_RESPONSE {
407 return None;
408 }
409 let mut code = ErrorCodeAttribute::default();
410 code.get_from(m).ok()?;
411 Some(code.code)
412}
413
414/// Whether `request` carried credentials: an integrity attribute (RFC 8489 section 9.2.4).
415fn request_was_authenticated(request: &Message) -> bool {
416 request.contains(ATTR_MESSAGE_INTEGRITY) || request.contains(ATTR_MESSAGE_INTEGRITY_SHA256)
417}
418
419/// The authentication attributes of a request, as a [`Setter`]: see
420/// [`LongTermCredentials::setter`].
421pub struct LongTermAuthentication<'a> {
422 credentials: &'a LongTermCredentials,
423 crypto: &'a dyn RTCCrypto,
424}
425
426impl Setter for LongTermAuthentication<'_> {
427 fn add_to(&self, m: &mut Message) -> Result<()> {
428 let Some(session) = &self.credentials.session else {
429 return Ok(());
430 };
431 match &session.userhash {
432 Some(userhash) => userhash.add_to(m)?,
433 None => {
434 TextAttribute::new(ATTR_USERNAME, self.credentials.username.clone()).add_to(m)?
435 }
436 }
437 TextAttribute::new(ATTR_REALM, session.realm.clone()).add_to(m)?;
438 TextAttribute::new(ATTR_NONCE, session.nonce.clone()).add_to(m)?;
439 if let Some(algorithms) = &session.algorithms {
440 algorithms.add_to(m)?;
441 }
442 if let Some(algorithm) = &session.algorithm {
443 algorithm.add_to(m)?;
444 }
445 if session.algorithms.is_some() {
446 MessageIntegritySha256::new_raw(session.key.as_ref().to_vec(), self.crypto).add_to(m)
447 } else {
448 MessageIntegrity::new_raw_integrity_with_provider(
449 session.key.as_ref().to_vec(),
450 self.crypto,
451 )
452 .add_to(m)
453 }
454 }
455}