use std::sync::Arc;
use crypto::{RTCCrypto, SecretVec};
use shared::error::Result;
use stun::attributes::{
ATTR_MESSAGE_INTEGRITY, ATTR_MESSAGE_INTEGRITY_SHA256, ATTR_NONCE, ATTR_PASSWORD_ALGORITHMS,
ATTR_REALM,
};
use stun::error_code::{
CODE_BAD_REQUEST, CODE_STALE_NONCE, CODE_UNAUTHORIZED, ErrorCode, ErrorCodeAttribute,
};
use stun::integrity::long_term_key;
use stun::long_term::{ChallengeError, LongTermCredentials, LongTermResponse};
use stun::message::{CLASS_ERROR_RESPONSE, Getter, Message, Setter};
use stun::nonce_cookie::SecurityFeatures;
use stun::password_algorithm::{
PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256, PasswordAlgorithms,
};
use stun::textattrs::TextAttribute;
use stun::validated::{Rejection, ValidatedMessage, Validator};
pub(crate) struct Login {
pub(crate) username: String,
pub(crate) password: String,
pub(crate) password_algorithms: Vec<u16>,
pub(crate) username_anonymity_required: bool,
}
struct Session {
credentials: LongTermCredentials,
challenge: Message,
key: SecretVec,
}
pub(crate) struct Credential {
login: Arc<Login>,
session: Option<Session>,
}
impl Credential {
pub(crate) fn new(login: Arc<Login>) -> Self {
Self {
login,
session: None,
}
}
pub(crate) fn has_login(&self) -> bool {
!self.login.username.is_empty() || !self.login.password.is_empty()
}
pub(crate) fn is_established(&self) -> bool {
self.session.is_some()
}
pub(crate) fn is_for(&self, login: &Login) -> bool {
self.login.username == login.username
&& self.login.password == login.password
&& self.login.password_algorithms == login.password_algorithms
}
pub(crate) fn has_login_of(&self, other: &Credential) -> bool {
self.is_for(&other.login)
}
#[cfg(test)]
pub(crate) fn nonce(&self) -> Option<&str> {
self.session.as_ref()?.credentials.nonce()
}
fn build(
login: &Arc<Login>,
earlier: Option<&Message>,
new: Option<(&Message, &Message)>,
crypto: &dyn RTCCrypto,
) -> std::result::Result<Self, ChallengeError> {
let unusable = |err: shared::error::Error| ChallengeError::Unusable(err.to_string());
let new = match new {
Some((request, response)) => Some((
request,
Validator::new()
.unauthenticated(response)
.map_err(|_| ChallengeError::NotAChallenge)?
.into_message(),
)),
None => None,
};
let Some(latest) = new.as_ref().map(|(_, response)| response).or(earlier) else {
return Ok(Self::new(login.clone()));
};
let mut credentials = LongTermCredentials::new(&login.username, &login.password)
.map_err(unusable)?
.with_password_algorithms(&accepted_algorithms(login, latest))
.with_username_anonymity_required(login.username_anonymity_required);
let mut challenge = None;
if let Some((request, mut response)) = new {
if let Some(earlier) = earlier {
let _ = credentials.challenge(&Message::new(), earlier, crypto);
}
if !response.contains(ATTR_REALM)
&& is_stale_nonce(&response)
&& let Some(realm) = credentials.realm()
{
let realm = realm.to_owned();
response.add(ATTR_REALM, realm.as_bytes());
}
credentials.challenge(request, &response, crypto)?;
challenge = Some(response);
} else if let Some(earlier) = earlier {
credentials.challenge(&Message::new(), earlier, crypto)?;
challenge = Some(earlier.clone());
}
let Some(challenge) = challenge else {
return Ok(Self::new(login.clone()));
};
let key = long_term_key(
credentials
.password_algorithm()
.map_or(PASSWORD_ALGORITHM_MD5, |a| a.algorithm),
credentials.username(),
credentials.realm().unwrap_or_default(),
&login.password,
crypto,
)
.map_err(unusable)?;
Ok(Self {
login: login.clone(),
session: Some(Session {
credentials,
challenge,
key: SecretVec::new(key),
}),
})
}
pub(crate) fn challenged(
&self,
request: &Message,
response: &Message,
crypto: &dyn RTCCrypto,
) -> std::result::Result<Self, ChallengeError> {
Self::build(
&self.login,
self.session.as_ref().map(|s| &s.challenge),
Some((request, response)),
crypto,
)
}
pub(crate) fn with_login(&self, login: Arc<Login>, crypto: &dyn RTCCrypto) -> Result<Self> {
Self::build(
&login,
self.session.as_ref().map(|s| &s.challenge),
None,
crypto,
)
.map_err(|err| shared::error::Error::Other(err.to_string()))
}
pub(crate) fn setter<'a>(&'a self, crypto: &'a dyn RTCCrypto) -> Option<Box<dyn Setter + 'a>> {
let session = self.session.as_ref()?;
Some(Box::new(session.credentials.setter(crypto)))
}
pub(crate) fn check_response(
&self,
response: &Message,
validator: &Validator<'_>,
crypto: &dyn RTCCrypto,
) -> std::result::Result<Checked, Rejection> {
if is_unsigned_bad_request(response) {
return Ok(Checked::NeverReceived);
}
let Some(session) = &self.session else {
let valid = validator.unauthenticated(response)?;
if !is_challenge(&valid) && promises_password_algorithms_it_lacks(&valid) {
return Ok(Checked::NeverReceived);
}
return Ok(Checked::Valid(valid));
};
let valid = match session
.credentials
.check_response(response, validator, crypto)?
{
LongTermResponse::Authenticated(valid) => valid,
LongTermResponse::Challenge(unsigned) => {
if response.contains(ATTR_MESSAGE_INTEGRITY)
|| response.contains(ATTR_MESSAGE_INTEGRITY_SHA256)
{
validator.authenticate(response, session.key.as_ref(), crypto)?
} else {
unsigned
}
}
};
Ok(Checked::Valid(valid))
}
}
pub(crate) enum Checked {
Valid(ValidatedMessage),
NeverReceived,
}
fn error_code_of(m: &Message) -> Option<ErrorCode> {
if m.typ.class != CLASS_ERROR_RESPONSE {
return None;
}
let mut code = ErrorCodeAttribute::default();
code.get_from(m).ok()?;
Some(code.code)
}
fn is_unsigned_bad_request(response: &Message) -> bool {
error_code_of(response) == Some(CODE_BAD_REQUEST)
&& !response.contains(ATTR_MESSAGE_INTEGRITY)
&& !response.contains(ATTR_MESSAGE_INTEGRITY_SHA256)
}
fn is_challenge(response: &Message) -> bool {
matches!(error_code_of(response), Some(c) if c == CODE_UNAUTHORIZED || c == CODE_STALE_NONCE)
}
fn promises_password_algorithms_it_lacks(response: &Message) -> bool {
TextAttribute::get_from_as(response, ATTR_NONCE).is_ok_and(|nonce| {
SecurityFeatures::from_nonce(&nonce.text).is_some_and(|f| f.password_algorithms())
}) && !response.contains(ATTR_PASSWORD_ALGORITHMS)
}
fn accepted_algorithms(login: &Login, challenge: &Message) -> Vec<u16> {
let allowed = if login.password_algorithms.is_empty() {
vec![PASSWORD_ALGORITHM_SHA256, PASSWORD_ALGORITHM_MD5]
} else {
login.password_algorithms.clone()
};
let mut offered = PasswordAlgorithms::default();
if allowed.contains(&PASSWORD_ALGORITHM_SHA256)
&& offered.get_from(challenge).is_ok()
&& offered
.0
.iter()
.any(|a| a.algorithm == PASSWORD_ALGORITHM_SHA256)
{
vec![PASSWORD_ALGORITHM_SHA256]
} else {
allowed
}
}
fn is_stale_nonce(m: &Message) -> bool {
let mut code = ErrorCodeAttribute::default();
m.typ.class == CLASS_ERROR_RESPONSE && code.get_from(m).is_ok() && code.code == CODE_STALE_NONCE
}
#[cfg(test)]
impl Credential {
pub(crate) fn established() -> Arc<Self> {
use stun::error_code::CODE_UNAUTHORIZED;
use stun::message::{METHOD_ALLOCATE, MessageType, TransactionId};
use stun::textattrs::TextAttribute;
let provider = crypto::default_provider().expect("a built-in crypto provider");
let mut challenge = Message::new();
challenge
.build(&[
Box::new(TransactionId::new()),
Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE)),
Box::new(ErrorCodeAttribute {
code: CODE_UNAUTHORIZED,
reason: b"Unauthorized".to_vec(),
}),
Box::new(TextAttribute::new(
stun::attributes::ATTR_NONCE,
"nonce".to_owned(),
)),
Box::new(TextAttribute::new(ATTR_REALM, "realm".to_owned())),
])
.expect("the challenge builds");
let login = Arc::new(Login {
username: "user".to_owned(),
password: "pass".to_owned(),
password_algorithms: vec![],
username_anonymity_required: false,
});
Arc::new(
Self::new(login)
.challenged(&Message::new(), &challenge, provider.crypto())
.expect("the challenge is taken"),
)
}
}