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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use crate::error::TLSError;
use crate::key_schedule::{derive_traffic_iv, derive_traffic_key};
use crate::msgs::codec;
use crate::msgs::codec::Codec;
use crate::msgs::enums::{ContentType, ProtocolVersion};
use crate::msgs::fragmenter::MAX_FRAGMENT_LEN;
use crate::msgs::message::{BorrowMessage, Message, MessagePayload};
use crate::session::SessionSecrets;
use crate::suites::SupportedCipherSuite;
use ring::{aead, hkdf};
use std::io::Write;
pub trait MessageDecrypter: Send + Sync {
fn decrypt(&self, m: Message, seq: u64) -> Result<Message, TLSError>;
}
pub trait MessageEncrypter: Send + Sync {
fn encrypt(&self, m: BorrowMessage, seq: u64) -> Result<Message, TLSError>;
}
impl dyn MessageEncrypter {
pub fn invalid() -> Box<dyn MessageEncrypter> {
Box::new(InvalidMessageEncrypter {})
}
}
impl dyn MessageDecrypter {
pub fn invalid() -> Box<dyn MessageDecrypter> {
Box::new(InvalidMessageDecrypter {})
}
}
pub type MessageCipherPair = (Box<dyn MessageDecrypter>, Box<dyn MessageEncrypter>);
const TLS12_AAD_SIZE: usize = 8 + 1 + 2 + 2;
fn make_tls12_aad(
seq: u64,
typ: ContentType,
vers: ProtocolVersion,
len: usize,
) -> ring::aead::Aad<[u8; TLS12_AAD_SIZE]> {
let mut out = [0; TLS12_AAD_SIZE];
codec::put_u64(seq, &mut out[0..]);
out[8] = typ.get_u8();
codec::put_u16(vers.get_u16(), &mut out[9..]);
codec::put_u16(len as u16, &mut out[11..]);
ring::aead::Aad::from(out)
}
fn make_tls12_gcm_nonce(write_iv: &[u8], explicit: &[u8]) -> Iv {
debug_assert_eq!(write_iv.len(), 4);
debug_assert_eq!(explicit.len(), 8);
let mut iv = Iv(Default::default());
iv.0[..4].copy_from_slice(write_iv);
iv.0[4..].copy_from_slice(explicit);
iv
}
pub type BuildTLS12Decrypter = fn(&[u8], &[u8]) -> Box<dyn MessageDecrypter>;
pub type BuildTLS12Encrypter = fn(&[u8], &[u8], &[u8]) -> Box<dyn MessageEncrypter>;
pub fn build_tls12_gcm_128_decrypter(key: &[u8], iv: &[u8]) -> Box<dyn MessageDecrypter> {
Box::new(GCMMessageDecrypter::new(&aead::AES_128_GCM, key, iv))
}
pub fn build_tls12_gcm_128_encrypter(
key: &[u8],
iv: &[u8],
extra: &[u8],
) -> Box<dyn MessageEncrypter> {
let nonce = make_tls12_gcm_nonce(iv, extra);
Box::new(GCMMessageEncrypter::new(&aead::AES_128_GCM, key, nonce))
}
pub fn build_tls12_gcm_256_decrypter(key: &[u8], iv: &[u8]) -> Box<dyn MessageDecrypter> {
Box::new(GCMMessageDecrypter::new(&aead::AES_256_GCM, key, iv))
}
pub fn build_tls12_gcm_256_encrypter(
key: &[u8],
iv: &[u8],
extra: &[u8],
) -> Box<dyn MessageEncrypter> {
let nonce = make_tls12_gcm_nonce(iv, extra);
Box::new(GCMMessageEncrypter::new(&aead::AES_256_GCM, key, nonce))
}
pub fn build_tls12_chacha_decrypter(key: &[u8], iv: &[u8]) -> Box<dyn MessageDecrypter> {
Box::new(ChaCha20Poly1305MessageDecrypter::new(
&aead::CHACHA20_POLY1305,
key,
Iv::copy(iv),
))
}
pub fn build_tls12_chacha_encrypter(key: &[u8], iv: &[u8], _: &[u8]) -> Box<dyn MessageEncrypter> {
Box::new(ChaCha20Poly1305MessageEncrypter::new(
&aead::CHACHA20_POLY1305,
key,
Iv::copy(iv),
))
}
pub fn new_tls12(
scs: &'static SupportedCipherSuite,
secrets: &SessionSecrets,
) -> MessageCipherPair {
let key_block = secrets.make_key_block(scs.key_block_len());
let mut offs = 0;
let client_write_key = &key_block[offs..offs + scs.enc_key_len];
offs += scs.enc_key_len;
let server_write_key = &key_block[offs..offs + scs.enc_key_len];
offs += scs.enc_key_len;
let client_write_iv = &key_block[offs..offs + scs.fixed_iv_len];
offs += scs.fixed_iv_len;
let server_write_iv = &key_block[offs..offs + scs.fixed_iv_len];
offs += scs.fixed_iv_len;
let (write_key, write_iv) = if secrets.randoms.we_are_client {
(client_write_key, client_write_iv)
} else {
(server_write_key, server_write_iv)
};
let (read_key, read_iv) = if secrets.randoms.we_are_client {
(server_write_key, server_write_iv)
} else {
(client_write_key, client_write_iv)
};
(
scs.build_tls12_decrypter.unwrap()(read_key, read_iv),
scs.build_tls12_encrypter.unwrap()(write_key, write_iv, &key_block[offs..]),
)
}
pub fn new_tls13_read(
scs: &'static SupportedCipherSuite,
secret: &hkdf::Prk,
) -> Box<dyn MessageDecrypter> {
let key = derive_traffic_key(secret, scs.aead_algorithm);
let iv = derive_traffic_iv(secret);
Box::new(TLS13MessageDecrypter::new(key, iv))
}
pub fn new_tls13_write(
scs: &'static SupportedCipherSuite,
secret: &hkdf::Prk,
) -> Box<dyn MessageEncrypter> {
let key = derive_traffic_key(secret, scs.aead_algorithm);
let iv = derive_traffic_iv(secret);
Box::new(TLS13MessageEncrypter::new(key, iv))
}
pub struct GCMMessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
pub struct GCMMessageDecrypter {
dec_key: aead::LessSafeKey,
dec_salt: [u8; 4],
}
const GCM_EXPLICIT_NONCE_LEN: usize = 8;
const GCM_OVERHEAD: usize = GCM_EXPLICIT_NONCE_LEN + 16;
impl MessageDecrypter for GCMMessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let payload = msg
.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < GCM_OVERHEAD {
return Err(TLSError::DecryptError);
}
let nonce = {
let mut nonce = [0u8; 12];
nonce
.as_mut()
.write_all(&self.dec_salt)
.unwrap();
nonce[4..]
.as_mut()
.write_all(&buf[..8])
.unwrap();
aead::Nonce::assume_unique_for_key(nonce)
};
let aad = make_tls12_aad(seq, msg.typ, msg.version, buf.len() - GCM_OVERHEAD);
let plain_len = self
.dec_key
.open_within(nonce, aad, &mut buf, GCM_EXPLICIT_NONCE_LEN..)
.map_err(|_| TLSError::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
buf.truncate(plain_len);
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageEncrypter for GCMMessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
let nonce = make_tls13_nonce(&self.iv, seq);
let aad = make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len());
let total_len = msg.payload.len() + self.enc_key.algorithm().tag_len();
let mut payload = Vec::with_capacity(GCM_EXPLICIT_NONCE_LEN + total_len);
payload.extend_from_slice(&nonce.as_ref()[4..]);
payload.extend_from_slice(&msg.payload);
self.enc_key
.seal_in_place_separate_tag(nonce, aad, &mut payload[GCM_EXPLICIT_NONCE_LEN..])
.map(|tag| payload.extend(tag.as_ref()))
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(payload),
})
}
}
impl GCMMessageEncrypter {
fn new(alg: &'static aead::Algorithm, enc_key: &[u8], iv: Iv) -> GCMMessageEncrypter {
let key = aead::UnboundKey::new(alg, enc_key).unwrap();
GCMMessageEncrypter {
enc_key: aead::LessSafeKey::new(key),
iv,
}
}
}
impl GCMMessageDecrypter {
fn new(alg: &'static aead::Algorithm, dec_key: &[u8], dec_iv: &[u8]) -> GCMMessageDecrypter {
let key = aead::UnboundKey::new(alg, dec_key).unwrap();
let mut ret = GCMMessageDecrypter {
dec_key: aead::LessSafeKey::new(key),
dec_salt: [0u8; 4],
};
debug_assert_eq!(dec_iv.len(), 4);
ret.dec_salt
.as_mut()
.write_all(dec_iv)
.unwrap();
ret
}
}
pub(crate) struct Iv([u8; ring::aead::NONCE_LEN]);
impl Iv {
pub(crate) fn new(value: [u8; ring::aead::NONCE_LEN]) -> Self {
Self(value)
}
fn copy(value: &[u8]) -> Self {
debug_assert_eq!(value.len(), ring::aead::NONCE_LEN);
let mut iv = Iv::new(Default::default());
iv.0.copy_from_slice(value);
iv
}
#[cfg(test)]
pub(crate) fn value(&self) -> &[u8; 12] {
&self.0
}
}
pub(crate) struct IvLen;
impl hkdf::KeyType for IvLen {
fn len(&self) -> usize {
aead::NONCE_LEN
}
}
impl From<hkdf::Okm<'_, IvLen>> for Iv {
fn from(okm: hkdf::Okm<IvLen>) -> Self {
let mut r = Iv(Default::default());
okm.fill(&mut r.0[..]).unwrap();
r
}
}
struct TLS13MessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
struct TLS13MessageDecrypter {
dec_key: aead::LessSafeKey,
iv: Iv,
}
fn unpad_tls13(v: &mut Vec<u8>) -> ContentType {
loop {
match v.pop() {
Some(0) => {}
Some(content_type) => return ContentType::read_bytes(&[content_type]).unwrap(),
None => return ContentType::Unknown(0),
}
}
}
fn make_tls13_nonce(iv: &Iv, seq: u64) -> ring::aead::Nonce {
let mut nonce = [0u8; ring::aead::NONCE_LEN];
codec::put_u64(seq, &mut nonce[4..]);
nonce
.iter_mut()
.zip(iv.0.iter())
.for_each(|(nonce, iv)| {
*nonce ^= *iv;
});
aead::Nonce::assume_unique_for_key(nonce)
}
fn make_tls13_aad(len: usize) -> ring::aead::Aad<[u8; 1 + 2 + 2]> {
ring::aead::Aad::from([
0x17,
0x3,
0x3,
(len >> 8) as u8,
len as u8,
])
}
impl MessageEncrypter for TLS13MessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
let total_len = msg.payload.len() + 1 + self.enc_key.algorithm().tag_len();
let mut buf = Vec::with_capacity(total_len);
buf.extend_from_slice(&msg.payload);
msg.typ.encode(&mut buf);
let nonce = make_tls13_nonce(&self.iv, seq);
let aad = make_tls13_aad(total_len);
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut buf)
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: ContentType::ApplicationData,
version: ProtocolVersion::TLSv1_2,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageDecrypter for TLS13MessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let payload = msg
.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < self.dec_key.algorithm().tag_len() {
return Err(TLSError::DecryptError);
}
let nonce = make_tls13_nonce(&self.iv, seq);
let aad = make_tls13_aad(buf.len());
let plain_len = self
.dec_key
.open_in_place(nonce, aad, &mut buf)
.map_err(|_| TLSError::DecryptError)?
.len();
buf.truncate(plain_len);
if buf.len() > MAX_FRAGMENT_LEN + 1 {
return Err(TLSError::PeerSentOversizedRecord);
}
let content_type = unpad_tls13(&mut buf);
if content_type == ContentType::Unknown(0) {
let msg = "peer sent bad TLSInnerPlaintext".to_string();
return Err(TLSError::PeerMisbehavedError(msg));
}
if buf.len() > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
Ok(Message {
typ: content_type,
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl TLS13MessageEncrypter {
fn new(key: aead::UnboundKey, enc_iv: Iv) -> TLS13MessageEncrypter {
TLS13MessageEncrypter {
enc_key: aead::LessSafeKey::new(key),
iv: enc_iv,
}
}
}
impl TLS13MessageDecrypter {
fn new(key: aead::UnboundKey, dec_iv: Iv) -> TLS13MessageDecrypter {
TLS13MessageDecrypter {
dec_key: aead::LessSafeKey::new(key),
iv: dec_iv,
}
}
}
pub struct ChaCha20Poly1305MessageEncrypter {
enc_key: aead::LessSafeKey,
enc_offset: Iv,
}
pub struct ChaCha20Poly1305MessageDecrypter {
dec_key: aead::LessSafeKey,
dec_offset: Iv,
}
impl ChaCha20Poly1305MessageEncrypter {
fn new(
alg: &'static aead::Algorithm,
enc_key: &[u8],
enc_iv: Iv,
) -> ChaCha20Poly1305MessageEncrypter {
let key = aead::UnboundKey::new(alg, enc_key).unwrap();
ChaCha20Poly1305MessageEncrypter {
enc_key: aead::LessSafeKey::new(key),
enc_offset: enc_iv,
}
}
}
impl ChaCha20Poly1305MessageDecrypter {
fn new(
alg: &'static aead::Algorithm,
dec_key: &[u8],
dec_iv: Iv,
) -> ChaCha20Poly1305MessageDecrypter {
let key = aead::UnboundKey::new(alg, dec_key).unwrap();
ChaCha20Poly1305MessageDecrypter {
dec_key: aead::LessSafeKey::new(key),
dec_offset: dec_iv,
}
}
}
const CHACHAPOLY1305_OVERHEAD: usize = 16;
impl MessageDecrypter for ChaCha20Poly1305MessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let payload = msg
.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < CHACHAPOLY1305_OVERHEAD {
return Err(TLSError::DecryptError);
}
let nonce = make_tls13_nonce(&self.dec_offset, seq);
let aad = make_tls12_aad(
seq,
msg.typ,
msg.version,
buf.len() - CHACHAPOLY1305_OVERHEAD,
);
let plain_len = self
.dec_key
.open_in_place(nonce, aad, &mut buf)
.map_err(|_| TLSError::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
buf.truncate(plain_len);
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageEncrypter for ChaCha20Poly1305MessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
let nonce = make_tls13_nonce(&self.enc_offset, seq);
let aad = make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len());
let total_len = msg.payload.len() + self.enc_key.algorithm().tag_len();
let mut buf = Vec::with_capacity(total_len);
buf.extend_from_slice(&msg.payload);
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut buf)
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
pub struct InvalidMessageEncrypter {}
impl MessageEncrypter for InvalidMessageEncrypter {
fn encrypt(&self, _m: BorrowMessage, _seq: u64) -> Result<Message, TLSError> {
Err(TLSError::General("encrypt not yet available".to_string()))
}
}
pub struct InvalidMessageDecrypter {}
impl MessageDecrypter for InvalidMessageDecrypter {
fn decrypt(&self, _m: Message, _seq: u64) -> Result<Message, TLSError> {
Err(TLSError::DecryptError)
}
}