use crate::model::tls::{CipherSuite, TlsVersion};
mod content_type {
pub const HANDSHAKE: u8 = 22;
pub const ALERT: u8 = 21;
}
mod handshake_type {
pub const CLIENT_HELLO: u8 = 1;
pub const SERVER_HELLO: u8 = 2;
}
mod extension {
pub const SERVER_NAME: u16 = 0;
pub const SUPPORTED_GROUPS: u16 = 10;
pub const EC_POINT_FORMATS: u16 = 11;
pub const SIGNATURE_ALGORITHMS: u16 = 13;
pub const SUPPORTED_VERSIONS: u16 = 43;
pub const KEY_SHARE: u16 = 51;
}
pub const HELLO_RETRY_RANDOM: [u8; 32] = [
0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
];
pub const RECORD_HEADER_LEN: usize = 5;
pub const MAX_RECORD_LEN: usize = 16_384 + 2_048;
const SUPPORTED_GROUPS: [u16; 7] = [
0x001D, 0x0017, 0x0018, 0x0019, 0x0100, 0x0101, 0x0102, ];
const SIGNATURE_ALGORITHMS: [u16; 14] = [
0x0403, 0x0503, 0x0603, 0x0807, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601, 0x0402, 0x0201, 0x0203, 0x0202, ];
const KEY_SHARE_GROUP: u16 = 0x001D;
const KEY_SHARE_LEN: usize = 32;
#[derive(Debug, Clone, Copy)]
pub struct Offer<'a> {
pub version: TlsVersion,
pub suites: &'a [CipherSuite],
pub server_name: Option<&'a str>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerResponse {
Hello {
version: Option<TlsVersion>,
suite: u16,
retry: bool,
},
Alert {
level: u8,
description: u8,
},
}
impl ServerResponse {
pub const fn accepted(self) -> bool {
matches!(self, Self::Hello { .. })
}
}
pub fn client_hello(offer: &Offer<'_>) -> Vec<u8> {
let mut body = Vec::with_capacity(512);
let legacy_version = match offer.version {
TlsVersion::Tls13 => TlsVersion::Tls12.code(),
version => version.code(),
};
body.extend_from_slice(&legacy_version.to_be_bytes());
let random: [u8; 32] = rand::random();
body.extend_from_slice(&random);
body.push(0);
let suites_len = offer.suites.len() * 2;
body.extend_from_slice(&(suites_len as u16).to_be_bytes());
for suite in offer.suites {
body.extend_from_slice(&suite.code().to_be_bytes());
}
body.push(1);
body.push(0);
if offer.version != TlsVersion::Ssl30 {
let extensions = extensions(offer);
body.extend_from_slice(&(extensions.len() as u16).to_be_bytes());
body.extend_from_slice(&extensions);
}
let mut handshake = Vec::with_capacity(body.len() + 4);
handshake.push(handshake_type::CLIENT_HELLO);
handshake.extend_from_slice(&three_byte_len(body.len()));
handshake.extend_from_slice(&body);
let mut record = Vec::with_capacity(handshake.len() + RECORD_HEADER_LEN);
record.push(content_type::HANDSHAKE);
record.extend_from_slice(&TlsVersion::Tls10.code().to_be_bytes());
record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
record.extend_from_slice(&handshake);
record
}
fn extensions(offer: &Offer<'_>) -> Vec<u8> {
let mut out = Vec::with_capacity(256);
if let Some(name) = offer.server_name {
let name = name.as_bytes();
let mut value = Vec::with_capacity(name.len() + 5);
value.extend_from_slice(&((name.len() + 3) as u16).to_be_bytes());
value.push(0);
value.extend_from_slice(&(name.len() as u16).to_be_bytes());
value.extend_from_slice(name);
push_extension(&mut out, extension::SERVER_NAME, &value);
}
let mut groups = Vec::with_capacity(SUPPORTED_GROUPS.len() * 2 + 2);
groups.extend_from_slice(&((SUPPORTED_GROUPS.len() * 2) as u16).to_be_bytes());
for group in SUPPORTED_GROUPS {
groups.extend_from_slice(&group.to_be_bytes());
}
push_extension(&mut out, extension::SUPPORTED_GROUPS, &groups);
push_extension(&mut out, extension::EC_POINT_FORMATS, &[1, 0]);
let mut algorithms = Vec::with_capacity(SIGNATURE_ALGORITHMS.len() * 2 + 2);
algorithms.extend_from_slice(&((SIGNATURE_ALGORITHMS.len() * 2) as u16).to_be_bytes());
for algorithm in SIGNATURE_ALGORITHMS {
algorithms.extend_from_slice(&algorithm.to_be_bytes());
}
push_extension(&mut out, extension::SIGNATURE_ALGORITHMS, &algorithms);
if offer.version == TlsVersion::Tls13 {
push_extension(&mut out, extension::SUPPORTED_VERSIONS, &[2, 0x03, 0x04]);
let share: [u8; KEY_SHARE_LEN] = rand::random();
let mut key_share = Vec::with_capacity(KEY_SHARE_LEN + 6);
key_share.extend_from_slice(&((KEY_SHARE_LEN + 4) as u16).to_be_bytes());
key_share.extend_from_slice(&KEY_SHARE_GROUP.to_be_bytes());
key_share.extend_from_slice(&(KEY_SHARE_LEN as u16).to_be_bytes());
key_share.extend_from_slice(&share);
push_extension(&mut out, extension::KEY_SHARE, &key_share);
}
out
}
fn push_extension(out: &mut Vec<u8>, number: u16, value: &[u8]) {
out.extend_from_slice(&number.to_be_bytes());
out.extend_from_slice(&(value.len() as u16).to_be_bytes());
out.extend_from_slice(value);
}
fn three_byte_len(len: usize) -> [u8; 3] {
let bytes = (len as u32).to_be_bytes();
[bytes[1], bytes[2], bytes[3]]
}
pub fn record_length(bytes: &[u8]) -> Option<usize> {
let header: &[u8; RECORD_HEADER_LEN] = bytes.first_chunk()?;
let declared = usize::from(u16::from_be_bytes([header[3], header[4]]));
(declared <= MAX_RECORD_LEN).then_some(RECORD_HEADER_LEN + declared)
}
pub fn read_response(bytes: &[u8]) -> Option<ServerResponse> {
let header: &[u8; RECORD_HEADER_LEN] = bytes.first_chunk()?;
let declared = usize::from(u16::from_be_bytes([header[3], header[4]]));
let body = bytes.get(RECORD_HEADER_LEN..)?;
let body = body.get(..declared.min(body.len()))?;
match header[0] {
content_type::ALERT => {
let alert: &[u8; 2] = body.first_chunk()?;
Some(ServerResponse::Alert {
level: alert[0],
description: alert[1],
})
}
content_type::HANDSHAKE => read_server_hello(body),
_ => None,
}
}
fn read_server_hello(body: &[u8]) -> Option<ServerResponse> {
if *body.first()? != handshake_type::SERVER_HELLO {
return None;
}
let after_header = body.get(4..)?;
let legacy_version = u16::from_be_bytes([*after_header.first()?, *after_header.get(1)?]);
let random: &[u8; 32] = after_header.get(2..34)?.try_into().ok()?;
let retry = *random == HELLO_RETRY_RANDOM;
let session_len = usize::from(*after_header.get(34)?);
let rest = after_header.get(35 + session_len..)?;
let suite = u16::from_be_bytes([*rest.first()?, *rest.get(1)?]);
let version = rest
.get(3..)
.and_then(negotiated_version)
.or_else(|| TlsVersion::from_code(legacy_version));
Some(ServerResponse::Hello {
version,
suite,
retry,
})
}
fn negotiated_version(extensions: &[u8]) -> Option<TlsVersion> {
let declared = usize::from(u16::from_be_bytes([
*extensions.first()?,
*extensions.get(1)?,
]));
let mut rest = extensions.get(2..)?;
rest = rest.get(..declared.min(rest.len()))?;
while rest.len() >= 4 {
let number = u16::from_be_bytes([rest[0], rest[1]]);
let len = usize::from(u16::from_be_bytes([rest[2], rest[3]]));
let value = rest.get(4..4 + len)?;
if number == extension::SUPPORTED_VERSIONS {
let selected: &[u8; 2] = value.first_chunk()?;
return TlsVersion::from_code(u16::from_be_bytes(*selected));
}
rest = rest.get(4 + len..)?;
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn offer(version: TlsVersion) -> Vec<CipherSuite> {
CipherSuite::offered_under(version).take(4).collect()
}
#[test]
fn a_hello_declares_its_own_lengths_correctly() {
for version in TlsVersion::ALL {
let suites = offer(version);
let hello = client_hello(&Offer {
version,
suites: &suites,
server_name: None,
});
assert_eq!(hello[0], content_type::HANDSHAKE, "{version}");
let record_len = u16::from_be_bytes([hello[3], hello[4]]);
assert_eq!(
usize::from(record_len),
hello.len() - RECORD_HEADER_LEN,
"the record must count everything after its header, under {version}"
);
assert_eq!(hello[5], handshake_type::CLIENT_HELLO, "{version}");
let handshake_len = u32::from_be_bytes([0, hello[6], hello[7], hello[8]]);
assert_eq!(
handshake_len as usize,
hello.len() - 9,
"the handshake must count everything after its own header, under {version}"
);
assert_eq!(
record_length(&hello),
Some(hello.len()),
"a reader must find the whole record, under {version}"
);
}
}
#[test]
fn a_hello_offers_the_suites_it_was_given_in_order() {
let suites: Vec<_> = CipherSuite::offered_under(TlsVersion::Tls12)
.take(6)
.collect();
let hello = client_hello(&Offer {
version: TlsVersion::Tls12,
suites: &suites,
server_name: None,
});
let offset = RECORD_HEADER_LEN + 4 + 2 + 32 + 1;
let declared = u16::from_be_bytes([hello[offset], hello[offset + 1]]);
assert_eq!(usize::from(declared), suites.len() * 2);
let on_the_wire: Vec<u16> = hello[offset + 2..offset + 2 + suites.len() * 2]
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_be_bytes(*pair))
.collect();
let expected: Vec<u16> = suites.iter().map(|suite| suite.code()).collect();
assert_eq!(on_the_wire, expected);
}
#[test]
fn tls13_is_asked_for_in_the_extension_and_not_the_version_field() {
let suites = offer(TlsVersion::Tls13);
let hello = client_hello(&Offer {
version: TlsVersion::Tls13,
suites: &suites,
server_name: None,
});
let version_field = u16::from_be_bytes([hello[9], hello[10]]);
assert_eq!(
version_field,
TlsVersion::Tls12.code(),
"RFC 8446 §4.1.2 freezes the field at 0x0303"
);
assert!(
contains_extension(&hello, extension::SUPPORTED_VERSIONS),
"1.3 has to be asked for through supported_versions"
);
assert!(
contains_extension(&hello, extension::KEY_SHARE),
"a share the server can answer without a retry"
);
}
#[test]
fn the_older_versions_are_asked_for_in_the_version_field() {
for version in [TlsVersion::Tls10, TlsVersion::Tls11, TlsVersion::Tls12] {
let suites = offer(version);
let hello = client_hello(&Offer {
version,
suites: &suites,
server_name: None,
});
assert_eq!(u16::from_be_bytes([hello[9], hello[10]]), version.code());
assert!(!contains_extension(&hello, extension::SUPPORTED_VERSIONS));
assert!(!contains_extension(&hello, extension::KEY_SHARE));
}
}
#[test]
fn an_ssl3_hello_carries_no_extensions_at_all() {
let suites = offer(TlsVersion::Ssl30);
let hello = client_hello(&Offer {
version: TlsVersion::Ssl30,
suites: &suites,
server_name: None,
});
let expected = RECORD_HEADER_LEN + 4 + 2 + 32 + 1 + 2 + suites.len() * 2 + 2;
assert_eq!(
hello.len(),
expected,
"an SSLv3 hello has nothing after compression"
);
}
#[test]
fn a_server_name_reaches_the_wire_and_its_absence_sends_nothing() {
let suites = offer(TlsVersion::Tls12);
let named = client_hello(&Offer {
version: TlsVersion::Tls12,
suites: &suites,
server_name: Some("example.test"),
});
assert!(contains_extension(&named, extension::SERVER_NAME));
assert!(
named
.windows(b"example.test".len())
.any(|window| window == b"example.test"),
"the name itself has to be on the wire"
);
let anonymous = client_hello(&Offer {
version: TlsVersion::Tls12,
suites: &suites,
server_name: None,
});
assert!(!contains_extension(&anonymous, extension::SERVER_NAME));
}
#[test]
fn two_hellos_do_not_carry_the_same_random() {
let suites = offer(TlsVersion::Tls12);
let build = || {
client_hello(&Offer {
version: TlsVersion::Tls12,
suites: &suites,
server_name: None,
})
};
assert_ne!(build(), build());
}
fn server_hello(
legacy_version: u16,
suite: u16,
random: [u8; 32],
extensions: Option<&[u8]>,
) -> Vec<u8> {
let mut body = vec![handshake_type::SERVER_HELLO, 0, 0, 0];
body.extend_from_slice(&legacy_version.to_be_bytes());
body.extend_from_slice(&random);
body.push(0); body.extend_from_slice(&suite.to_be_bytes());
body.push(0); if let Some(extensions) = extensions {
body.extend_from_slice(&(extensions.len() as u16).to_be_bytes());
body.extend_from_slice(extensions);
}
let length = body.len() - 4;
body[1..4].copy_from_slice(&three_byte_len(length));
let mut record = vec![content_type::HANDSHAKE, 0x03, 0x03];
record.extend_from_slice(&(body.len() as u16).to_be_bytes());
record.extend_from_slice(&body);
record
}
#[test]
fn a_server_hello_names_the_version_and_the_suite() {
let record = server_hello(0x0303, 0xC02F, [0u8; 32], None);
assert_eq!(
read_response(&record),
Some(ServerResponse::Hello {
version: Some(TlsVersion::Tls12),
suite: 0xC02F,
retry: false,
})
);
}
#[test]
fn tls13_is_read_from_the_extension_rather_than_the_field() {
let extensions = [0x00, 0x2B, 0x00, 0x02, 0x03, 0x04];
let record = server_hello(0x0303, 0x1301, [0u8; 32], Some(&extensions));
assert_eq!(
read_response(&record),
Some(ServerResponse::Hello {
version: Some(TlsVersion::Tls13),
suite: 0x1301,
retry: false,
})
);
}
#[test]
fn the_version_extension_is_found_behind_others() {
let extensions = [
0x00, 0x33, 0x00, 0x02, 0xAA, 0xBB, 0xFF, 0x01, 0x00, 0x01, 0x00, 0x00, 0x2B, 0x00, 0x02, 0x03, 0x04, ];
let record = server_hello(0x0303, 0x1302, [0u8; 32], Some(&extensions));
assert!(matches!(
read_response(&record),
Some(ServerResponse::Hello {
version: Some(TlsVersion::Tls13),
..
})
));
}
#[test]
fn a_hello_retry_request_is_an_answer_and_says_so() {
let extensions = [0x00, 0x2B, 0x00, 0x02, 0x03, 0x04];
let record = server_hello(0x0303, 0x1301, HELLO_RETRY_RANDOM, Some(&extensions));
assert_eq!(
read_response(&record),
Some(ServerResponse::Hello {
version: Some(TlsVersion::Tls13),
suite: 0x1301,
retry: true,
})
);
}
#[test]
fn a_session_id_does_not_move_the_suite() {
let mut body = vec![handshake_type::SERVER_HELLO, 0, 0, 0];
body.extend_from_slice(&0x0303u16.to_be_bytes());
body.extend_from_slice(&[0u8; 32]);
body.push(32);
body.extend_from_slice(&[0xAB; 32]);
body.extend_from_slice(&0x009Cu16.to_be_bytes());
body.push(0);
let length = body.len() - 4;
body[1..4].copy_from_slice(&three_byte_len(length));
let mut record = vec![content_type::HANDSHAKE, 0x03, 0x03];
record.extend_from_slice(&(body.len() as u16).to_be_bytes());
record.extend_from_slice(&body);
assert!(matches!(
read_response(&record),
Some(ServerResponse::Hello { suite: 0x009C, .. })
));
}
#[test]
fn an_alert_is_read_as_a_refusal_with_its_reason() {
let record = [content_type::ALERT, 0x03, 0x03, 0x00, 0x02, 0x02, 0x28];
assert_eq!(
read_response(&record),
Some(ServerResponse::Alert {
level: 2,
description: 40,
})
);
assert!(!read_response(&record).expect("an answer").accepted());
}
#[test]
fn what_is_not_an_answer_is_not_read_as_one() {
assert_eq!(read_response(b"HTTP/1.1 200 OK"), None);
assert_eq!(read_response(b"SSH-2.0-OpenSSH_9.6p1"), None);
assert_eq!(read_response(&[]), None);
assert_eq!(read_response(&[0x16, 0x03, 0x03, 0x00, 0x4A]), None);
assert_eq!(
read_response(&[0x16, 0x03, 0x03, 0x00, 0x04, 0x0B, 0x00, 0x00, 0x00]),
None
);
let mut short = server_hello(0x0303, 0xC02F, [0u8; 32], None);
short.truncate(RECORD_HEADER_LEN + 20);
assert_eq!(read_response(&short), None);
assert_eq!(
read_response(&[0x17, 0x03, 0x03, 0x00, 0x02, 0x00, 0x00]),
None
);
}
#[test]
fn a_record_longer_than_tls_permits_is_refused() {
let absurd = [0x16, 0x03, 0x03, 0xFF, 0xFF];
assert_eq!(record_length(&absurd), None);
let largest = u16::try_from(MAX_RECORD_LEN).expect("fits").to_be_bytes();
let permitted = [0x16, 0x03, 0x03, largest[0], largest[1]];
assert_eq!(
record_length(&permitted),
Some(RECORD_HEADER_LEN + MAX_RECORD_LEN)
);
assert_eq!(
record_length(&[0x16, 0x03]),
None,
"the header is not here yet"
);
}
fn contains_extension(hello: &[u8], number: u16) -> bool {
let after_random = RECORD_HEADER_LEN + 4 + 2 + 32;
let session_len = usize::from(hello[after_random]);
let mut rest = &hello[after_random + 1 + session_len..];
let suites_len = usize::from(u16::from_be_bytes([rest[0], rest[1]]));
rest = &rest[2 + suites_len..];
let compression_len = usize::from(rest[0]);
rest = &rest[1 + compression_len..];
if rest.len() < 2 {
return false;
}
let declared = usize::from(u16::from_be_bytes([rest[0], rest[1]]));
let mut block = &rest[2..2 + declared];
while block.len() >= 4 {
let found = u16::from_be_bytes([block[0], block[1]]);
let len = usize::from(u16::from_be_bytes([block[2], block[3]]));
if found == number {
return true;
}
block = &block[4 + len..];
}
false
}
proptest::proptest! {
#[test]
fn reading_an_answer_never_panics(
record in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..512)
) {
let _ = read_response(&record);
let _ = record_length(&record);
}
#[test]
fn reading_a_malformed_handshake_never_panics(
body in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..256)
) {
let mut record = vec![content_type::HANDSHAKE, 0x03, 0x03];
record.extend_from_slice(&(body.len() as u16).to_be_bytes());
record.extend_from_slice(&body);
let _ = read_response(&record);
}
}
}