1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#[cfg(test)]
mod handshake_cache_test;
use crate::cipher_suite::*;
use crate::handshake::*;
use std::collections::HashMap;
use std::io::BufReader;
/// Most messages the cache holds. A full DTLS 1.2 handshake caches about ten; the cap stops a
/// peer that sends handshake messages under ever new sequence numbers from growing it.
pub(crate) const MAX_HANDSHAKE_CACHE_ITEMS: usize = 64;
#[derive(Clone, Debug)]
pub(crate) struct HandshakeCacheItem {
typ: HandshakeType,
is_client: bool,
epoch: u16,
message_sequence: u16,
data: Vec<u8>,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct HandshakeCachePullRule {
pub(crate) typ: HandshakeType,
pub(crate) epoch: u16,
pub(crate) is_client: bool,
pub(crate) optional: bool,
}
/// Why [`HandshakeCache::full_pull_map`] could not hand out a flight.
#[derive(Debug, PartialEq)]
pub(crate) enum PullError {
/// A message of the flight has not arrived yet.
Incomplete,
/// The place of a message of the flight is taken by another message of the peer's.
OutOfOrder,
/// A cached message no longer decodes (it did when it was cached).
Decode(Error),
}
#[derive(Clone)]
pub(crate) struct HandshakeCache {
cache: Vec<HandshakeCacheItem>,
}
impl HandshakeCache {
pub(crate) fn new() -> Self {
HandshakeCache { cache: vec![] }
}
pub(crate) fn push(
&mut self,
data: Vec<u8>,
epoch: u16,
message_sequence: u16,
typ: HandshakeType,
is_client: bool,
) -> bool {
for i in &self.cache {
if i.message_sequence == message_sequence && i.is_client == is_client {
return false;
}
}
if self.cache.len() >= MAX_HANDSHAKE_CACHE_ITEMS {
return false;
}
self.cache.push(HandshakeCacheItem {
typ,
is_client,
epoch,
message_sequence,
data,
});
true
}
// The caller authenticates the record first. Recognize the complete Finished or
// its final fragment without buffering a new post-handshake transcript. Only the
// ending fragment triggers a reply, so fragmentation does not spend a retry per fragment.
pub(crate) fn matches_received_finished(
&self,
mut data: &[u8],
epoch: u16,
is_client: bool,
) -> bool {
while !data.is_empty() {
let mut reader = data;
let Ok(header) = HandshakeHeader::unmarshal(&mut reader) else {
return false;
};
let fragment_length = header.fragment_length as usize;
let Some(fragment) = reader.get(..fragment_length) else {
return false;
};
let fragment_start = header.fragment_offset as usize;
let fragment_end = fragment_start + fragment_length;
if header.handshake_type == HandshakeType::Finished
&& fragment_length > 0
&& fragment_end == header.length as usize
&& self.cache.iter().any(|item| {
item.typ == HandshakeType::Finished
&& item.epoch == epoch
&& item.is_client == is_client
&& item.message_sequence == header.message_sequence
&& item.data.len() == HANDSHAKE_HEADER_LENGTH + header.length as usize
&& item.data.get(
HANDSHAKE_HEADER_LENGTH + fragment_start
..HANDSHAKE_HEADER_LENGTH + fragment_end,
) == Some(fragment)
})
{
return true;
}
data = &reader[fragment_length..];
}
false
}
// returns a list handshakes that match the requested rules
// the list will contain null entries for rules that can't be satisfied
// multiple entries may match a rule, but only the last match is returned (ie ClientHello with cookies)
pub(crate) fn pull(&self, rules: &[HandshakeCachePullRule]) -> Vec<HandshakeCacheItem> {
let mut out = vec![];
for r in rules {
let mut item: Option<HandshakeCacheItem> = None;
for c in &self.cache {
if c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch {
if let Some(x) = &item {
if x.message_sequence < c.message_sequence {
item = Some(c.clone());
}
} else {
item = Some(c.clone());
}
}
}
if let Some(c) = item {
out.push(c);
}
}
out
}
/// The peer's flight as `rules` lists it, in that order, from message sequence `start_seq`
/// on: each rule's message (the latest of its type, side and epoch) must sit at the next
/// sequence number, and an optional one that is not there is skipped.
///
/// When a rule's message is not at the sequence number it should hold, what holds that
/// number decides. Nothing yet: the flight is still arriving ([`PullError::Incomplete`]).
/// A message of the peer's: it is in the wrong place, a later message sent first, a
/// message sent twice, or a required one left out (RFC 5246 7.4: handshake messages in an
/// unexpected order are a fatal error), and waiting cannot mend that: the place is taken
/// ([`PullError::OutOfOrder`]).
pub(crate) fn full_pull_map(
&self,
start_seq: isize,
rules: &[HandshakeCachePullRule],
) -> std::result::Result<(isize, HashMap<HandshakeType, HandshakeMessage>), PullError> {
let mut out = HashMap::new();
let mut seq = start_seq;
for r in rules {
let item = self
.cache
.iter()
.filter(|c| c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch)
.max_by_key(|c| c.message_sequence);
let expected = seq as u16;
match item {
Some(c) if c.message_sequence == expected => {
let mut reader = BufReader::new(c.data.as_slice());
let raw_handshake =
Handshake::unmarshal(&mut reader).map_err(PullError::Decode)?;
seq += 1;
out.insert(r.typ, raw_handshake.handshake_message);
}
// An optional message that is absent, or is only one from an earlier flight.
None if r.optional => {}
Some(c) if r.optional && c.message_sequence < expected => {}
_ => return Err(self.why_not_at(expected, r.is_client)),
}
}
Ok((seq, out))
}
/// Why the message a flight needs at `message_sequence` is not there: nothing of the peer's
/// holds that number yet, or something else does.
fn why_not_at(&self, message_sequence: u16, is_client: bool) -> PullError {
if self.holds_message_at(message_sequence, is_client) {
PullError::OutOfOrder
} else {
PullError::Incomplete
}
}
/// Whether a message of the peer (`is_client`) under `message_sequence`, of any type and
/// epoch, has been received.
pub(crate) fn holds_message_at(&self, message_sequence: u16, is_client: bool) -> bool {
self.cache
.iter()
.any(|c| c.message_sequence == message_sequence && c.is_client == is_client)
}
// pull_and_merge calls pull and then merges the results, ignoring any null entries
pub(crate) fn pull_and_merge(&self, rules: &[HandshakeCachePullRule]) -> Vec<u8> {
let mut merged = vec![];
for p in &self.pull(rules) {
merged.extend_from_slice(&p.data);
}
merged
}
// session_hash returns the session hash for Extended Master Secret support
// https://tools.ietf.org/html/draft-ietf-tls-session-hash-06#section-4
pub(crate) fn session_hash(
&self,
crypto: &dyn crypto::RTCCrypto,
hf: CipherSuiteHash,
epoch: u16,
additional: &[u8],
) -> Result<Vec<u8>> {
let mut merged = vec![];
// Order defined by https://tools.ietf.org/html/rfc5246#section-7.3
let handshake_buffer = self.pull(&[
HandshakeCachePullRule {
typ: HandshakeType::ClientHello,
epoch,
is_client: true,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::ServerHello,
epoch,
is_client: false,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::Certificate,
epoch,
is_client: false,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::ServerKeyExchange,
epoch,
is_client: false,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::CertificateRequest,
epoch,
is_client: false,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::ServerHelloDone,
epoch,
is_client: false,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::Certificate,
epoch,
is_client: true,
optional: false,
},
HandshakeCachePullRule {
typ: HandshakeType::ClientKeyExchange,
epoch,
is_client: true,
optional: false,
},
]);
for p in &handshake_buffer {
merged.extend_from_slice(&p.data);
}
merged.extend_from_slice(additional);
crypto
.hash(hf.hash_algorithm(), &merged)
.map_err(|error| Error::Crypto(error.to_string()))
}
/// Whether `data`, one complete handshake message with its header, is byte for byte the
/// message cached under its sequence number for `epoch` and `is_client`: a repeat of a
/// message already received, not a different one under a reused sequence number.
pub(crate) fn contains_message(&self, data: &[u8], epoch: u16, is_client: bool) -> bool {
let mut reader = data;
let Ok(header) = HandshakeHeader::unmarshal(&mut reader) else {
return false;
};
self.cache.iter().any(|item| {
item.message_sequence == header.message_sequence
&& item.is_client == is_client
&& item.epoch == epoch
&& item.data == data
})
}
}