#[cfg(test)]
mod integrity_test;
use crate::attributes::*;
use crate::message::*;
use crate::opaque::opaque_string;
use crate::password_algorithm::{PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256};
use crypto::{CryptoError, HashAlgorithm, HmacAlgorithm, RTCCrypto, SecretVec, constant_time_eq};
use shared::error::*;
use std::fmt;
pub(crate) const CREDENTIALS_SEP: &str = ":";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntegrityAlgorithm {
Sha1,
Sha256,
}
impl IntegrityAlgorithm {
#[must_use]
pub const fn attr_type(self) -> AttrType {
match self {
Self::Sha1 => ATTR_MESSAGE_INTEGRITY,
Self::Sha256 => ATTR_MESSAGE_INTEGRITY_SHA256,
}
}
#[must_use]
pub const fn tag_len(self) -> usize {
match self {
Self::Sha1 => MESSAGE_INTEGRITY_SIZE,
Self::Sha256 => MESSAGE_INTEGRITY_SHA256_SIZE,
}
}
const fn hmac(self) -> HmacAlgorithm {
match self {
Self::Sha1 => HmacAlgorithm::Sha1,
Self::Sha256 => HmacAlgorithm::Sha256,
}
}
}
pub const MESSAGE_INTEGRITY_SIZE: usize = 20;
pub const MESSAGE_INTEGRITY_SHA256_SIZE: usize = 32;
pub const MESSAGE_INTEGRITY_SHA256_MIN_SIZE: usize = 16;
fn crypto_error(error: CryptoError) -> Error {
Error::Crypto(error.to_string())
}
fn hmac_input(m: &Message, start: usize, value_len: usize) -> Result<([u8; 2], &[u8], &[u8])> {
if start < MESSAGE_HEADER_SIZE || m.raw.len() < start {
return Err(Error::ErrUnexpectedHeaderEof);
}
let length = start - MESSAGE_HEADER_SIZE
+ ATTRIBUTE_HEADER_SIZE
+ nearest_padded_value_length(value_len);
let length = u16::try_from(length).map_err(|_| Error::ErrPacketTooBig)?;
Ok((length.to_be_bytes(), &m.raw[..2], &m.raw[4..start]))
}
fn add_integrity(
m: &mut Message,
algorithm: IntegrityAlgorithm,
tag_len: usize,
key: &[u8],
crypto: &dyn RTCCrypto,
) -> Result<()> {
for a in &m.attributes.0 {
if a.typ == ATTR_FINGERPRINT {
return Err(Error::ErrFingerprintBeforeIntegrity);
}
}
let start = MESSAGE_HEADER_SIZE + m.length as usize;
let mut tag = vec![0_u8; algorithm.tag_len()];
{
let (length, type_field, rest) = hmac_input(m, start, tag_len)?;
crypto
.new_hmac(algorithm.hmac(), key)
.and_then(|mut mac| mac.sign(&[type_field, &length, rest], &mut tag))
.map_err(crypto_error)?;
}
m.add(algorithm.attr_type(), &tag[..tag_len]);
Ok(())
}
pub(crate) fn check_integrity(
m: &Message,
algorithm: IntegrityAlgorithm,
min_tag_len: usize,
key: &[u8],
crypto: &dyn RTCCrypto,
) -> Result<()> {
let index = m
.position(algorithm.attr_type())
.ok_or(Error::ErrAttributeNotFound)?;
let value = &m.attributes.0[index].value;
let full = algorithm.tag_len();
if value.len() > full || value.len() < min_tag_len || !value.len().is_multiple_of(PADDING) {
return Err(Error::ErrIntegrityMismatch);
}
let (length, type_field, rest) = hmac_input(m, m.attribute_offset(index), value.len())?;
let input: [&[u8]; 3] = [type_field, &length, rest];
let mut mac = crypto
.new_hmac(algorithm.hmac(), key)
.map_err(crypto_error)?;
let result = if value.len() == full {
mac.verify(&input, value)
} else {
let mut tag = vec![0_u8; full];
mac.sign(&input, &mut tag).and_then(|()| {
if constant_time_eq(&tag[..value.len()], value) {
Ok(())
} else {
Err(CryptoError::AuthenticationFailed)
}
})
};
match result {
Ok(()) => Ok(()),
Err(CryptoError::AuthenticationFailed | CryptoError::InvalidTagLength { .. }) => {
Err(Error::ErrIntegrityMismatch)
}
Err(error) => Err(crypto_error(error)),
}
}
pub fn long_term_key(
algorithm: u16,
username: &str,
realm: &str,
password: &str,
crypto: &dyn RTCCrypto,
) -> Result<Vec<u8>> {
let (hash, key_len) = match algorithm {
PASSWORD_ALGORITHM_MD5 => (HashAlgorithm::Md5, 16),
PASSWORD_ALGORITHM_SHA256 => (HashAlgorithm::Sha256, 32),
other => {
return Err(Error::Other(format!(
"password algorithm {other:#06x} is not supported"
)));
}
};
let credentials = SecretVec::new(
[
opaque_or_empty(username)?,
opaque_or_empty(realm)?,
opaque_or_empty(password)?,
]
.join(CREDENTIALS_SEP)
.into_bytes(),
);
let key = crypto
.hash(hash, credentials.as_ref())
.map_err(crypto_error)?;
if key.len() != key_len {
return Err(Error::Crypto(format!(
"provider returned an invalid digest length: {}",
key.len()
)));
}
Ok(key)
}
fn opaque_or_empty(s: &str) -> Result<String> {
if s.is_empty() {
Ok(String::new())
} else {
opaque_string(s).map(|s| s.into_owned())
}
}
#[derive(Clone)]
pub struct MessageIntegrity<'a> {
key: SecretVec,
crypto: &'a dyn RTCCrypto,
}
impl<'a> fmt::Display for MessageIntegrity<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"MESSAGE-INTEGRITY key: [REDACTED; {} bytes]",
self.key.len()
)
}
}
impl<'a> Setter for MessageIntegrity<'a> {
fn add_to(&self, m: &mut Message) -> Result<()> {
add_integrity(
m,
IntegrityAlgorithm::Sha1,
MESSAGE_INTEGRITY_SIZE,
self.key.as_ref(),
self.crypto,
)
}
}
impl<'a> MessageIntegrity<'a> {
#[must_use]
pub fn new_raw_integrity_with_provider(
key: impl Into<Vec<u8>>,
crypto: &'a dyn RTCCrypto,
) -> Self {
Self {
key: SecretVec::new(key.into()),
crypto,
}
}
#[must_use]
pub fn new_short_term_integrity_with_provider(
password: String,
crypto: &'a dyn RTCCrypto,
) -> Self {
Self::new_raw_integrity_with_provider(password.into_bytes(), crypto)
}
pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
let key = opaque_string(password)?.into_owned().into_bytes();
Ok(Self::new_raw_integrity_with_provider(key, crypto))
}
pub fn new_long_term_integrity_with_provider(
username: String,
realm: String,
password: String,
crypto: &'a dyn RTCCrypto,
) -> Result<Self> {
let key = MessageIntegrity::long_term_integrity_key(username, realm, password, crypto)?;
Ok(Self::new_raw_integrity_with_provider(key, crypto))
}
pub fn long_term_integrity_key(
username: String,
realm: String,
password: String,
crypto: &'a dyn RTCCrypto,
) -> Result<Vec<u8>> {
let password = SecretVec::new(password.into_bytes());
let password = std::str::from_utf8(password.as_ref())
.map_err(|_| Error::Other("the password is not UTF-8".to_owned()))?;
long_term_key(PASSWORD_ALGORITHM_MD5, &username, &realm, password, crypto)
}
pub fn check(m: &mut Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
check_integrity(
m,
IntegrityAlgorithm::Sha1,
MESSAGE_INTEGRITY_SIZE,
key,
crypto,
)
}
}
#[derive(Clone)]
pub struct MessageIntegritySha256<'a> {
key: SecretVec,
tag_len: usize,
crypto: &'a dyn RTCCrypto,
}
impl<'a> fmt::Display for MessageIntegritySha256<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"MESSAGE-INTEGRITY-SHA256 key: [REDACTED; {} bytes]",
self.key.len()
)
}
}
impl<'a> Setter for MessageIntegritySha256<'a> {
fn add_to(&self, m: &mut Message) -> Result<()> {
add_integrity(
m,
IntegrityAlgorithm::Sha256,
self.tag_len,
self.key.as_ref(),
self.crypto,
)
}
}
impl<'a> MessageIntegritySha256<'a> {
#[must_use]
pub fn new_raw(key: impl Into<Vec<u8>>, crypto: &'a dyn RTCCrypto) -> Self {
Self {
key: SecretVec::new(key.into()),
tag_len: MESSAGE_INTEGRITY_SHA256_SIZE,
crypto,
}
}
pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
let key = opaque_string(password)?.into_owned().into_bytes();
Ok(Self::new_raw(key, crypto))
}
pub fn long_term(
password_algorithm: u16,
username: &str,
realm: &str,
password: &str,
crypto: &'a dyn RTCCrypto,
) -> Result<Self> {
let key = long_term_key(password_algorithm, username, realm, password, crypto)?;
Ok(Self::new_raw(key, crypto))
}
pub fn with_tag_len(mut self, tag_len: usize) -> Result<Self> {
if !(MESSAGE_INTEGRITY_SHA256_MIN_SIZE..=MESSAGE_INTEGRITY_SHA256_SIZE).contains(&tag_len)
|| !tag_len.is_multiple_of(PADDING)
{
return Err(Error::ErrAttributeSizeInvalid);
}
self.tag_len = tag_len;
Ok(self)
}
pub fn check(m: &Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
Self::check_truncated(m, MESSAGE_INTEGRITY_SHA256_SIZE, key, crypto)
}
pub fn check_truncated(
m: &Message,
min_tag_len: usize,
key: &[u8],
crypto: &dyn RTCCrypto,
) -> Result<()> {
check_integrity(
m,
IntegrityAlgorithm::Sha256,
min_tag_len.max(MESSAGE_INTEGRITY_SHA256_MIN_SIZE),
key,
crypto,
)
}
}