pub mod extension_server_name;
pub mod extension_supported_elliptic_curves;
pub mod extension_supported_point_formats;
pub mod extension_supported_signature_algorithms;
pub mod extension_use_extended_master_secret;
pub mod extension_use_srtp;
pub mod renegotiation_info;
use extension_server_name::*;
use extension_supported_elliptic_curves::*;
use extension_supported_point_formats::*;
use extension_supported_signature_algorithms::*;
use extension_use_extended_master_secret::*;
use extension_use_srtp::*;
use shared::error::*;
use crate::extension::renegotiation_info::ExtensionRenegotiationInfo;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Read, Write};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExtensionValue {
ServerName = 0,
SupportedEllipticCurves = 10,
SupportedPointFormats = 11,
SupportedSignatureAlgorithms = 13,
UseSrtp = 14,
UseExtendedMasterSecret = 23,
RenegotiationInfo = 65281,
Unsupported,
}
impl From<u16> for ExtensionValue {
fn from(val: u16) -> Self {
match val {
0 => ExtensionValue::ServerName,
10 => ExtensionValue::SupportedEllipticCurves,
11 => ExtensionValue::SupportedPointFormats,
13 => ExtensionValue::SupportedSignatureAlgorithms,
14 => ExtensionValue::UseSrtp,
23 => ExtensionValue::UseExtendedMasterSecret,
65281 => ExtensionValue::RenegotiationInfo,
_ => ExtensionValue::Unsupported,
}
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
#[non_exhaustive]
pub enum Extension {
ServerName(ExtensionServerName),
SupportedEllipticCurves(ExtensionSupportedEllipticCurves),
SupportedPointFormats(ExtensionSupportedPointFormats),
SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms),
UseSrtp(ExtensionUseSrtp),
UseExtendedMasterSecret(ExtensionUseExtendedMasterSecret),
RenegotiationInfo(ExtensionRenegotiationInfo),
Unknown {
extension_type: u16,
data: Vec<u8>,
},
}
pub(crate) const EXTENSION_CONNECTION_ID: u16 = 54;
pub(crate) const EXTENSION_ALPN: u16 = 16;
pub(crate) fn encode_alpn(protocols: &[String]) -> Vec<u8> {
let mut list = vec![];
for protocol in protocols {
list.push(protocol.len() as u8);
list.extend_from_slice(protocol.as_bytes());
}
let mut data = (list.len() as u16).to_be_bytes().to_vec();
data.extend_from_slice(&list);
data
}
pub(crate) fn parse_alpn(data: &[u8]) -> Result<Vec<String>> {
let malformed = || Error::Other("malformed application_layer_protocol_negotiation".to_owned());
let (length, mut list) = match data {
[a, b, rest @ ..] => (usize::from(u16::from_be_bytes([*a, *b])), rest),
_ => return Err(malformed()),
};
if length != list.len() || length < 2 {
return Err(malformed());
}
let mut protocols = vec![];
while let Some((&name_length, rest)) = list.split_first() {
let name_length = usize::from(name_length);
if name_length == 0 || rest.len() < name_length {
return Err(malformed());
}
let (name, rest) = rest.split_at(name_length);
protocols.push(String::from_utf8_lossy(name).into_owned());
list = rest;
}
Ok(protocols)
}
impl Extension {
pub(crate) fn connection_id(connection_id: &[u8]) -> Self {
let mut data = vec![connection_id.len() as u8];
data.extend_from_slice(connection_id);
Extension::Unknown {
extension_type: EXTENSION_CONNECTION_ID,
data,
}
}
pub(crate) fn alpn(protocols: &[String]) -> Self {
Extension::Unknown {
extension_type: EXTENSION_ALPN,
data: encode_alpn(protocols),
}
}
pub(crate) fn as_alpn(&self) -> Option<Result<Vec<String>>> {
match self {
Extension::Unknown {
extension_type: EXTENSION_ALPN,
data,
} => Some(parse_alpn(data)),
_ => None,
}
}
pub(crate) fn as_connection_id(&self) -> Option<Result<&[u8]>> {
match self {
Extension::Unknown {
extension_type: EXTENSION_CONNECTION_ID,
data,
} => Some(match data.split_first() {
Some((length, connection_id)) if usize::from(*length) == connection_id.len() => {
Ok(connection_id)
}
_ => Err(Error::Other("malformed connection_id extension".to_owned())),
}),
_ => None,
}
}
pub fn extension_type(&self) -> u16 {
match self {
Extension::Unknown { extension_type, .. } => *extension_type,
known => known.extension_value() as u16,
}
}
pub fn extension_value(&self) -> ExtensionValue {
match self {
Extension::Unknown { .. } => ExtensionValue::Unsupported,
Extension::ServerName(ext) => ext.extension_value(),
Extension::SupportedEllipticCurves(ext) => ext.extension_value(),
Extension::SupportedPointFormats(ext) => ext.extension_value(),
Extension::SupportedSignatureAlgorithms(ext) => ext.extension_value(),
Extension::UseSrtp(ext) => ext.extension_value(),
Extension::UseExtendedMasterSecret(ext) => ext.extension_value(),
Extension::RenegotiationInfo(ext) => ext.extension_value(),
}
}
pub fn size(&self) -> usize {
let mut len = 2;
len += match self {
Extension::ServerName(ext) => ext.size(),
Extension::SupportedEllipticCurves(ext) => ext.size(),
Extension::SupportedPointFormats(ext) => ext.size(),
Extension::SupportedSignatureAlgorithms(ext) => ext.size(),
Extension::UseSrtp(ext) => ext.size(),
Extension::UseExtendedMasterSecret(ext) => ext.size(),
Extension::RenegotiationInfo(ext) => ext.size(),
Extension::Unknown { data, .. } => 2 + data.len(),
};
len
}
pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
writer.write_u16::<BigEndian>(self.extension_type())?;
match self {
Extension::Unknown { data, .. } => {
writer.write_u16::<BigEndian>(data.len() as u16)?;
writer.write_all(data)?;
Ok(writer.flush()?)
}
Extension::ServerName(ext) => ext.marshal(writer),
Extension::SupportedEllipticCurves(ext) => ext.marshal(writer),
Extension::SupportedPointFormats(ext) => ext.marshal(writer),
Extension::SupportedSignatureAlgorithms(ext) => ext.marshal(writer),
Extension::UseSrtp(ext) => ext.marshal(writer),
Extension::UseExtendedMasterSecret(ext) => ext.marshal(writer),
Extension::RenegotiationInfo(ext) => ext.marshal(writer),
}
}
pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
let extension_value: ExtensionValue = reader.read_u16::<BigEndian>()?.into();
match extension_value {
ExtensionValue::ServerName => Ok(Extension::ServerName(
ExtensionServerName::unmarshal(reader)?,
)),
ExtensionValue::SupportedEllipticCurves => Ok(Extension::SupportedEllipticCurves(
ExtensionSupportedEllipticCurves::unmarshal(reader)?,
)),
ExtensionValue::SupportedPointFormats => Ok(Extension::SupportedPointFormats(
ExtensionSupportedPointFormats::unmarshal(reader)?,
)),
ExtensionValue::SupportedSignatureAlgorithms => {
Ok(Extension::SupportedSignatureAlgorithms(
ExtensionSupportedSignatureAlgorithms::unmarshal(reader)?,
))
}
ExtensionValue::UseSrtp => Ok(Extension::UseSrtp(ExtensionUseSrtp::unmarshal(reader)?)),
ExtensionValue::UseExtendedMasterSecret => Ok(Extension::UseExtendedMasterSecret(
ExtensionUseExtendedMasterSecret::unmarshal(reader)?,
)),
ExtensionValue::RenegotiationInfo => Ok(Extension::RenegotiationInfo(
ExtensionRenegotiationInfo::unmarshal(reader)?,
)),
_ => Err(Error::ErrInvalidExtensionType),
}
}
}
pub(crate) fn unmarshal_hello_extensions<R: Read>(reader: &mut R) -> Result<Vec<Extension>> {
let mut rest = vec![];
reader.read_to_end(&mut rest)?;
if rest.is_empty() {
return Ok(vec![]);
}
if rest.len() < 2 {
return Err(Error::ErrBufferTooSmall);
}
let block = &rest[2..];
if u16::from_be_bytes([rest[0], rest[1]]) as usize != block.len() {
return Err(Error::ErrLengthMismatch);
}
let mut extensions = vec![];
let mut seen: Vec<u16> = vec![];
let mut offset = 0;
while offset < block.len() {
if offset + 4 > block.len() {
return Err(Error::ErrBufferTooSmall);
}
let extension_type = u16::from_be_bytes([block[offset], block[offset + 1]]);
let data_len = u16::from_be_bytes([block[offset + 2], block[offset + 3]]) as usize;
let end = offset + 4 + data_len;
if end > block.len() {
return Err(Error::ErrBufferTooSmall);
}
if seen.contains(&extension_type) {
return Err(Error::ErrDuplicateExtension);
}
seen.push(extension_type);
let mut extension_reader = &block[offset..end];
match Extension::unmarshal(&mut extension_reader) {
Ok(extension) => extensions.push(extension),
Err(err) => {
log::debug!("extension type {extension_type} kept unparsed: {err}");
extensions.push(Extension::Unknown {
extension_type,
data: block[offset + 4..end].to_vec(),
});
}
}
offset = end;
}
Ok(extensions)
}