rtci_dtls/record_layer/record_layer_header.rs
1//! The DTLS record header.
2//!
3//! Thirteen bytes: content type, protocol version, a 16-bit epoch, a 48-bit sequence number, and
4//! the body length. The epoch is what DTLS adds over TLS here — it increments on every
5//! ChangeCipherSpec, so records protected with the old and new keys can be told apart while a
6//! rekey is in flight.
7//!
8//! The sequence number is 48 bits on the wire but held as a `u64`; [`MAX_SEQUENCE_NUMBER`] is the
9//! largest value that fits.
10use crate::content::*;
11
12use shared::error::*;
13
14use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
15use std::io::{Read, Write};
16
17/// Length of the DTLS record header in bytes.
18pub const RECORD_LAYER_HEADER_SIZE: usize = 13;
19/// The largest sequence number the 48-bit field can hold.
20pub const MAX_SEQUENCE_NUMBER: u64 = 0x0000FFFFFFFFFFFF;
21
22/// Major version byte for DTLS 1.2.
23pub const DTLS1_2MAJOR: u8 = 0xfe;
24/// Minor version byte for DTLS 1.2.
25pub const DTLS1_2MINOR: u8 = 0xfd;
26
27/// Major version byte for DTLS 1.0.
28pub const DTLS1_0MAJOR: u8 = 0xfe;
29/// Minor version byte for DTLS 1.0.
30pub const DTLS1_0MINOR: u8 = 0xff;
31
32// VERSION_DTLS12 is the DTLS version in the same style as
33// VersionTLSXX from crypto/tls
34/// DTLS 1.2 as a single 16-bit value.
35pub const VERSION_DTLS12: u16 = 0xfefd;
36
37/// The first byte of every DTLS version: {254, 255} is 1.0, {254, 253} is 1.2, and the second
38/// byte goes down as the version goes up.
39pub(crate) const DTLS_VERSION_MAJOR: u8 = 0xfe;
40
41impl ProtocolVersion {
42 /// Whether this is DTLS 1.2 or a later version of DTLS. A ClientHello with a later version
43 /// than the server speaks is answered with the server's highest, 1.2 (RFC 5246 E.1).
44 pub(crate) fn is_dtls1_2_or_later(&self) -> bool {
45 self.major == DTLS_VERSION_MAJOR && self.minor <= PROTOCOL_VERSION1_2.minor
46 }
47}
48
49/// DTLS 1.0 as a [`ProtocolVersion`].
50pub const PROTOCOL_VERSION1_0: ProtocolVersion = ProtocolVersion {
51 major: DTLS1_0MAJOR,
52 minor: DTLS1_0MINOR,
53};
54/// DTLS 1.2 as a [`ProtocolVersion`].
55pub const PROTOCOL_VERSION1_2: ProtocolVersion = ProtocolVersion {
56 major: DTLS1_2MAJOR,
57 minor: DTLS1_2MINOR,
58};
59
60/// ## Specifications
61///
62/// * [RFC 4346 §6.2.1]
63///
64/// [RFC 4346 §6.2.1]: https://tools.ietf.org/html/rfc4346#section-6.2.1
65#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
66pub struct ProtocolVersion {
67 /// The major version byte.
68 pub major: u8,
69 /// The minor version byte.
70 pub minor: u8,
71}
72
73#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
74/// The header on every DTLS record.
75pub struct RecordLayerHeader {
76 /// What the record body holds.
77 pub content_type: ContentType,
78 /// The record's protocol version.
79 pub protocol_version: ProtocolVersion,
80 /// The key epoch, incremented on each ChangeCipherSpec so old and new keys can coexist.
81 pub epoch: u16,
82 /// The record sequence number — a 48-bit field on the wire.
83 pub sequence_number: u64, // uint48 in spec
84 /// The body length in bytes.
85 pub content_len: u16,
86}
87
88impl RecordLayerHeader {
89 /// Encodes this message to `writer`.
90 ///
91 /// # Errors
92 ///
93 /// Fails on a write error, or if a field exceeds the length its wire format allows.
94 pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
95 if self.sequence_number > MAX_SEQUENCE_NUMBER {
96 return Err(Error::ErrSequenceNumberOverflow);
97 }
98
99 writer.write_u8(self.content_type as u8)?;
100 writer.write_u8(self.protocol_version.major)?;
101 writer.write_u8(self.protocol_version.minor)?;
102 writer.write_u16::<BigEndian>(self.epoch)?;
103
104 let be: [u8; 8] = self.sequence_number.to_be_bytes();
105 writer.write_all(&be[2..])?; // uint48 in spec
106
107 writer.write_u16::<BigEndian>(self.content_len)?;
108
109 Ok(writer.flush()?)
110 }
111
112 /// Decodes one of these messages from `reader`.
113 ///
114 /// # Errors
115 ///
116 /// Fails if `reader` is truncated or its contents are not a valid encoding.
117 pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
118 let content_type = reader.read_u8()?.into();
119 let major = reader.read_u8()?;
120 let minor = reader.read_u8()?;
121 let epoch = reader.read_u16::<BigEndian>()?;
122
123 // SequenceNumber is stored as uint48, make into uint64
124 let mut be: [u8; 8] = [0u8; 8];
125 reader.read_exact(&mut be[2..])?;
126 let sequence_number = u64::from_be_bytes(be);
127
128 let protocol_version = ProtocolVersion { major, minor };
129 // RFC 5246 E.1: a ClientHello may come under any record-layer version of the protocol
130 // family ({254, xx}), so every epoch-0 record is taken; which version is spoken is
131 // settled by the hellos. Protected records carry the negotiated version (the AEAD
132 // additional data covers the field).
133 let known =
134 protocol_version == PROTOCOL_VERSION1_0 || protocol_version == PROTOCOL_VERSION1_2;
135 if !known && !(major == DTLS_VERSION_MAJOR && epoch == 0) {
136 return Err(Error::ErrUnsupportedProtocolVersion);
137 }
138 let content_len = reader.read_u16::<BigEndian>()?;
139
140 Ok(RecordLayerHeader {
141 content_type,
142 protocol_version,
143 epoch,
144 sequence_number,
145 content_len,
146 })
147 }
148}