#[cfg(feature = "crypto")]
use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use broadcast_common::error::InvalidField;
use core::time::Duration;
#[cfg(feature = "crypto")]
use subtle::ConstantTimeEq;
#[cfg(feature = "crypto")]
use zeroize::Zeroize;
use crate::error::{Error, Result};
#[cfg(feature = "crypto")]
use crate::packet::KeyMaterial;
use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
#[cfg(feature = "crypto")]
use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
use crate::packet::{
ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionBlock,
HandshakeExtensionMessageFlags, HandshakeExtensions, HandshakePacket, HandshakeType,
HsExtMessage,
};
pub const HANDSHAKE_VERSION_4: u32 = 4;
pub const HANDSHAKE_VERSION_5: u32 = 5;
pub const SRT_MAGIC_CODE: u16 = 0x4A17;
pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
pub const REJECTION_CODE_BASE: u32 = 1000;
pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum RejectionReason {
Unknown,
System,
Peer,
Resource,
Rogue,
Backlog,
Ipe,
Close,
Version,
RdvCookie,
BadSecret,
Unsecure,
MessageApi,
Congestion,
Filter,
Group,
Reserved(u32),
}
impl RejectionReason {
pub fn from_bits(v: u32) -> Self {
match v {
1000 => RejectionReason::Unknown,
1001 => RejectionReason::System,
1002 => RejectionReason::Peer,
1003 => RejectionReason::Resource,
1004 => RejectionReason::Rogue,
1005 => RejectionReason::Backlog,
1006 => RejectionReason::Ipe,
1007 => RejectionReason::Close,
1008 => RejectionReason::Version,
1009 => RejectionReason::RdvCookie,
1010 => RejectionReason::BadSecret,
1011 => RejectionReason::Unsecure,
1012 => RejectionReason::MessageApi,
1013 => RejectionReason::Congestion,
1014 => RejectionReason::Filter,
1015 => RejectionReason::Group,
other => RejectionReason::Reserved(other),
}
}
pub fn to_bits(self) -> u32 {
match self {
RejectionReason::Unknown => 1000,
RejectionReason::System => 1001,
RejectionReason::Peer => 1002,
RejectionReason::Resource => 1003,
RejectionReason::Rogue => 1004,
RejectionReason::Backlog => 1005,
RejectionReason::Ipe => 1006,
RejectionReason::Close => 1007,
RejectionReason::Version => 1008,
RejectionReason::RdvCookie => 1009,
RejectionReason::BadSecret => 1010,
RejectionReason::Unsecure => 1011,
RejectionReason::MessageApi => 1012,
RejectionReason::Congestion => 1013,
RejectionReason::Filter => 1014,
RejectionReason::Group => 1015,
RejectionReason::Reserved(v) => v,
}
}
pub fn name(&self) -> &'static str {
match self {
RejectionReason::Unknown => "REJ_UNKNOWN",
RejectionReason::System => "REJ_SYSTEM",
RejectionReason::Peer => "REJ_PEER",
RejectionReason::Resource => "REJ_RESOURCE",
RejectionReason::Rogue => "REJ_ROGUE",
RejectionReason::Backlog => "REJ_BACKLOG",
RejectionReason::Ipe => "REJ_IPE",
RejectionReason::Close => "REJ_CLOSE",
RejectionReason::Version => "REJ_VERSION",
RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
RejectionReason::BadSecret => "REJ_BADSECRET",
RejectionReason::Unsecure => "REJ_UNSECURE",
RejectionReason::MessageApi => "REJ_MESSAGEAPI",
RejectionReason::Congestion => "REJ_CONGESTION",
RejectionReason::Filter => "REJ_FILTER",
RejectionReason::Group => "REJ_GROUP",
RejectionReason::Reserved(_) => "reserved",
}
}
pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
match ht {
HandshakeType::Reserved(v)
if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
{
Some(RejectionReason::from_bits(v))
}
_ => None,
}
}
pub fn to_handshake_type(self) -> HandshakeType {
HandshakeType::from_bits(self.to_bits())
}
}
broadcast_common::impl_spec_display!(RejectionReason, Reserved);
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
#[derive(Clone)]
#[non_exhaustive]
pub struct CryptoConfig {
pub passphrase: Vec<u8>,
pub salt: [u8; crate::crypto::SALT_LEN],
pub sek: Vec<u8>,
}
#[cfg(feature = "crypto")]
impl core::fmt::Debug for CryptoConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CryptoConfig")
.field(
"passphrase",
&format_args!("<redacted, {} bytes>", self.passphrase.len()),
)
.field(
"salt",
&format_args!("<redacted, {} bytes>", self.salt.len()),
)
.field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
.finish()
}
}
#[cfg(feature = "crypto")]
impl PartialEq for CryptoConfig {
fn eq(&self, other: &Self) -> bool {
let passphrase = self
.passphrase
.as_slice()
.ct_eq(other.passphrase.as_slice());
let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
bool::from(passphrase & salt & sek)
}
}
#[cfg(feature = "crypto")]
impl Zeroize for CryptoConfig {
fn zeroize(&mut self) {
self.passphrase.zeroize();
self.salt.zeroize();
self.sek.zeroize();
}
}
#[cfg(feature = "crypto")]
impl Drop for CryptoConfig {
fn drop(&mut self) {
self.zeroize();
}
}
#[cfg(feature = "crypto")]
impl zeroize::ZeroizeOnDrop for CryptoConfig {}
#[cfg(feature = "crypto")]
impl CryptoConfig {
#[must_use]
pub fn new(passphrase: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN], sek: Vec<u8>) -> Self {
Self {
passphrase,
salt,
sek,
}
}
}
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
#[derive(Clone)]
pub struct SecretBytes(Vec<u8>);
#[cfg(feature = "crypto")]
impl SecretBytes {
pub fn new(bytes: Vec<u8>) -> Self {
SecretBytes(bytes)
}
}
#[cfg(feature = "crypto")]
impl From<Vec<u8>> for SecretBytes {
fn from(bytes: Vec<u8>) -> Self {
SecretBytes(bytes)
}
}
#[cfg(feature = "crypto")]
impl core::ops::Deref for SecretBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
#[cfg(feature = "crypto")]
impl core::fmt::Debug for SecretBytes {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
}
}
#[cfg(feature = "crypto")]
impl PartialEq for SecretBytes {
fn eq(&self, other: &Self) -> bool {
bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
}
}
#[cfg(feature = "crypto")]
impl Eq for SecretBytes {}
#[cfg(feature = "crypto")]
impl Zeroize for SecretBytes {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg(feature = "crypto")]
impl Drop for SecretBytes {
fn drop(&mut self) {
self.zeroize();
}
}
#[cfg(feature = "crypto")]
impl zeroize::ZeroizeOnDrop for SecretBytes {}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HandshakeConfig {
pub latency: Duration,
pub mtu: u32,
pub max_flow_window_size: u32,
pub initial_seq_number: u32,
pub srt_version: u32,
pub flags: HandshakeExtensionMessageFlags,
pub encryption_field: EncryptionField,
pub stream_id: Option<String>,
pub group: Option<GroupMembershipExtension>,
pub local_ip: [u32; 4],
pub retransmit_after: Duration,
pub max_retries: u32,
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
pub crypto: Option<CryptoConfig>,
}
impl HandshakeConfig {
#[must_use]
pub fn with_latency(mut self, latency: Duration) -> Self {
self.latency = latency;
self
}
#[must_use]
pub fn with_mtu(mut self, mtu: u32) -> Self {
self.mtu = mtu;
self
}
#[must_use]
pub fn with_max_flow_window_size(mut self, max_flow_window_size: u32) -> Self {
self.max_flow_window_size = max_flow_window_size;
self
}
#[must_use]
pub fn with_initial_seq_number(mut self, initial_seq_number: u32) -> Self {
self.initial_seq_number = initial_seq_number;
self
}
#[must_use]
pub fn with_srt_version(mut self, srt_version: u32) -> Self {
self.srt_version = srt_version;
self
}
#[must_use]
pub fn with_flags(mut self, flags: HandshakeExtensionMessageFlags) -> Self {
self.flags = flags;
self
}
#[must_use]
pub fn with_encryption_field(mut self, encryption_field: EncryptionField) -> Self {
self.encryption_field = encryption_field;
self
}
#[must_use]
pub fn with_stream_id(mut self, stream_id: Option<String>) -> Self {
self.stream_id = stream_id;
self
}
#[must_use]
pub fn with_group(mut self, group: Option<GroupMembershipExtension>) -> Self {
self.group = group;
self
}
#[must_use]
pub fn with_local_ip(mut self, local_ip: [u32; 4]) -> Self {
self.local_ip = local_ip;
self
}
#[must_use]
pub fn with_retransmit_after(mut self, retransmit_after: Duration) -> Self {
self.retransmit_after = retransmit_after;
self
}
#[must_use]
pub fn with_max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = max_retries;
self
}
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
#[must_use]
pub fn with_crypto(mut self, crypto: Option<CryptoConfig>) -> Self {
self.crypto = crypto;
self
}
}
pub const DEFAULT_MAX_RETRIES: u32 = 12;
pub const DEFAULT_RETRANSMIT_AFTER: Duration = Duration::from_micros(83_333);
impl Default for HandshakeConfig {
fn default() -> Self {
HandshakeConfig {
latency: Duration::from_millis(120),
mtu: 1500,
max_flow_window_size: 8192,
initial_seq_number: 0,
srt_version: 0x0105_0000,
flags: HandshakeExtensionMessageFlags(
crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
| crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
| crate::packet::handshake::HS_MSG_FLAG_CRYPT
| crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
| crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
| crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
),
encryption_field: EncryptionField::NoEncryption,
stream_id: None,
group: None,
local_ip: [0, 0, 0, 0],
retransmit_after: DEFAULT_RETRANSMIT_AFTER,
max_retries: DEFAULT_MAX_RETRIES,
#[cfg(feature = "crypto")]
crypto: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct NegotiatedParams {
pub version: u32,
pub flags: HandshakeExtensionMessageFlags,
pub latency: Duration,
pub own_socket_id: u32,
pub peer_socket_id: u32,
pub mtu: u32,
pub max_flow_window_size: u32,
pub stream_id: Option<String>,
pub group: Option<GroupMembershipExtension>,
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
#[cfg_attr(feature = "serde", serde(skip))]
pub sek: Option<SecretBytes>,
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum HandshakeOutput {
Send(Vec<u8>),
Connected(NegotiatedParams),
Rejected(RejectionReason),
TimedOut,
}
pub(crate) enum RetransmitStep {
Idle,
Resend(Vec<u8>),
TimedOut,
}
impl RetransmitStep {
pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
match self {
Self::Idle => Vec::new(),
Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
Self::TimedOut => vec![HandshakeOutput::TimedOut],
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct WireClock {
us: u32,
}
impl WireClock {
pub(crate) fn set(&mut self, elapsed: core::time::Duration) {
self.us = crate::arq::duration_to_wire_us(elapsed);
}
pub(crate) fn now(&self) -> u32 {
self.us
}
}
#[derive(Debug, Default)]
pub(crate) struct Retransmit {
last_sent: Option<Vec<u8>>,
silent: Duration,
retries: u32,
}
impl Retransmit {
pub(crate) fn remember(&mut self, bytes: &[u8]) {
self.last_sent = Some(bytes.to_vec());
}
pub(crate) fn arm(&mut self, bytes: &[u8]) {
self.remember(bytes);
self.silent = Duration::ZERO;
}
pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
self.arm(bytes);
self.retries = 0;
}
pub(crate) fn last_sent(&self) -> Option<&[u8]> {
self.last_sent.as_deref()
}
pub(crate) fn tick(&mut self, elapsed: Duration, config: &HandshakeConfig) -> RetransmitStep {
self.silent = self.silent.saturating_add(elapsed);
if self.silent < config.retransmit_after {
return RetransmitStep::Idle;
}
self.silent = Duration::ZERO;
self.retries += 1;
if self.retries > config.max_retries {
return RetransmitStep::TimedOut;
}
self.last_sent
.clone()
.map_or(RetransmitStep::Idle, RetransmitStep::Resend)
}
}
pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
let pkt = ControlPacket::Handshake(hp);
let mut buf = alloc::vec![0u8; pkt.serialized_len()];
pkt.serialize_into(&mut buf)?;
Ok(buf)
}
pub(crate) fn build_conclusion_extensions<'a>(
hs_ext_type: crate::packet::ExtensionType,
contents: &'a ConclusionExtensionContents,
) -> (HandshakeExtensions<'a>, u16) {
let mut blocks = alloc::vec![HandshakeExtensionBlock {
ext_type: hs_ext_type,
contents: &contents.hs_msg,
}];
let mut ext_flags = HS_EXT_FLAG_HSREQ;
if let Some(sid) = contents.stream_id.as_ref() {
blocks.push(HandshakeExtensionBlock {
ext_type: crate::packet::ExtensionType::Sid,
contents: sid,
});
ext_flags |= HS_EXT_FLAG_CONFIG;
}
if let Some(group) = contents.group.as_ref() {
blocks.push(HandshakeExtensionBlock {
ext_type: crate::packet::ExtensionType::Group,
contents: group,
});
ext_flags |= HS_EXT_FLAG_CONFIG;
}
if let Some((ext_type, km)) = contents.km.as_ref() {
blocks.push(HandshakeExtensionBlock {
ext_type: *ext_type,
contents: km,
});
ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
}
(HandshakeExtensions(blocks), ext_flags)
}
pub(crate) struct ConclusionExtensionContents {
hs_msg: Vec<u8>,
stream_id: Option<Vec<u8>>,
group: Option<Vec<u8>>,
km: Option<(crate::packet::ExtensionType, Vec<u8>)>,
}
impl ConclusionExtensionContents {
pub(crate) fn new(
hs_msg: HsExtMessage,
stream_id: Option<&str>,
group: Option<GroupMembershipExtension>,
) -> Self {
use crate::packet::handshake::encode_stream_id;
ConclusionExtensionContents {
hs_msg: Vec::from(hs_msg.to_bytes()),
stream_id: stream_id.map(encode_stream_id),
group: group.map(|g| Vec::from(g.to_bytes())),
km: None,
}
}
#[cfg(feature = "crypto")]
pub(crate) fn set_key_material(
&mut self,
ext_type: crate::packet::ExtensionType,
contents: Vec<u8>,
) {
self.km = Some((ext_type, contents));
}
}
#[derive(Debug, Default)]
pub(crate) struct ParsedPeerExtensions<'a> {
pub hs_msg: Option<HsExtMessage>,
pub stream_id: Option<String>,
pub group: Option<GroupMembershipExtension>,
#[cfg(feature = "crypto")]
pub km: Option<KeyMaterial<'a>>,
#[cfg(not(feature = "crypto"))]
_phantom: core::marker::PhantomData<&'a ()>,
}
pub(crate) fn parse_peer_extensions<'a>(
hp: &HandshakePacket<'a>,
) -> Result<ParsedPeerExtensions<'a>> {
use crate::packet::ExtensionType;
let mut out = ParsedPeerExtensions::default();
for block in hp.extensions.iter() {
match block.ext_type {
ExtensionType::HsReq | ExtensionType::HsRsp => {
let msg = block.as_hs_ext_message().map_err(|_| {
Error::InvalidField(InvalidField {
field: "handshake extension message",
reason: "malformed HSREQ/HSRSP contents",
})
})?;
out.hs_msg = Some(msg);
}
ExtensionType::Sid => {
let sid = block.as_stream_id().map_err(|_| {
Error::InvalidField(InvalidField {
field: "stream ID extension",
reason: "malformed or non-UTF-8 contents",
})
})?;
out.stream_id = Some(sid);
}
ExtensionType::Group => {
let g = block.as_group_membership().map_err(|_| {
Error::InvalidField(InvalidField {
field: "group membership extension",
reason: "malformed contents",
})
})?;
out.group = Some(g);
}
#[cfg(feature = "crypto")]
ExtensionType::KmReq | ExtensionType::KmRsp => {
let km = block.as_key_material().map_err(|_| {
Error::InvalidField(InvalidField {
field: "key material extension",
reason: "malformed contents",
})
})?;
out.km = Some(km);
}
_ => {}
}
}
Ok(out)
}
#[cfg(feature = "crypto")]
pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
let km = KeyMaterial {
kk: KmKeyFlag::Even,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &crypto.salt,
icv,
x_sek: &wrapped,
o_sek: None,
};
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf)?;
crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
}
#[cfg(feature = "crypto")]
pub(crate) fn build_key_material_contents(crypto: &CryptoConfig) -> Result<Vec<u8>> {
let block = build_key_material_extension(crypto)?;
Ok(block[crate::packet::handshake::HANDSHAKE_EXT_BLOCK_HEADER_LEN..].to_vec())
}
#[cfg(feature = "crypto")]
pub(crate) fn echo_key_material_contents<'a>(
hp: &'a HandshakePacket<'a>,
km: &KeyMaterial<'_>,
) -> Result<Cow<'a, [u8]>> {
for block in hp.extensions.iter() {
if matches!(
block.ext_type,
crate::packet::ExtensionType::KmReq | crate::packet::ExtensionType::KmRsp
) {
return Ok(Cow::Borrowed(block.contents));
}
}
let mut contents = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut contents)?;
Ok(Cow::Owned(contents))
}
#[cfg(feature = "crypto")]
pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
#[cfg(feature = "crypto")]
pub(crate) fn recover_sek(
passphrase: &[u8],
km: &KeyMaterial<'_>,
kek_cache: &mut crate::crypto::KekCache,
) -> Result<RecoveredSek> {
if km.salt.len() != crate::crypto::SALT_LEN {
return Err(Error::InvalidField(InvalidField {
field: "Key Material Salt",
reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
}));
}
let mut salt = [0u8; crate::crypto::SALT_LEN];
salt.copy_from_slice(km.salt);
let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
Ok((sek, salt))
}
#[cfg(all(feature = "crypto", feature = "tokio"))]
pub(crate) fn recover_both_seks(
passphrase: &[u8],
km: &KeyMaterial<'_>,
kek_cache: &mut crate::crypto::KekCache,
) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
return Err(Error::InvalidField(InvalidField {
field: "Key Material KK",
reason: "expected both an even and an odd SEK",
}));
};
if km.salt.len() != crate::crypto::SALT_LEN {
return Err(Error::InvalidField(InvalidField {
field: "Key Material Salt",
reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
}));
}
let mut salt = [0u8; crate::crypto::SALT_LEN];
salt.copy_from_slice(km.salt);
let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
wrapped.extend_from_slice(km.x_sek);
wrapped.extend_from_slice(o_sek);
let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
let (even, odd) = keys.split_at(km.x_sek.len());
Ok((
SecretBytes::new(even.to_vec()),
SecretBytes::new(odd.to_vec()),
salt,
))
}
#[cfg(feature = "crypto")]
pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
Ok(k) => k,
Err(_) => return false,
};
let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
Ok(v) => v,
Err(_) => return false,
};
let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
bool::from(salt & icv & wrapped)
}
pub(crate) fn negotiate_latency(local: Duration, peer_msg: &HsExtMessage) -> Duration {
local
.max(peer_msg.receiver_tsbpd_delay)
.max(peer_msg.sender_tsbpd_delay)
}
fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
const C_ROUNDS: usize = 2;
const D_ROUNDS: usize = 4;
const INIT_V0: u64 = 0x736f_6d65_7073_6575;
const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
const INIT_V3: u64 = 0x7465_6462_7974_6573;
const FINALIZATION_XOR: u64 = 0xFF;
let mut v0 = k0 ^ INIT_V0;
let mut v1 = k1 ^ INIT_V1;
let mut v2 = k0 ^ INIT_V2;
let mut v3 = k1 ^ INIT_V3;
fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
*v0 = v0.wrapping_add(*v1);
*v1 = v1.rotate_left(13);
*v1 ^= *v0;
*v0 = v0.rotate_left(32);
*v2 = v2.wrapping_add(*v3);
*v3 = v3.rotate_left(16);
*v3 ^= *v2;
*v0 = v0.wrapping_add(*v3);
*v3 = v3.rotate_left(21);
*v3 ^= *v0;
*v2 = v2.wrapping_add(*v1);
*v1 = v1.rotate_left(17);
*v1 ^= *v2;
*v2 = v2.rotate_left(32);
}
let mut chunks = data.chunks_exact(8);
for chunk in chunks.by_ref() {
let mut word = [0u8; 8];
word.copy_from_slice(chunk);
let m = u64::from_le_bytes(word);
v3 ^= m;
for _ in 0..C_ROUNDS {
round(&mut v0, &mut v1, &mut v2, &mut v3);
}
v0 ^= m;
}
let mut last = [0u8; 8];
let rest = chunks.remainder();
last[..rest.len()].copy_from_slice(rest);
last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
let m = u64::from_le_bytes(last);
v3 ^= m;
for _ in 0..C_ROUNDS {
round(&mut v0, &mut v1, &mut v2, &mut v3);
}
v0 ^= m;
v2 ^= FINALIZATION_XOR;
for _ in 0..D_ROUNDS {
round(&mut v0, &mut v1, &mut v2, &mut v3);
}
v0 ^ v1 ^ v2 ^ v3
}
pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
let mut input = [0u8; 12];
input[..8].copy_from_slice(&peer_key.to_le_bytes());
input[8..].copy_from_slice(&time_bucket.to_le_bytes());
let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
let k1 = u64::try_from(secret >> 64).unwrap_or(0);
let digest = siphash24(k0, k1, &input);
u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
}
const SOCKET_ID_DOMAIN: u8 = 1;
const ISN_DOMAIN: u8 = 2;
pub fn derive_listener_ids(peer_key: u64, time_bucket: u32, secret: u128) -> (u32, u32) {
let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
let k1 = u64::try_from(secret >> 64).unwrap_or(0);
let keyed = |domain: u8| {
let mut input = [0u8; 13];
input[0] = domain;
input[1..9].copy_from_slice(&peer_key.to_le_bytes());
input[9..].copy_from_slice(&time_bucket.to_le_bytes());
u32::try_from(siphash24(k0, k1, &input) & u64::from(u32::MAX)).unwrap_or(0)
};
let socket_id = keyed(SOCKET_ID_DOMAIN) | 1;
let initial_seq = keyed(ISN_DOMAIN) & crate::packet::SEQ_NUMBER_MASK;
(socket_id, initial_seq)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejection_reason_round_trips_table_7() {
let all = [
RejectionReason::Unknown,
RejectionReason::System,
RejectionReason::Peer,
RejectionReason::Resource,
RejectionReason::Rogue,
RejectionReason::Backlog,
RejectionReason::Ipe,
RejectionReason::Close,
RejectionReason::Version,
RejectionReason::RdvCookie,
RejectionReason::BadSecret,
RejectionReason::Unsecure,
RejectionReason::MessageApi,
RejectionReason::Congestion,
RejectionReason::Filter,
RejectionReason::Group,
];
for (i, r) in all.iter().enumerate() {
assert_eq!(r.to_bits(), 1000 + i as u32);
assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
assert_eq!(
RejectionReason::from_handshake_type(r.to_handshake_type()),
Some(*r)
);
}
}
#[test]
fn non_rejection_handshake_types_are_not_a_rejection() {
for ht in [
HandshakeType::Induction,
HandshakeType::Conclusion,
HandshakeType::Wavehand,
HandshakeType::Agreement,
HandshakeType::Done,
] {
assert_eq!(RejectionReason::from_handshake_type(ht), None);
}
}
#[test]
fn derive_cookie_is_deterministic_and_nonzero() {
let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
assert_eq!(a, b);
assert_ne!(a, 0);
let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
assert_ne!(a, c);
}
#[test]
fn derive_listener_ids_is_stable_in_range_and_distinct_from_the_cookie() {
let first = derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
let again = derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
assert_eq!(first, again);
let (socket_id, initial_seq) = first;
assert_ne!(socket_id, 0);
assert!(initial_seq <= crate::packet::SEQ_NUMBER_MASK);
assert_ne!(
socket_id,
derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF)
);
assert_ne!(
first,
derive_listener_ids(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF),
"peer"
);
assert_ne!(
first,
derive_listener_ids(0x1234_5678_9ABC_DEF0, 12346, 0xDEAD_BEEF),
"time bucket"
);
assert_ne!(
first,
derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEE0),
"secret"
);
}
#[test]
fn only_the_positive_rejection_range_counts_as_a_rejection() {
let is_rejection =
|v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
assert!(!is_rejection(0xFFFF_FFFC));
assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
assert!(!is_rejection(REJECTION_CODE_BASE - 1));
assert!(is_rejection(REJECTION_CODE_BASE));
assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
assert_eq!(
RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
Some(RejectionReason::BadSecret)
);
assert_eq!(
RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
Some(RejectionReason::Reserved(1500))
);
assert_eq!(
RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
Some(RejectionReason::Reserved(2001))
);
}
#[cfg(feature = "crypto")]
#[test]
fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
let crypto = CryptoConfig {
passphrase: b"0123456789abcdef".to_vec(),
salt: [0x33; crate::crypto::SALT_LEN],
sek: alloc::vec![0x44; 16],
};
let ext = build_key_material_extension(&crypto).unwrap();
let km = KeyMaterial::parse(&ext[4..]).unwrap();
assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
assert_eq!(km.se.to_bits(), 2);
assert_eq!(ext[4 + 10], 2);
}
#[test]
fn siphash24_matches_the_reference_vector() {
let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
let input: Vec<u8> = (0u8..15).collect();
assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
}
#[test]
fn derive_cookie_depends_on_secret_peer_and_time() {
let base = derive_cookie(1, 2, 3);
assert_ne!(base, derive_cookie(1, 2, 4), "secret");
assert_ne!(base, derive_cookie(9, 2, 3), "peer");
assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
assert_eq!(base & 1, 1);
assert_eq!(
derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
0x5905_9ee9
);
assert_eq!(
derive_cookie(
0x1234_5678_9ABC_DEF0,
12345,
0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
),
0xec46_1e0b
);
assert_ne!(
derive_cookie(1, 2, 7),
derive_cookie(1, 2, 7 | (1u128 << 64)),
"the high key half must influence the cookie"
);
}
#[cfg(feature = "crypto")]
fn distinctive(seed: u32, len: usize) -> Vec<u8> {
let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
(0..len)
.map(|_| {
x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
u8::try_from(x >> 24).unwrap()
})
.collect()
}
#[cfg(feature = "crypto")]
fn needles(bytes: &[u8]) -> Vec<String> {
let head = &bytes[..6];
let dec = |sep: &str| {
head.iter()
.map(|b| alloc::format!("{b}"))
.collect::<Vec<_>>()
.join(sep)
};
alloc::vec![
dec(", "),
dec(","),
head.iter()
.map(|b| alloc::format!("{b:x}"))
.collect::<Vec<_>>()
.join(", "),
head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
]
}
#[cfg(feature = "crypto")]
fn secret_config() -> CryptoConfig {
CryptoConfig {
passphrase: distinctive(1, 15),
salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
sek: distinctive(3, 16),
}
}
#[cfg(feature = "crypto")]
#[test]
fn crypto_config_debug_never_shows_secret_bytes() {
let config = HandshakeConfig {
crypto: Some(secret_config()),
..HandshakeConfig::default()
};
for dump in [
alloc::format!("{:?}", secret_config()),
alloc::format!("{:#?}", secret_config()),
alloc::format!("{:?}", config),
alloc::format!("{:#?}", config),
alloc::format!("{:x?}", config),
] {
let secret = secret_config();
for (name, bytes) in [
("passphrase", &secret.passphrase[..]),
("salt", &secret.salt[..]),
("sek", &secret.sek[..]),
] {
for needle in needles(bytes) {
assert!(
!dump.contains(&needle),
"{name} leaked as {needle:?}: {dump}"
);
}
}
assert!(dump.contains("redacted"), "{dump}");
}
assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
}
#[cfg(feature = "crypto")]
#[test]
fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
let sek_bytes = distinctive(9, 16);
let params = NegotiatedParams {
version: HANDSHAKE_VERSION_5,
flags: HandshakeExtensionMessageFlags(0),
latency: Duration::from_millis(120),
own_socket_id: 1,
peer_socket_id: 2,
mtu: 1500,
max_flow_window_size: 8192,
stream_id: None,
group: None,
sek: Some(SecretBytes::new(sek_bytes.clone())),
salt: Some([0x11; crate::crypto::SALT_LEN]),
};
for dump in [
alloc::format!("{params:?}"),
alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
] {
for needle in needles(&sek_bytes) {
assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
}
assert!(dump.contains("redacted"), "{dump}");
}
#[cfg(feature = "serde")]
{
let json = serde_json::to_string(¶ms).expect("serialize");
assert!(!json.contains("sek"), "the SEK was serialized: {json}");
for needle in needles(&sek_bytes) {
assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
}
}
}
#[cfg(feature = "crypto")]
#[test]
fn secrets_compare_correctly_and_wipe_on_zeroize() {
let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
let mut sek = SecretBytes::new(alloc::vec![9; 16]);
sek.zeroize();
assert!(sek.is_empty(), "zeroize must clear the key");
let mut config = secret_config();
assert!(config == secret_config());
let mut other = secret_config();
other.sek[0] ^= 1;
assert!(config != other);
config.zeroize();
assert!(config.passphrase.is_empty() && config.sek.is_empty());
assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
}
#[cfg(feature = "crypto")]
#[test]
fn secret_holders_are_zeroize_on_drop() {
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
assert_zeroize_on_drop::<CryptoConfig>();
assert_zeroize_on_drop::<SecretBytes>();
}
}