use std::sync::Arc;
use crypto::{RTCCrypto, SecretVec};
use shared::error::Result;
use stun::attributes::{ATTR_MESSAGE_INTEGRITY, ATTR_MESSAGE_INTEGRITY_SHA256, ATTR_REALM};
use stun::error_code::{CODE_STALE_NONCE, 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::password_algorithm::{
PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256, PasswordAlgorithms,
};
use stun::validated::{Rejection, ValidatedMessage, Validator};
pub(crate) struct Login {
pub(crate) username: String,
pub(crate) password: String,
pub(crate) password_algorithms: Vec<u16>,
}
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 is_established(&self) -> bool {
self.session.is_some()
}
#[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));
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<ValidatedMessage, Rejection> {
let Some(session) = &self.session else {
return validator.unauthenticated(response);
};
match session
.credentials
.check_response(response, validator, crypto)?
{
LongTermResponse::Authenticated(valid) => Ok(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 {
Ok(unsigned)
}
}
}
}
}
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![],
});
Arc::new(
Self::new(login)
.challenged(&Message::new(), &challenge, provider.crypto())
.expect("the challenge is taken"),
)
}
}