use super::suite::Suite13;
use crypto::{RTCCrypto, SecretVec, hkdf_expand_label, hkdf_extract};
use shared::error::{Error, Result};
pub(crate) const DTLS13_LABEL_PREFIX: &str = "dtls13";
#[cfg(test)]
pub(crate) const TLS13_LABEL_PREFIX: &str = "tls13 ";
pub(crate) const HANDSHAKE_TYPE_MESSAGE_HASH: u8 = 254;
fn crypto_error(error: crypto::CryptoError) -> Error {
Error::Crypto(error.to_string())
}
#[derive(Clone, Default)]
pub(crate) struct Transcript {
bytes: Vec<u8>,
}
impl Transcript {
pub(crate) fn add(&mut self, handshake_type: u8, body: &[u8]) {
self.bytes.push(handshake_type);
self.bytes
.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]);
self.bytes.extend_from_slice(body);
}
pub(crate) fn replace_with_message_hash(
&mut self,
crypto: &dyn RTCCrypto,
suite: Suite13,
) -> Result<()> {
let hash = self.hash(crypto, suite)?;
self.set_message_hash(&hash);
Ok(())
}
pub(crate) fn set_message_hash(&mut self, client_hello_hash: &[u8]) {
self.bytes.clear();
self.add(HANDSHAKE_TYPE_MESSAGE_HASH, client_hello_hash);
}
pub(crate) fn hash(&self, crypto: &dyn RTCCrypto, suite: Suite13) -> Result<Vec<u8>> {
crypto.hash(suite.hash(), &self.bytes).map_err(crypto_error)
}
pub(crate) fn hash_with(
&self,
crypto: &dyn RTCCrypto,
suite: Suite13,
more: &[u8],
) -> Result<Vec<u8>> {
let mut bytes = self.bytes.clone();
bytes.extend_from_slice(more);
crypto.hash(suite.hash(), &bytes).map_err(crypto_error)
}
pub(crate) fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
pub(crate) struct KeySchedule {
suite: Suite13,
prefix: &'static str,
current: SecretVec,
pub(crate) client_handshake_traffic: Option<SecretVec>,
pub(crate) server_handshake_traffic: Option<SecretVec>,
pub(crate) client_application_traffic: Option<SecretVec>,
pub(crate) server_application_traffic: Option<SecretVec>,
pub(crate) exporter: Option<SecretVec>,
}
impl KeySchedule {
pub(crate) fn new(
crypto: &dyn RTCCrypto,
suite: Suite13,
prefix: &'static str,
) -> Result<Self> {
let zeros = vec![0u8; suite.hash_len()];
Self::with_psk(crypto, suite, prefix, &zeros)
}
pub(crate) fn with_psk(
crypto: &dyn RTCCrypto,
suite: Suite13,
prefix: &'static str,
psk: &[u8],
) -> Result<Self> {
let early = hkdf_extract(crypto, suite.hmac(), &[], psk).map_err(crypto_error)?;
Ok(Self {
suite,
prefix,
current: early,
client_handshake_traffic: None,
server_handshake_traffic: None,
client_application_traffic: None,
server_application_traffic: None,
exporter: None,
})
}
pub(crate) fn suite(&self) -> Suite13 {
self.suite
}
fn expand_label(
&self,
crypto: &dyn RTCCrypto,
secret: &[u8],
label: &str,
context: &[u8],
length: usize,
) -> Result<SecretVec> {
hkdf_expand_label(
crypto,
self.suite.hmac(),
secret,
self.prefix,
label,
context,
length,
)
.map_err(crypto_error)
}
fn derive_secret(
&self,
crypto: &dyn RTCCrypto,
secret: &[u8],
label: &str,
transcript_hash: &[u8],
) -> Result<SecretVec> {
self.expand_label(
crypto,
secret,
label,
transcript_hash,
self.suite.hash_len(),
)
}
pub(crate) fn binder_key(&self, crypto: &dyn RTCCrypto, external: bool) -> Result<SecretVec> {
let empty_hash = crypto.hash(self.suite.hash(), &[]).map_err(crypto_error)?;
let label = if external { "ext binder" } else { "res binder" };
self.derive_secret(crypto, self.current.as_ref(), label, &empty_hash)
}
pub(crate) fn client_early_traffic_secret(
&self,
crypto: &dyn RTCCrypto,
client_hello_hash: &[u8],
) -> Result<SecretVec> {
self.derive_secret(
crypto,
self.current.as_ref(),
"c e traffic",
client_hello_hash,
)
}
fn advance(&mut self, crypto: &dyn RTCCrypto, input: &[u8]) -> Result<()> {
let empty_hash = crypto.hash(self.suite.hash(), &[]).map_err(crypto_error)?;
let salt = self.derive_secret(crypto, self.current.as_ref(), "derived", &empty_hash)?;
self.current =
hkdf_extract(crypto, self.suite.hmac(), salt.as_ref(), input).map_err(crypto_error)?;
Ok(())
}
pub(crate) fn enter_handshake(
&mut self,
crypto: &dyn RTCCrypto,
shared_secret: &[u8],
transcript_hash: &[u8],
) -> Result<()> {
self.advance(crypto, shared_secret)?;
self.client_handshake_traffic = Some(self.derive_secret(
crypto,
self.current.as_ref(),
"c hs traffic",
transcript_hash,
)?);
self.server_handshake_traffic = Some(self.derive_secret(
crypto,
self.current.as_ref(),
"s hs traffic",
transcript_hash,
)?);
Ok(())
}
pub(crate) fn enter_application(
&mut self,
crypto: &dyn RTCCrypto,
transcript_hash: &[u8],
) -> Result<()> {
let zeros = vec![0u8; self.suite.hash_len()];
self.advance(crypto, &zeros)?;
self.client_application_traffic = Some(self.derive_secret(
crypto,
self.current.as_ref(),
"c ap traffic",
transcript_hash,
)?);
self.server_application_traffic = Some(self.derive_secret(
crypto,
self.current.as_ref(),
"s ap traffic",
transcript_hash,
)?);
self.exporter = Some(self.derive_secret(
crypto,
self.current.as_ref(),
"exp master",
transcript_hash,
)?);
Ok(())
}
pub(crate) fn take_resumption_master_secret(
&mut self,
crypto: &dyn RTCCrypto,
transcript_hash: &[u8],
) -> Result<SecretVec> {
if self.current.is_empty() || self.exporter.is_none() {
return Err(Error::ErrCipherSuiteUnset);
}
let secret =
self.derive_secret(crypto, self.current.as_ref(), "res master", transcript_hash);
self.current = SecretVec::new(vec![]);
secret
}
pub(crate) fn resumption_psk(
&self,
crypto: &dyn RTCCrypto,
resumption_master_secret: &[u8],
ticket_nonce: &[u8],
) -> Result<SecretVec> {
self.expand_label(
crypto,
resumption_master_secret,
"resumption",
ticket_nonce,
self.suite.hash_len(),
)
}
pub(crate) fn finished_verify_data(
&self,
crypto: &dyn RTCCrypto,
base_key: &[u8],
transcript_hash: &[u8],
) -> Result<Vec<u8>> {
let finished_key =
self.expand_label(crypto, base_key, "finished", &[], self.suite.hash_len())?;
let mut mac = crypto
.new_hmac(self.suite.hmac(), finished_key.as_ref())
.map_err(crypto_error)?;
let mut verify_data = vec![0u8; mac.output_len()];
mac.sign(&[transcript_hash], &mut verify_data)
.map_err(crypto_error)?;
Ok(verify_data)
}
pub(crate) fn next_application_traffic_secret(
&self,
crypto: &dyn RTCCrypto,
secret: &[u8],
) -> Result<SecretVec> {
self.expand_label(crypto, secret, "traffic upd", &[], self.suite.hash_len())
}
pub(crate) fn traffic_keys(
&self,
crypto: &dyn RTCCrypto,
secret: &[u8],
) -> Result<TrafficKeys> {
Ok(TrafficKeys {
key: self.expand_label(crypto, secret, "key", &[], self.suite.key_len())?,
iv: self.expand_label(crypto, secret, "iv", &[], 12)?,
sequence_number_key: self.expand_label(
crypto,
secret,
"sn",
&[],
self.suite.header_mask().key_len(),
)?,
})
}
pub(crate) fn export(
&self,
crypto: &dyn RTCCrypto,
exporter_secret: &[u8],
label: &str,
context: &[u8],
length: usize,
) -> Result<SecretVec> {
let empty_hash = crypto.hash(self.suite.hash(), &[]).map_err(crypto_error)?;
let secret = self.derive_secret(crypto, exporter_secret, label, &empty_hash)?;
let context_hash = crypto
.hash(self.suite.hash(), context)
.map_err(crypto_error)?;
self.expand_label(crypto, secret.as_ref(), "exporter", &context_hash, length)
}
#[cfg(test)]
pub(crate) fn is_forgotten(&self) -> bool {
self.current.as_ref().is_empty()
&& self.client_handshake_traffic.is_none()
&& self.server_handshake_traffic.is_none()
&& self.client_application_traffic.is_none()
&& self.server_application_traffic.is_none()
&& self.exporter.is_none()
}
pub(crate) fn forget_handshake_secrets(&mut self) {
self.client_handshake_traffic = None;
self.server_handshake_traffic = None;
}
#[cfg(test)]
pub(crate) fn handshake_secrets_forgotten(&self) -> bool {
self.client_handshake_traffic.is_none() && self.server_handshake_traffic.is_none()
}
#[cfg(test)]
pub(crate) fn application_secrets_handed_over(&self) -> bool {
self.client_application_traffic.is_none() && self.server_application_traffic.is_none()
}
pub(crate) fn forget(&mut self) {
self.current = SecretVec::new(vec![]);
self.client_handshake_traffic = None;
self.server_handshake_traffic = None;
self.client_application_traffic = None;
self.server_application_traffic = None;
self.exporter = None;
}
}
pub(crate) struct TrafficKeys {
pub(crate) key: SecretVec,
pub(crate) iv: SecretVec,
pub(crate) sequence_number_key: SecretVec,
}
pub(crate) fn certificate_verify_input(from_server: bool, transcript_hash: &[u8]) -> Vec<u8> {
let context: &[u8] = if from_server {
b"TLS 1.3, server CertificateVerify"
} else {
b"TLS 1.3, client CertificateVerify"
};
let mut input = vec![0x20u8; 64];
input.extend_from_slice(context);
input.push(0);
input.extend_from_slice(transcript_hash);
input
}
pub(crate) fn export_keying_material(
crypto: &dyn RTCCrypto,
suite: Suite13,
exporter_secret: &[u8],
label: &str,
context: &[u8],
length: usize,
) -> Result<SecretVec> {
let empty_hash = crypto.hash(suite.hash(), &[]).map_err(crypto_error)?;
let expand = |secret: &[u8], label: &str, context: &[u8], length: usize| {
hkdf_expand_label(
crypto,
suite.hmac(),
secret,
DTLS13_LABEL_PREFIX,
label,
context,
length,
)
.map_err(crypto_error)
};
let secret = expand(exporter_secret, label, &empty_hash, suite.hash_len())?;
let context_hash = crypto.hash(suite.hash(), context).map_err(crypto_error)?;
expand(secret.as_ref(), "exporter", &context_hash, length)
}