Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 157 additions & 2 deletions rtc-turn/src/client/client_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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<BytesMut>| -> Result<Message> {
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(())
}
52 changes: 24 additions & 28 deletions rtc-turn/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(());
}
};
Expand All @@ -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
Expand All @@ -680,19 +676,21 @@ 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() {
Error::Other(format!("{}", response.typ))
} 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(());
}

Expand All @@ -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"
Expand All @@ -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));
}
_ => {}
}
Expand Down
35 changes: 14 additions & 21 deletions rtc-turn/src/client/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SocketAddr>),
RefreshRequest(RelayedAddr),
ChannelBindRequest(RelayedAddr, SocketAddr),
Expand Down Expand Up @@ -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));
}
Expand Down
Loading