#[cfg(test)]
mod validated_test;
use crate::attributes::*;
use crate::error_code::CODE_UNKNOWN_ATTRIBUTE;
use crate::fingerprint::FINGERPRINT;
use crate::integrity::{
IntegrityAlgorithm, MESSAGE_INTEGRITY_SHA256_MIN_SIZE, MESSAGE_INTEGRITY_SHA256_SIZE,
check_integrity,
};
use crate::message::*;
use crate::uattrs::UnknownAttributes;
use crypto::RTCCrypto;
use shared::error::*;
use std::fmt;
use std::ops::Deref;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Rejection {
FingerprintMissing,
FingerprintMismatch,
IntegrityMissing,
IntegrityMismatch,
UnknownAttributes(Vec<AttrType>),
Crypto(String),
}
impl fmt::Display for Rejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FingerprintMissing => write!(f, "FINGERPRINT is missing"),
Self::FingerprintMismatch => write!(f, "FINGERPRINT does not match"),
Self::IntegrityMissing => write!(f, "the integrity attribute is missing"),
Self::IntegrityMismatch => write!(f, "the integrity attribute does not match"),
Self::UnknownAttributes(unknown) => write!(
f,
"unknown comprehension-required attributes: {}",
UnknownAttributes(unknown.clone())
),
Self::Crypto(error) => write!(f, "crypto provider: {error}"),
}
}
}
impl std::error::Error for Rejection {}
#[derive(Debug, Clone, Copy)]
pub struct Validator<'a> {
known: Option<&'a [AttrType]>,
fingerprint_required: bool,
min_sha256_len: usize,
}
impl Default for Validator<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> Validator<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
known: None,
fingerprint_required: false,
min_sha256_len: MESSAGE_INTEGRITY_SHA256_SIZE,
}
}
#[must_use]
pub const fn require_fingerprint(mut self) -> Self {
self.fingerprint_required = true;
self
}
#[must_use]
pub const fn known_attributes(mut self, known: &'a [AttrType]) -> Self {
self.known = Some(known);
self
}
#[must_use]
pub const fn allow_truncated_sha256(mut self, min_len: usize) -> Self {
self.min_sha256_len = if min_len < MESSAGE_INTEGRITY_SHA256_MIN_SIZE {
MESSAGE_INTEGRITY_SHA256_MIN_SIZE
} else {
min_len
};
self
}
pub fn authenticate(
&self,
m: &Message,
key: &[u8],
crypto: &dyn RTCCrypto,
) -> std::result::Result<ValidatedMessage, Rejection> {
let algorithm = if m.contains(ATTR_MESSAGE_INTEGRITY_SHA256) {
IntegrityAlgorithm::Sha256
} else {
IntegrityAlgorithm::Sha1
};
self.authenticate_with(m, algorithm, key, crypto)
}
pub fn authenticate_with(
&self,
m: &Message,
algorithm: IntegrityAlgorithm,
key: &[u8],
crypto: &dyn RTCCrypto,
) -> std::result::Result<ValidatedMessage, Rejection> {
let fingerprint = self.check_fingerprint(m)?;
if !m.contains(algorithm.attr_type()) {
return Err(Rejection::IntegrityMissing);
}
let min_len = match algorithm {
IntegrityAlgorithm::Sha1 => algorithm.tag_len(),
IntegrityAlgorithm::Sha256 => self.min_sha256_len,
};
match check_integrity(m, algorithm, min_len, key, crypto) {
Ok(()) => {}
Err(Error::ErrIntegrityMismatch) => return Err(Rejection::IntegrityMismatch),
Err(Error::ErrAttributeNotFound) => return Err(Rejection::IntegrityMissing),
Err(error) => return Err(Rejection::Crypto(error.to_string())),
}
self.finish(m, Some(algorithm), fingerprint)
}
pub fn unauthenticated(&self, m: &Message) -> std::result::Result<ValidatedMessage, Rejection> {
let fingerprint = self.check_fingerprint(m)?;
self.finish(m, None, fingerprint)
}
fn check_fingerprint(&self, m: &Message) -> std::result::Result<bool, Rejection> {
if !m.contains(ATTR_FINGERPRINT) {
return if self.fingerprint_required {
Err(Rejection::FingerprintMissing)
} else {
Ok(false)
};
}
FINGERPRINT
.check(m)
.map(|()| true)
.map_err(|_| Rejection::FingerprintMismatch)
}
fn finish(
&self,
m: &Message,
integrity: Option<IntegrityAlgorithm>,
fingerprint: bool,
) -> std::result::Result<ValidatedMessage, Rejection> {
let covered = covered_message(m);
if let Some(known) = self.known {
let unknown = covered.unknown_required_attributes(known);
if !unknown.is_empty() {
return Err(Rejection::UnknownAttributes(unknown));
}
}
Ok(ValidatedMessage {
covered,
integrity,
fingerprint,
})
}
}
fn covered_message(m: &Message) -> Message {
let cut = m
.attributes
.0
.iter()
.position(|a| {
a.typ == ATTR_MESSAGE_INTEGRITY
|| a.typ == ATTR_MESSAGE_INTEGRITY_SHA256
|| a.typ == ATTR_FINGERPRINT
})
.unwrap_or(m.attributes.0.len());
let end = m.attribute_offset(cut).min(m.raw.len());
let mut covered = Message {
typ: m.typ,
length: (end.saturating_sub(MESSAGE_HEADER_SIZE)) as u32,
transaction_id: m.transaction_id,
attributes: Attributes(m.attributes.0[..cut].to_vec()),
raw: m.raw[..end].to_vec(),
};
if covered.raw.len() >= MESSAGE_HEADER_SIZE {
covered.write_length();
}
covered
}
#[derive(Debug, Clone, PartialEq)]
pub struct ValidatedMessage {
covered: Message,
integrity: Option<IntegrityAlgorithm>,
fingerprint: bool,
}
impl ValidatedMessage {
#[must_use]
pub fn message(&self) -> &Message {
&self.covered
}
#[must_use]
pub fn into_message(self) -> Message {
self.covered
}
#[must_use]
pub fn integrity(&self) -> Option<IntegrityAlgorithm> {
self.integrity
}
#[must_use]
pub fn is_authenticated(&self) -> bool {
self.integrity.is_some()
}
#[must_use]
pub fn has_fingerprint(&self) -> bool {
self.fingerprint
}
}
impl Deref for ValidatedMessage {
type Target = Message;
fn deref(&self) -> &Message {
&self.covered
}
}
impl AsRef<Message> for ValidatedMessage {
fn as_ref(&self) -> &Message {
&self.covered
}
}
pub fn unknown_attributes_response(
request: &Message,
unknown: &[AttrType],
then: &[Box<dyn Setter + '_>],
) -> Result<Message> {
if request.typ.class != CLASS_REQUEST {
return Err(Error::ErrUnexpectedClass);
}
let mut response = Message::new();
response.write_header();
response.set_type(MessageType::new(request.typ.method, CLASS_ERROR_RESPONSE));
request.transaction_id.add_to(&mut response)?;
CODE_UNKNOWN_ATTRIBUTE.add_to(&mut response)?;
UnknownAttributes(unknown.to_vec()).add_to(&mut response)?;
for setter in then {
setter.add_to(&mut response)?;
if response.length > u32::from(u16::MAX) {
return Err(Error::ErrPacketTooBig);
}
}
Ok(response)
}