use crypto::{AeadCipher, Mac, RTCCrypto, StreamCipher, constant_time_eq};
use zeroize::{Zeroize, Zeroizing};
use crate::cipher_suite::{AeadKind, CipherSuite, NONCE_LEN};
use crate::error::{Error, Result, crypto_error};
const MAX_MAC_LEN: usize = 64;
pub(crate) enum SuiteAead {
Gcm(Box<dyn AeadCipher>),
CtrHmac {
cipher: Box<dyn StreamCipher>,
mac: Box<dyn Mac>,
tag_len: usize,
},
}
impl SuiteAead {
pub(crate) fn new(crypto: &dyn RTCCrypto, suite: CipherSuite, key: &[u8]) -> Result<Self> {
if key.len() != suite.key_len() {
return Err(Error::Crypto(crypto::CryptoError::InvalidKeyLength {
expected: suite.key_len(),
actual: key.len(),
}));
}
match suite.aead_kind() {
AeadKind::Gcm(algorithm) => {
let aead = crypto.new_aead(algorithm, key).map_err(crypto_error)?;
if aead.tag_len() != suite.tag_len() {
return Err(Error::Crypto(crypto::CryptoError::InvalidTagLength {
expected: suite.tag_len(),
actual: aead.tag_len(),
}));
}
Ok(Self::Gcm(aead))
}
AeadKind::CtrHmac(algorithm) => {
let (enc_key, auth_key) = key.split_at(key.len() - suite.hash_len());
let mac = crypto
.new_hmac(suite.hmac(), auth_key)
.map_err(crypto_error)?;
if mac.output_len() != suite.hash_len() || suite.hash_len() > MAX_MAC_LEN {
return Err(Error::Crypto(crypto::CryptoError::InvalidTagLength {
expected: suite.hash_len(),
actual: mac.output_len(),
}));
}
Ok(Self::CtrHmac {
cipher: crypto
.new_stream_cipher(algorithm, enc_key)
.map_err(crypto_error)?,
mac,
tag_len: suite.tag_len(),
})
}
}
}
pub(crate) fn seal(
&mut self,
nonce: &[u8; NONCE_LEN],
header: &[u8],
metadata: &[u8],
scratch: &mut Vec<u8>,
data: &mut [u8],
tag: &mut [u8],
) -> Result<()> {
match self {
Self::Gcm(aead) => aead
.seal_in_place(nonce, joined(header, metadata, scratch), data, tag)
.map_err(crypto_error),
Self::CtrHmac {
cipher,
mac,
tag_len,
} => {
check_tag_len(*tag_len, tag.len())?;
cipher
.apply_keystream(&initial_counter(nonce)[..], data)
.map_err(crypto_error)?;
let mut full = [0u8; MAX_MAC_LEN];
let computed = compute_tag_into(
mac.as_mut(),
*tag_len,
nonce,
header,
metadata,
data,
&mut full,
);
if computed.is_ok() {
tag.copy_from_slice(&full[..*tag_len]);
}
full.zeroize();
computed.map(|_| ())
}
}
}
pub(crate) fn open(
&mut self,
nonce: &[u8; NONCE_LEN],
header: &[u8],
metadata: &[u8],
scratch: &mut Vec<u8>,
data: &mut [u8],
tag: &[u8],
) -> Result<()> {
match self {
Self::Gcm(aead) => aead
.open_in_place(nonce, joined(header, metadata, scratch), data, tag)
.map_err(crypto_error),
Self::CtrHmac {
cipher,
mac,
tag_len,
} => {
check_tag_len(*tag_len, tag.len())?;
let mut full = [0u8; MAX_MAC_LEN];
let mac_len = compute_tag_into(
mac.as_mut(),
*tag_len,
nonce,
header,
metadata,
data,
&mut full,
);
let authentic = match &mac_len {
Ok(_) => constant_time_eq(&full[..*tag_len], tag),
Err(_) => false,
};
full.zeroize();
let decrypted = cipher
.apply_keystream(&initial_counter(nonce)[..], data)
.map_err(crypto_error);
mac_len?;
decrypted?;
if authentic {
Ok(())
} else {
Err(Error::AuthenticationFailed)
}
}
}
}
}
fn check_tag_len(expected: usize, actual: usize) -> Result<()> {
if expected == actual {
Ok(())
} else {
Err(Error::Crypto(crypto::CryptoError::InvalidTagLength {
expected,
actual,
}))
}
}
fn joined<'a>(header: &'a [u8], metadata: &[u8], scratch: &'a mut Vec<u8>) -> &'a [u8] {
if metadata.is_empty() {
return header;
}
scratch.clear();
scratch.extend_from_slice(header);
scratch.extend_from_slice(metadata);
scratch
}
fn initial_counter(nonce: &[u8; NONCE_LEN]) -> Zeroizing<[u8; 16]> {
let mut counter = Zeroizing::new([0u8; 16]);
counter[..NONCE_LEN].copy_from_slice(nonce);
counter
}
fn compute_tag_into(
mac: &mut dyn Mac,
tag_len: usize,
nonce: &[u8; NONCE_LEN],
header: &[u8],
metadata: &[u8],
ciphertext: &[u8],
full: &mut [u8; MAX_MAC_LEN],
) -> Result<usize> {
let mut lengths = [0u8; 24];
lengths[..8].copy_from_slice(&((header.len() + metadata.len()) as u64).to_be_bytes());
lengths[8..16].copy_from_slice(&(ciphertext.len() as u64).to_be_bytes());
lengths[16..].copy_from_slice(&(tag_len as u64).to_be_bytes());
let mac_len = mac.output_len();
mac.sign(
&[&lengths, nonce, header, metadata, ciphertext],
&mut full[..mac_len],
)
.map_err(crypto_error)?;
Ok(mac_len)
}