From e68357719e471eb5e84292488737b44140ef25da Mon Sep 17 00:00:00 2001 From: Andrey Mnatsakanov Date: Sun, 8 Nov 2026 10:05:33 +0100 Subject: [PATCH] fix(turn): send the authenticated Allocate retry under a fresh random id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The retry after a 401 went out under the anonymous request's id with its last byte bumped. RFC 8489 §6 wants every new transaction under a fresh, cryptographically random 96-bit id, and the retry is a new transaction. The risk was small — whoever could predict the id had seen the first request — but the rule also forced allocate() to foretell its own retry, and #281 had to special-case the timeout and the error exit so that they named that foretold id rather than the one on the wire. The retry now carries TransactionId::new(), as every other request does, and the transaction remembers which allocation it belongs to: TransactionType::AllocateRequest holds the id allocate() returned next to the nonce, and the response, error and timeout handlers report that id. allocate() returns the anonymous request's own id, so an error or a timeout on the first request names the wire id as it is, and authenticated_allocate_id() and both special cases go away. Nothing visible to a caller changes: every event about an allocation still names the id allocate() handed out, which is what webrtc's relayer and the examples match on. The test drives a 401 with nonce and realm, reads the retry off the wire and asserts its id differs from the anonymous one in more than its last byte; then answers it with a success, with a 403, and with nothing, and asserts each event names the id allocate() returned. The #281 tests pass unchanged. Follow-up to #281, as discussed there. --- rtc-turn/src/client/client_test.rs | 159 ++++++++++++++++++++++++++++- rtc-turn/src/client/mod.rs | 52 +++++----- rtc-turn/src/client/transaction.rs | 35 +++---- 3 files changed, 195 insertions(+), 51 deletions(-) diff --git a/rtc-turn/src/client/client_test.rs b/rtc-turn/src/client/client_test.rs index ced3358fe..4e1b2db18 100644 --- a/rtc-turn/src/client/client_test.rs +++ b/rtc-turn/src/client/client_test.rs @@ -321,7 +321,10 @@ fn test_allocation_refresh_interval_cap_is_applied() -> Result<()> { client.handle_allocate_response( base, response, - TransactionType::AllocateRequest(Nonce::new(ATTR_NONCE, "nonce".to_owned())), + TransactionType::AllocateRequest { + nonce: Nonce::new(ATTR_NONCE, "nonce".to_owned()), + allocation: TransactionId::new(), + }, )?; for expected_secs in [30, 60, 90, 120, 150, 180] { @@ -688,7 +691,10 @@ fn test_zero_lifetime_allocate_response_is_an_error() -> Result<()> { client.handle_allocate_response( base, res, - TransactionType::AllocateRequest(Nonce::new(ATTR_NONCE, "nonce".to_owned())), + TransactionType::AllocateRequest { + nonce: Nonce::new(ATTR_NONCE, "nonce".to_owned()), + allocation: TransactionId::new(), + }, )?; assert!( @@ -933,3 +939,152 @@ fn test_an_error_reply_without_a_nonce_is_reported_under_the_id_allocate_returne } Ok(()) } + +/// The authenticated retry after a 401 is a new transaction, and RFC 8489 §6 wants every new +/// transaction under a fresh, cryptographically random 96-bit id. It used to go out under the +/// anonymous request's id with its last byte bumped — predictable, and the only reason +/// `allocate()` had to foretell its own retry. The retry is random now and the client remembers +/// which allocation it belongs to, so a response, an error and a timeout to the retry still +/// name the id [`Client::allocate`] returned: what a caller matches on never changes. +#[test] +fn test_the_authenticated_retry_carries_a_fresh_id_and_reports_under_the_one_allocate_returned() +-> Result<()> { + use stun::error_code::{CODE_FORBIDDEN, CODE_UNAUTHORIZED}; + + #[derive(Debug, Clone, Copy)] + enum Answer { + Success, + Error, + Nothing, + } + for answer in [Answer::Success, Answer::Error, Answer::Nothing] { + let start = Instant::now(); + let local_addr: SocketAddr = "127.0.0.1:50000".parse().unwrap(); + let server_addr: SocketAddr = "127.0.0.1:3478".parse().unwrap(); + let mut client = Client::new( + ClientConfig { + turn_serv_addr: server_addr.to_string(), + local_addr, + transport_protocol: TransportProtocol::UDP, + username: "user".to_owned(), + password: "pass".to_owned(), + ..Default::default() + }, + test_crypto_provider(), + )?; + let from_server = |message: &Message| TransportMessage { + now: start, + transport: TransportContext { + local_addr, + peer_addr: server_addr, + transport_protocol: TransportProtocol::UDP, + ecn: None, + }, + message: BytesMut::from(&message.raw[..]), + }; + let decode = |transmit: TransportMessage| -> Result { + let mut sent = Message::new(); + sent.raw = transmit.message.to_vec(); + sent.decode()?; + Ok(sent) + }; + + let tid = client.allocate(start)?; + let anonymous = decode( + client + .poll_write() + .expect("the anonymous Allocate goes out"), + )?; + + // The server wants credentials. + let mut challenge = Message::new(); + challenge.build(&[ + Box::new(anonymous.transaction_id), + Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE)), + Box::new(ErrorCodeAttribute { + code: CODE_UNAUTHORIZED, + reason: b"Unauthorized".to_vec(), + }), + Box::new(Nonce::new(ATTR_NONCE, "nonce".to_owned())), + Box::new(Realm::new(ATTR_REALM, "realm".to_owned())), + Box::new(FINGERPRINT), + ])?; + client.handle_read(from_server(&challenge))?; + + let retry = decode( + client + .poll_write() + .expect("the authenticated retry goes out"), + )?; + assert!( + retry.contains(ATTR_MESSAGE_INTEGRITY) && retry.contains(ATTR_NONCE), + "{answer:?}: the retry is the authenticated Allocate" + ); + assert_ne!( + retry.transaction_id, anonymous.transaction_id, + "{answer:?}: a new transaction, a new id" + ); + assert_ne!( + retry.transaction_id.0[..TRANSACTION_ID_SIZE - 1], + anonymous.transaction_id.0[..TRANSACTION_ID_SIZE - 1], + "{answer:?}: a fresh random id, not the anonymous one with its last byte bumped" + ); + + // Whatever becomes of the retry is reported under the id the caller holds. + let reported = match answer { + Answer::Success => { + let mut success = Message::new(); + success.build(&[ + Box::new(retry.transaction_id), + Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_SUCCESS_RESPONSE)), + Box::new(RelayedAddress { + ip: "127.0.0.1".parse().unwrap(), + port: 40000, + }), + Box::new(Lifetime(Duration::from_secs(600))), + Box::new(FINGERPRINT), + ])?; + client.handle_read(from_server(&success))?; + match client.poll_event() { + Some(Event::AllocateResponse(id, _)) => id, + other => panic!("{answer:?}: expected AllocateResponse, got {other:?}"), + } + } + Answer::Error => { + let mut refusal = Message::new(); + refusal.build(&[ + Box::new(retry.transaction_id), + Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE)), + Box::new(ErrorCodeAttribute { + code: CODE_FORBIDDEN, + reason: b"Forbidden".to_vec(), + }), + Box::new(FINGERPRINT), + ])?; + client.handle_read(from_server(&refusal))?; + match client.poll_event() { + Some(Event::AllocateError(id, _)) => id, + other => panic!("{answer:?}: expected AllocateError, got {other:?}"), + } + } + Answer::Nothing => { + let mut timed_out = None; + while let Some(deadline) = client.poll_timeout() { + client.handle_timeout(deadline)?; + while client.poll_write().is_some() {} + while let Some(event) = client.poll_event() { + if let Event::TransactionTimeout(id) = event { + timed_out = Some(id); + } + } + } + timed_out.expect("a retry nobody answers times out") + } + }; + assert_eq!( + reported, tid, + "{answer:?}: the event must name the allocation its caller knows" + ); + } + Ok(()) +} diff --git a/rtc-turn/src/client/mod.rs b/rtc-turn/src/client/mod.rs index 5dd0180cc..912acb1b7 100644 --- a/rtc-turn/src/client/mod.rs +++ b/rtc-turn/src/client/mod.rs @@ -605,13 +605,15 @@ impl Client { ])?; debug!("client.Allocate call PerformTransaction 1"); - let tid = self.perform_transaction( + // The anonymous request's own id is what the caller gets, and what every event about + // the allocation names — the retry after a 401 goes out under a fresh id but reports + // under this one. + Ok(self.perform_transaction( now, &msg, self.turn_server_addr()?, TransactionType::AllocateAttempt, - ); - Ok(authenticated_allocate_id(tid)) + )) } fn handle_allocate_response( @@ -622,25 +624,21 @@ impl Client { ) -> Result<()> { match allocate_state { TransactionType::AllocateAttempt => { - // Anonymous allocate failed, trying to authenticate. Whatever is reported about - // it from here on names the id allocate() handed out, as the response does. + // Anonymous allocate failed, trying to authenticate. The anonymous request's id + // is the one allocate() handed out, so an error here names it as it is. let nonce = match Nonce::get_from_as(&response, ATTR_NONCE) { Ok(nonce) => nonce, Err(err) => { - self.events.push_back(Event::AllocateError( - authenticated_allocate_id(response.transaction_id), - err, - )); + self.events + .push_back(Event::AllocateError(response.transaction_id, err)); return Ok(()); } }; self.realm = match Realm::get_from_as(&response, ATTR_REALM) { Ok(realm) => realm, Err(err) => { - self.events.push_back(Event::AllocateError( - authenticated_allocate_id(response.transaction_id), - err, - )); + self.events + .push_back(Event::AllocateError(response.transaction_id, err)); return Ok(()); } }; @@ -654,13 +652,11 @@ impl Client { let mut msg = Message::new(); - // make it same as allocate() return value so that client can retrieve it - // from Event::AllocateResponse - let tid = authenticated_allocate_id(response.transaction_id); - - // Trying to authorize. + // A new transaction under a fresh random id (RFC 8489 §6). The transaction + // remembers the id allocate() returned, so the caller still hears about this + // allocation under the one it holds. msg.build(&[ - Box::new(tid), + Box::new(TransactionId::new()), Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_REQUEST)), Box::new(RequestedTransport { // Always a UDP relay, however the server is reached: REQUESTED-TRANSPORT @@ -680,10 +676,13 @@ impl Client { now, &msg, self.turn_server_addr()?, - TransactionType::AllocateRequest(nonce), + TransactionType::AllocateRequest { + nonce, + allocation: response.transaction_id, + }, ); } - TransactionType::AllocateRequest(nonce) => { + TransactionType::AllocateRequest { nonce, allocation } => { if response.typ.class == CLASS_ERROR_RESPONSE { let mut code = ErrorCodeAttribute::default(); let err = if code.get_from(&response).is_err() { @@ -691,8 +690,7 @@ impl Client { } else { Error::Other(format!("{} (error {})", response.typ, code)) }; - self.events - .push_back(Event::AllocateError(response.transaction_id, err)); + self.events.push_back(Event::AllocateError(allocation, err)); return Ok(()); } @@ -719,7 +717,7 @@ impl Client { // [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862). if lifetime.0.is_zero() { self.events.push_back(Event::AllocateError( - response.transaction_id, + allocation, Error::Other( "Allocate success response carried LIFETIME=0; RFC 5766 §6.2 \ requires at least the default lifetime" @@ -745,10 +743,8 @@ impl Client { self.allocation_refresh_interval_cap, ), ); - self.events.push_back(Event::AllocateResponse( - response.transaction_id, - relayed_addr, - )); + self.events + .push_back(Event::AllocateResponse(allocation, relayed_addr)); } _ => {} } diff --git a/rtc-turn/src/client/transaction.rs b/rtc-turn/src/client/transaction.rs index bfff2a0ef..bab472dc2 100644 --- a/rtc-turn/src/client/transaction.rs +++ b/rtc-turn/src/client/transaction.rs @@ -17,21 +17,18 @@ const MAX_RTX_COUNT: u16 = 7; // total 7 requests (Rc) /// this is how long the client waits for its answer. const RELIABLE_TRANSACTION_TIMEOUT: Duration = Duration::from_millis(39_500); -/// The id the authenticated retry of an Allocate uses: the anonymous request's, one on. -/// -/// [`Client::allocate`](crate::client::Client::allocate) hands this one to its caller, -/// because the anonymous request is answered with 401 and it is the retry that carries the -/// allocation. Everything the caller is told about that allocation names it. -pub(crate) fn authenticated_allocate_id(attempt: TransactionId) -> TransactionId { - let mut tid = attempt; - tid.0[TRANSACTION_ID_SIZE - 1] = tid.0[TRANSACTION_ID_SIZE - 1].wrapping_add(1); - tid -} - pub(crate) enum TransactionType { BindingRequest, + /// The anonymous Allocate, under the id [`Client::allocate`](crate::client::Client::allocate) + /// hands its caller. AllocateAttempt, - AllocateRequest(TextAttribute), + /// The authenticated retry after a 401. It is a new transaction under a fresh id (RFC 8489 + /// §6), so it remembers which allocation it belongs to: `allocation` is the id `allocate()` + /// returned, and every event about this request names it, not the id on the wire. + AllocateRequest { + nonce: TextAttribute, + allocation: TransactionId, + }, CreatePermissionRequest(RelayedAddr, Option), RefreshRequest(RelayedAddr), ChannelBindRequest(RelayedAddr, SocketAddr), @@ -193,15 +190,11 @@ impl TransactionMap { for key in keys { let exhausted = self.tr_map.remove(&key); - // An Allocate nobody answers is the one case where the request on the wire and - // the allocation its caller knows have different ids. - let timed_out = if matches!( - exhausted.as_ref().map(|tr| &tr.transaction_type), - Some(TransactionType::AllocateAttempt) - ) { - authenticated_allocate_id(key) - } else { - key + // The authenticated Allocate retry is the one request whose caller knows it by + // another id than the one on the wire. + let timed_out = match exhausted.as_ref().map(|tr| &tr.transaction_type) { + Some(TransactionType::AllocateRequest { allocation, .. }) => *allocation, + _ => key, }; self.events.push_back(Event::TransactionTimeout(timed_out)); }