#[cfg(test)]
mod long_term_test;
use crate::attributes::*;
use crate::error_code::{CODE_STALE_NONCE, CODE_UNAUTHORIZED, ErrorCode, ErrorCodeAttribute};
use crate::integrity::{
IntegrityAlgorithm, MessageIntegrity, MessageIntegritySha256, long_term_key,
};
use crate::message::*;
use crate::nonce_cookie::SecurityFeatures;
use crate::opaque::opaque_string;
use crate::password_algorithm::{
PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256, PasswordAlgorithm, PasswordAlgorithms,
};
use crate::textattrs::TextAttribute;
use crate::userhash::Userhash;
use crate::validated::{Rejection, ValidatedMessage, Validator};
use crypto::{RTCCrypto, SecretVec};
use shared::error::*;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChallengeError {
NotAChallenge,
Incomplete,
BidDown,
NoSupportedAlgorithm,
CredentialsRejected,
Unusable(String),
}
impl fmt::Display for ChallengeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAChallenge => write!(f, "not a 401 or 438 error response"),
Self::Incomplete => write!(f, "the challenge has no REALM or no NONCE"),
Self::BidDown => write!(
f,
"the nonce cookie announces PASSWORD-ALGORITHMS and the response has none"
),
Self::NoSupportedAlgorithm => {
write!(f, "the server offers no supported password algorithm")
}
Self::CredentialsRejected => write!(f, "the credentials were rejected"),
Self::Unusable(reason) => write!(f, "the credentials cannot be used: {reason}"),
}
}
}
impl std::error::Error for ChallengeError {}
#[derive(Debug, Clone, PartialEq)]
pub enum LongTermResponse {
Authenticated(ValidatedMessage),
Challenge(ValidatedMessage),
}
struct Session {
realm: String,
nonce: String,
algorithms: Option<PasswordAlgorithms>,
algorithm: Option<PasswordAlgorithm>,
userhash: Option<Userhash>,
key: SecretVec,
}
pub struct LongTermCredentials {
username: String,
password: SecretVec,
supported: Vec<u16>,
session: Option<Session>,
anonymity_required: bool,
}
impl fmt::Debug for LongTermCredentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LongTermCredentials")
.field("username", &self.username)
.field("password", &"[REDACTED]")
.field("realm", &self.realm())
.field("nonce", &self.nonce())
.field("password_algorithm", &self.password_algorithm())
.field("uses_userhash", &self.uses_userhash())
.finish()
}
}
impl LongTermCredentials {
pub fn new(username: &str, password: &str) -> Result<Self> {
Ok(Self {
username: opaque_string(username)?.into_owned(),
password: SecretVec::new(opaque_string(password)?.into_owned().into_bytes()),
supported: vec![PASSWORD_ALGORITHM_SHA256, PASSWORD_ALGORITHM_MD5],
session: None,
anonymity_required: false,
})
}
#[must_use]
pub fn with_username_anonymity_required(mut self, required: bool) -> Self {
self.anonymity_required = required;
self
}
#[must_use]
pub fn with_password_algorithms(mut self, supported: &[u16]) -> Self {
self.supported = supported
.iter()
.copied()
.filter(|a| [PASSWORD_ALGORITHM_SHA256, PASSWORD_ALGORITHM_MD5].contains(a))
.collect();
self
}
#[must_use]
pub fn username(&self) -> &str {
&self.username
}
#[must_use]
pub fn realm(&self) -> Option<&str> {
self.session.as_ref().map(|s| s.realm.as_str())
}
#[must_use]
pub fn nonce(&self) -> Option<&str> {
self.session.as_ref().map(|s| s.nonce.as_str())
}
#[must_use]
pub fn password_algorithm(&self) -> Option<&PasswordAlgorithm> {
self.session.as_ref().and_then(|s| s.algorithm.as_ref())
}
#[must_use]
pub fn uses_userhash(&self) -> bool {
self.session.as_ref().is_some_and(|s| s.userhash.is_some())
}
#[must_use]
pub fn integrity(&self) -> Option<IntegrityAlgorithm> {
self.session.as_ref().map(|s| {
if s.algorithms.is_some() {
IntegrityAlgorithm::Sha256
} else {
IntegrityAlgorithm::Sha1
}
})
}
pub fn reset(&mut self) {
self.session = None;
}
pub fn challenge(
&mut self,
request: &Message,
response: &Message,
crypto: &dyn RTCCrypto,
) -> std::result::Result<(), ChallengeError> {
let response = Validator::new()
.unauthenticated(response)
.map_err(|_| ChallengeError::NotAChallenge)?;
let code = error_code_of(&response).ok_or(ChallengeError::NotAChallenge)?;
if code != CODE_UNAUTHORIZED && code != CODE_STALE_NONCE {
return Err(ChallengeError::NotAChallenge);
}
let realm = TextAttribute::get_from_as(&response, ATTR_REALM)
.map_err(|_| ChallengeError::Incomplete)?
.text;
let nonce = TextAttribute::get_from_as(&response, ATTR_NONCE)
.map_err(|_| ChallengeError::Incomplete)?
.text;
if realm.is_empty() || nonce.is_empty() {
return Err(ChallengeError::Incomplete);
}
let realm = opaque_string(&realm)
.map_err(|e| ChallengeError::Unusable(e.to_string()))?
.into_owned();
let features = SecurityFeatures::from_nonce(&nonce).unwrap_or(SecurityFeatures::NONE);
let mut algorithms = PasswordAlgorithms::default();
let algorithms = match algorithms.get_from(&response) {
Ok(()) => Some(algorithms),
Err(Error::ErrAttributeNotFound) => None,
Err(_) => return Err(ChallengeError::Incomplete),
};
if features.password_algorithms() && algorithms.is_none() {
return Err(ChallengeError::BidDown);
}
let algorithm = match &algorithms {
Some(list) => Some(
list.first_supported(&self.supported)
.cloned()
.ok_or(ChallengeError::NoSupportedAlgorithm)?,
),
None if self.supported.contains(&PASSWORD_ALGORITHM_MD5) => None,
None => return Err(ChallengeError::NoSupportedAlgorithm),
};
if code == CODE_UNAUTHORIZED
&& let Some(session) = &self.session
&& request_was_authenticated(request)
&& session.realm == realm
&& session.algorithm == algorithm
&& session.userhash.is_some() == features.username_anonymity()
{
return Err(ChallengeError::CredentialsRejected);
}
if self.anonymity_required && !features.username_anonymity() {
return Err(ChallengeError::Unusable(
"the server offers no USERHASH and the user name may not be sent in the clear"
.to_owned(),
));
}
let userhash = if features.username_anonymity() {
Some(
Userhash::new(&self.username, &realm, crypto)
.map_err(|e| ChallengeError::Unusable(e.to_string()))?,
)
} else {
None
};
let password = std::str::from_utf8(self.password.as_ref())
.map_err(|e| ChallengeError::Unusable(e.to_string()))?;
let key = long_term_key(
algorithm
.as_ref()
.map_or(PASSWORD_ALGORITHM_MD5, |a| a.algorithm),
&self.username,
&realm,
password,
crypto,
)
.map_err(|e| ChallengeError::Unusable(e.to_string()))?;
self.session = Some(Session {
realm,
nonce,
algorithms,
algorithm,
userhash,
key: SecretVec::new(key),
});
Ok(())
}
#[must_use]
pub fn setter<'a>(&'a self, crypto: &'a dyn RTCCrypto) -> LongTermAuthentication<'a> {
LongTermAuthentication {
credentials: self,
crypto,
}
}
pub fn check_response(
&self,
response: &Message,
validator: &Validator<'_>,
crypto: &dyn RTCCrypto,
) -> std::result::Result<LongTermResponse, Rejection> {
let unauthenticated = validator.unauthenticated(response);
if let Ok(view) = &unauthenticated
&& response.typ.class == CLASS_ERROR_RESPONSE
&& let Some(code) = error_code_of(view)
&& (code == CODE_UNAUTHORIZED || code == CODE_STALE_NONCE)
{
return unauthenticated.map(LongTermResponse::Challenge);
}
let (Some(session), Some(algorithm)) = (&self.session, self.integrity()) else {
return Err(unauthenticated.err().unwrap_or(Rejection::IntegrityMissing));
};
let valid =
validator.authenticate_with(response, algorithm, session.key.as_ref(), crypto)?;
if let Ok(nonce) = TextAttribute::get_from_as(&valid, ATTR_NONCE)
&& SecurityFeatures::from_nonce(&nonce.text).is_some_and(|f| f.password_algorithms())
&& !valid.contains(ATTR_PASSWORD_ALGORITHMS)
{
return Err(Rejection::IntegrityMissing);
}
Ok(LongTermResponse::Authenticated(valid))
}
}
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 request_was_authenticated(request: &Message) -> bool {
request.contains(ATTR_MESSAGE_INTEGRITY) || request.contains(ATTR_MESSAGE_INTEGRITY_SHA256)
}
pub struct LongTermAuthentication<'a> {
credentials: &'a LongTermCredentials,
crypto: &'a dyn RTCCrypto,
}
impl Setter for LongTermAuthentication<'_> {
fn add_to(&self, m: &mut Message) -> Result<()> {
let Some(session) = &self.credentials.session else {
return Ok(());
};
match &session.userhash {
Some(userhash) => userhash.add_to(m)?,
None => {
TextAttribute::new(ATTR_USERNAME, self.credentials.username.clone()).add_to(m)?
}
}
TextAttribute::new(ATTR_REALM, session.realm.clone()).add_to(m)?;
TextAttribute::new(ATTR_NONCE, session.nonce.clone()).add_to(m)?;
if let Some(algorithms) = &session.algorithms {
algorithms.add_to(m)?;
}
if let Some(algorithm) = &session.algorithm {
algorithm.add_to(m)?;
}
if session.algorithms.is_some() {
MessageIntegritySha256::new_raw(session.key.as_ref().to_vec(), self.crypto).add_to(m)
} else {
MessageIntegrity::new_raw_integrity_with_provider(
session.key.as_ref().to_vec(),
self.crypto,
)
.add_to(m)
}
}
}