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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// Copyright (c) 2019-2026, Argenox Technologies LLC
// All rights reserved.
//
// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
//
// This file is part of the NoxTLS Library.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation; version 2 of the License.
//
// Alternatively, this file may be used under the terms of a commercial
// license from Argenox Technologies LLC.
//
// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
// CONTACT: info@argenox.com
//! TLS 1.3 handshake message construction, validation, and key schedule transitions.
use super::*;
impl Connection {
/// Builds a minimal TLS 1.3 Certificate handshake message with one certificate entry.
///
/// # Arguments
/// * `certificate_der`: DER-encoded certificate bytes.
///
/// # Returns
/// Encoded Certificate message bytes.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_certificate_message(certificate_der: &[u8]) -> Result<Vec<u8>> {
Self::noxtls_build_certificate_message_with_ocsp_staple(certificate_der, None)
}
/// Builds a TLS 1.3 Certificate handshake message with a complete certificate chain.
pub fn noxtls_build_certificate_chain_message(
certificate_chain_der: &[Vec<u8>],
) -> Result<Vec<u8>> {
if certificate_chain_der.is_empty() {
return Err(Error::InvalidLength("certificate chain must not be empty"));
}
let mut entries = Vec::new();
for certificate_der in certificate_chain_der {
if certificate_der.is_empty() {
return Err(Error::InvalidLength("certificate der must not be empty"));
}
if certificate_der.len() > 0x00FF_FFFF {
return Err(Error::InvalidLength("certificate der is too large"));
}
let cert_len = certificate_der.len() as u32;
entries.extend_from_slice(&cert_len.to_be_bytes()[1..4]);
entries.extend_from_slice(certificate_der);
entries.extend_from_slice(&0_u16.to_be_bytes());
}
if entries.len() > 0x00FF_FFFF {
return Err(Error::InvalidLength("certificate chain is too large"));
}
let mut body = Vec::new();
body.push(0x00);
let list_len = entries.len() as u32;
body.extend_from_slice(&list_len.to_be_bytes()[1..4]);
body.extend_from_slice(&entries);
Ok(noxtls_encode_handshake_message(
HANDSHAKE_CERTIFICATE,
&body,
))
}
/// Builds an RFC 8879 TLS 1.3 CompressedCertificate message using zlib.
///
/// The compressed payload is the Certificate message body, and this handshake message replaces
/// the normal Certificate message in the transcript when negotiated.
#[cfg(feature = "std")]
pub fn noxtls_build_zlib_compressed_certificate_message(
certificate_der: &[u8],
) -> Result<Vec<u8>> {
use flate2::{write::ZlibEncoder, Compression};
use std::io::Write as _;
let certificate = Self::noxtls_build_certificate_message(certificate_der)?;
let (_, certificate_body) = noxtls_parse_handshake_message(&certificate)?;
if certificate_body.len() > 0x00FF_FFFF {
return Err(Error::InvalidLength("certificate body is too large"));
}
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder
.write_all(certificate_body)
.map_err(|_| Error::CryptoFailure("zlib certificate compression failed"))?;
let compressed = encoder
.finish()
.map_err(|_| Error::CryptoFailure("zlib certificate compression failed"))?;
if compressed.is_empty() || compressed.len() > 0x00FF_FFFF {
return Err(Error::InvalidLength(
"compressed certificate body has invalid length",
));
}
let mut body = Vec::new();
body.extend_from_slice(&TLS13_CERT_COMPRESSION_ZLIB.to_be_bytes());
let uncompressed_len = certificate_body.len() as u32;
body.extend_from_slice(&uncompressed_len.to_be_bytes()[1..4]);
let compressed_len = compressed.len() as u32;
body.extend_from_slice(&compressed_len.to_be_bytes()[1..4]);
body.extend_from_slice(&compressed);
Ok(noxtls_encode_handshake_message(
HANDSHAKE_COMPRESSED_CERTIFICATE,
&body,
))
}
/// Builds a TLS 1.3 Certificate handshake message with optional leaf OCSP staple.
///
/// # Arguments
/// * `certificate_der`: DER-encoded certificate bytes.
/// * `ocsp_staple`: Optional stapled OCSP response bytes for leaf certificate entry.
///
/// # Returns
/// Encoded Certificate message bytes.
///
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
pub fn noxtls_build_certificate_message_with_ocsp_staple(
certificate_der: &[u8],
ocsp_staple: Option<&[u8]>,
) -> Result<Vec<u8>> {
if certificate_der.is_empty() {
return Err(Error::InvalidLength("certificate der must not be empty"));
}
if certificate_der.len() > 0x00FF_FFFF {
return Err(Error::InvalidLength("certificate der is too large"));
}
let certificate_extensions = if let Some(staple) = ocsp_staple {
noxtls_encode_certificate_entry_status_request_extension(staple)?
} else {
Vec::new()
};
let mut body = Vec::new();
body.push(0x00); // certificate_request_context length
let cert_entry_len = 3 + certificate_der.len() + 2 + certificate_extensions.len();
let list_len = cert_entry_len as u32;
body.extend_from_slice(&list_len.to_be_bytes()[1..4]);
let cert_len = certificate_der.len() as u32;
body.extend_from_slice(&cert_len.to_be_bytes()[1..4]);
body.extend_from_slice(certificate_der);
body.extend_from_slice(&(certificate_extensions.len() as u16).to_be_bytes());
body.extend_from_slice(&certificate_extensions);
Ok(noxtls_encode_handshake_message(
HANDSHAKE_CERTIFICATE,
&body,
))
}
/// Parses and records a TLS 1.3 CertificateVerify handshake message.
///
/// # Arguments
/// * `msg`: Encoded CertificateVerify handshake message.
///
/// # Returns
/// `Ok(())` when message type validates and transcript is updated.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_recv_certificate_verify(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::ServerCertificateReceived {
return Err(Error::StateError(
"certificate verify can only be processed after certificate",
));
}
let (handshake_type, body) = noxtls_parse_handshake_message(msg)?;
if handshake_type != HANDSHAKE_CERTIFICATE_VERIFY {
return Err(Error::ParseFailure("invalid certificate verify type"));
}
let (signature_scheme, signature) = noxtls_parse_certificate_verify_fields(body)?;
if signature.is_empty() {
return Err(Error::ParseFailure(
"certificate verify signature must not be empty",
));
}
if !noxtls_tls13_supported_certificate_verify_signature_scheme(signature_scheme) {
return Err(Error::UnsupportedFeature(
"unsupported tls13 certificate verify signature scheme",
));
}
if self.tls13_require_certificate_auth {
if !self.tls13_server_certificate_chain_validated {
return Err(Error::StateError(
"certificate verify requires validated server certificate chain",
));
}
self.noxtls_verify_tls13_server_certificate_verify_signature(
signature_scheme,
signature,
)?;
}
self.tls13_negotiated_certificate_verify_signature_scheme = Some(signature_scheme);
self.noxtls_append_transcript(msg);
self.state = HandshakeState::ServerCertificateVerified;
Ok(())
}
/// Builds a minimal TLS 1.3 CertificateVerify handshake message.
///
/// # Arguments
/// * `signature_scheme`: Signature scheme identifier.
/// * `signature`: Signature bytes.
///
/// # Returns
/// Encoded CertificateVerify message bytes.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_certificate_verify_message(
signature_scheme: u16,
signature: &[u8],
) -> Result<Vec<u8>> {
if signature.is_empty() {
return Err(Error::InvalidLength(
"certificate verify signature must not be empty",
));
}
if signature.len() > usize::from(u16::MAX) {
return Err(Error::InvalidLength(
"certificate verify signature is too large",
));
}
let mut body = Vec::new();
body.extend_from_slice(&signature_scheme.to_be_bytes());
body.extend_from_slice(&(signature.len() as u16).to_be_bytes());
body.extend_from_slice(signature);
Ok(noxtls_encode_handshake_message(
HANDSHAKE_CERTIFICATE_VERIFY,
&body,
))
}
/// Derives a prototype handshake secret from the selected transcript hash bytes.
///
/// # Arguments
/// * `self`: Connection with ServerHello already processed.
///
/// # Returns
/// 32-byte derived handshake secret.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_derive_handshake_secret(&mut self) -> Result<[u8; 32]> {
if self.version.uses_tls13_handshake_semantics() {
let allowed_state = if self.tls_role == TlsRole::Server {
self.state == HandshakeState::ServerHelloSent
} else {
matches!(
self.state,
HandshakeState::ServerHelloReceived
| HandshakeState::ServerEncryptedExtensionsReceived
| HandshakeState::ServerCertificateRequestReceived
| HandshakeState::ServerCertificateReceived
| HandshakeState::ServerCertificateVerified
| HandshakeState::KeysDerived
)
};
if !allowed_state {
return Err(Error::StateError(
"tls13 handshake traffic keys require server hello processing",
));
}
} else if self.state != HandshakeState::ServerHelloReceived
&& self.state != HandshakeState::ServerCertificateVerified
&& !(matches!(self.version, TlsVersion::Tls12 | TlsVersion::Dtls12)
&& self.tls12_pre_master_secret.is_some()
&& self.tls12_client_random.is_some()
&& self.tls12_server_random.is_some())
{
return Err(Error::StateError(
"cannot derive handshake secret before server hello",
));
}
let noxtls_transcript_hash = self.noxtls_transcript_hash();
let noxtls_hash_algorithm = self.noxtls_negotiated_hash_algorithm();
noxtls_tls13_debug_log(
"tls13.kdf.hash_algorithm",
noxtls_hash_algorithm_name(noxtls_hash_algorithm),
);
noxtls_tls13_debug_log_bytes("tls13.kdf.transcript_hash", &noxtls_transcript_hash);
if self.version.uses_tls13_handshake_semantics() {
if let Some(secret) = self.tls13_shared_secret.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.kdf.shared_secret_input", secret);
} else {
noxtls_tls13_debug_log("tls13.kdf.shared_secret_input", "none");
}
}
let secret_material = match self.version {
TlsVersion::Tls13 | TlsVersion::Dtls13 => noxtls_derive_tls13_handshake_secret(
noxtls_hash_algorithm,
self.tls13_shared_secret
.as_ref()
.map_or(&noxtls_transcript_hash, |secret| secret),
self.noxtls_selected_cipher_suite,
)?,
TlsVersion::Tls12 | TlsVersion::Dtls12 => {
if let Some(pre_master_secret) = self.tls12_pre_master_secret.as_ref() {
let client_random = self
.tls12_client_random
.ok_or(Error::StateError("tls12 client random is not available"))?;
let server_random = self
.tls12_server_random
.ok_or(Error::StateError("tls12 server random is not available"))?;
let seed_storage;
let (label, seed) = if let Some(session_hash) =
self.tls12_extended_master_secret_session_hash.as_ref()
{
(b"extended master secret" as &[u8], session_hash.as_slice())
} else {
seed_storage = {
let mut random_seed = Vec::with_capacity(64);
random_seed.extend_from_slice(&client_random);
random_seed.extend_from_slice(&server_random);
random_seed
};
(b"master secret" as &[u8], seed_storage.as_slice())
};
let master = noxtls_tls12_prf_for_hash(
noxtls_hash_algorithm,
pre_master_secret,
label,
seed,
48,
)?;
let mut master_secret = [0_u8; 48];
master_secret.copy_from_slice(&master);
self.tls12_master_secret = Some(master_secret);
master
} else {
let prk = noxtls_hkdf_extract_for_hash(
noxtls_hash_algorithm,
&noxtls_transcript_hash,
);
noxtls_tls12_prf_for_hash(
noxtls_hash_algorithm,
&prk,
b"handshake secret",
&noxtls_transcript_hash,
32,
)?
}
}
TlsVersion::Tls10 | TlsVersion::Tls11 => {
let prk =
noxtls_hkdf_extract_for_hash(noxtls_hash_algorithm, &noxtls_transcript_hash);
noxtls_hkdf_expand_for_hash(noxtls_hash_algorithm, &prk, b"handshake secret", 32)?
}
};
noxtls_tls13_debug_log_bytes("tls13.kdf.handshake_secret", &secret_material);
self.noxtls_install_traffic_keys(
noxtls_hash_algorithm,
&secret_material,
&noxtls_transcript_hash,
)?;
if self.version.uses_tls13_handshake_semantics() {
if let Some(secret) = self.tls13_client_handshake_traffic_secret.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.kdf.client_hs_traffic_secret", secret);
}
if let Some(secret) = self.tls13_server_handshake_traffic_secret.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.kdf.server_hs_traffic_secret", secret);
}
if let Some(key) = self.client_write_key.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.record.client_write_key", key);
}
if let Some(key) = self.server_write_key.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.record.server_write_key", key);
}
if let Some(iv) = self.client_write_iv.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.record.client_write_iv", iv);
}
if let Some(iv) = self.server_write_iv.as_ref() {
noxtls_tls13_debug_log_bytes("tls13.record.server_write_iv", iv);
}
}
self.handshake_secret = Some(secret_material.clone());
let mut secret = [0_u8; 32];
let copy_len = secret_material.len().min(32);
secret[..copy_len].copy_from_slice(&secret_material[..copy_len]);
self.state = HandshakeState::KeysDerived;
Ok(secret)
}
/// Finalizes the handshake and records verify data in transcript history.
///
/// # Arguments
/// * `verify_data`: Finished verify_data bytes to validate and record.
///
/// # Returns
/// `Ok(())` when Finished verification succeeds.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_finish(&mut self, verify_data: &[u8]) -> Result<()> {
if self.state != HandshakeState::KeysDerived
&& self.state != HandshakeState::ServerCertificateVerified
{
return Err(Error::StateError(
"noxtls_finish must follow key derivation",
));
}
let expected = self.noxtls_compute_finished_verify_data()?;
if verify_data != expected.as_slice() {
return Err(Error::CryptoFailure("finished verify_data mismatch"));
}
if self.version.uses_tls13_handshake_semantics() {
let finished_message = noxtls_encode_handshake_message(HANDSHAKE_FINISHED, verify_data);
self.noxtls_append_transcript(&finished_message);
} else {
self.noxtls_append_transcript(verify_data);
if self.version == TlsVersion::Tls12 {
if self.tls_role == TlsRole::Server {
self.tls12_secure_renegotiation_server_verify_data = verify_data.to_vec();
} else {
self.tls12_secure_renegotiation_client_verify_data = verify_data.to_vec();
}
self.tls12_secure_renegotiation_renegotiating = false;
}
}
self.state = HandshakeState::Finished;
Ok(())
}
/// Parses a TLS 1.3 Finished handshake wrapper and validates verify_data.
///
/// # Arguments
/// * `msg`: Encoded Finished handshake message.
///
/// # Returns
/// `Ok(())` when Finished verifies and state transitions to `Finished`.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_recv_finished_message(&mut self, msg: &[u8]) -> Result<()> {
let (handshake_type, body) = noxtls_parse_handshake_message(msg)?;
if handshake_type != HANDSHAKE_FINISHED {
return Err(Error::ParseFailure("invalid finished type"));
}
if self.state != HandshakeState::KeysDerived
&& self.state != HandshakeState::ServerCertificateVerified
{
return Err(Error::StateError(
"noxtls_finish must follow key derivation",
));
}
let expected = self.noxtls_compute_expected_finished()?;
if body.len() != expected.len() {
return Err(Error::ParseFailure("finished verify_data length mismatch"));
}
if body != expected.as_slice() {
return Err(Error::CryptoFailure("finished verify_data mismatch"));
}
self.noxtls_append_transcript(msg);
self.state = HandshakeState::Finished;
Ok(())
}
/// Activates TLS 1.3 application traffic keys after local Finished has been sent.
///
/// # Arguments
///
/// * `self` — `&mut self`.
///
/// # Returns
///
/// `Ok(())` when application traffic keys are installed for post-handshake records.
///
/// # Errors
///
/// Returns [`noxtls_core::Error`] when called outside TLS 1.3 `Finished` state or when
/// key-schedule material is unavailable.
///
/// # Panics
///
/// This function does not panic.
pub fn noxtls_activate_tls13_application_traffic_keys(&mut self) -> Result<()> {
if !self.version.uses_tls13_handshake_semantics() {
return Err(Error::StateError(
"application traffic key activation requires TLS 1.3 connection",
));
}
if self.state != HandshakeState::Finished {
return Err(Error::StateError(
"application traffic keys can only be activated in finished state",
));
}
self.noxtls_install_tls13_application_traffic_keys()
}
/// Builds local TLS 1.3 Finished handshake message from current transcript state.
///
/// # Arguments
///
/// * `&self` — `&self`.
///
/// # Returns
/// Encoded Finished handshake message bytes.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_finished_message(&self) -> Result<Vec<u8>> {
let verify_data = self.noxtls_compute_finished_verify_data()?;
Ok(noxtls_encode_handshake_message(
HANDSHAKE_FINISHED,
&verify_data,
))
}
/// Builds a TLS Finished handshake message for the **peer** (e.g. server's Finished on a client `Connection`).
///
/// This wraps [`Self::noxtls_compute_expected_finished`] as a handshake message. Use this when
/// modeling inbound server Finished bytes; use [`Self::noxtls_build_finished_message`] for the
/// local endpoint's Finished to transmit.
///
/// # Arguments
///
/// * `&self` — `&self`.
///
/// # Returns
///
/// Encoded `Finished` handshake message bytes.
///
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_peer_finished_message(&self) -> Result<Vec<u8>> {
let verify_data = self.noxtls_compute_expected_finished()?;
Ok(noxtls_encode_handshake_message(
HANDSHAKE_FINISHED,
&verify_data,
))
}
/// Builds a minimal TLS 1.3 NewSessionTicket handshake message.
///
/// # Arguments
/// * `ticket_lifetime`: Ticket lifetime in seconds.
/// * `ticket_age_add`: Obfuscation value for ticket age.
/// * `ticket_nonce`: Ticket nonce bytes.
/// * `ticket`: Opaque ticket identity bytes.
///
/// # Returns
/// Encoded NewSessionTicket message bytes.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_new_session_ticket_message(
ticket_lifetime: u32,
ticket_age_add: u32,
ticket_nonce: &[u8],
ticket: &[u8],
) -> Result<Vec<u8>> {
if ticket_nonce.len() > usize::from(u8::MAX) {
return Err(Error::InvalidLength("ticket nonce is too large"));
}
if ticket.len() > usize::from(u16::MAX) {
return Err(Error::InvalidLength("ticket identity is too large"));
}
let mut body = Vec::new();
body.extend_from_slice(&ticket_lifetime.to_be_bytes());
body.extend_from_slice(&ticket_age_add.to_be_bytes());
body.push(ticket_nonce.len() as u8);
body.extend_from_slice(ticket_nonce);
body.extend_from_slice(&(ticket.len() as u16).to_be_bytes());
body.extend_from_slice(ticket);
body.extend_from_slice(&0_u16.to_be_bytes()); // extensions length
Ok(noxtls_encode_handshake_message(
HANDSHAKE_NEW_SESSION_TICKET,
&body,
))
}
/// Parses and records a TLS 1.3 NewSessionTicket handshake message.
///
/// # Arguments
/// * `msg`: Encoded NewSessionTicket handshake message.
///
/// # Returns
/// `Ok(())` when message type validates and transcript is updated.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_recv_new_session_ticket_message(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::Finished {
return Err(Error::StateError(
"noxtls_new session ticket requires finished handshake state",
));
}
let (handshake_type, body) = noxtls_parse_handshake_message(msg)?;
if handshake_type != HANDSHAKE_NEW_SESSION_TICKET {
return Err(Error::ParseFailure(
"invalid noxtls_new session ticket type",
));
}
noxtls_parse_new_session_ticket_body(body)?;
self.noxtls_append_transcript(msg);
Ok(())
}
/// Builds a TLS 1.3 KeyUpdate handshake message.
///
/// # Arguments
/// * `request_update`: Whether peer should also noxtls_update its sending keys.
///
/// # Returns
/// Encoded KeyUpdate message bytes.
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_build_key_update_message(request_update: bool) -> Vec<u8> {
let request = if request_update { 1_u8 } else { 0_u8 };
noxtls_encode_handshake_message(HANDSHAKE_KEY_UPDATE, &[request])
}
/// Parses a TLS 1.3 KeyUpdate handshake message and rotates traffic keys.
///
/// # Arguments
/// * `msg`: Encoded KeyUpdate handshake message.
///
/// # Returns
/// `Ok(())` when KeyUpdate parses and local keys rotate successfully.
/// # Errors
///
/// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_recv_key_update_message(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::Finished {
return Err(Error::StateError(
"key noxtls_update requires finished handshake state",
));
}
let (handshake_type, body) = noxtls_parse_handshake_message(msg)?;
if handshake_type != HANDSHAKE_KEY_UPDATE {
return Err(Error::ParseFailure("invalid key noxtls_update type"));
}
if body.len() != 1 || body[0] > 1 {
return Err(Error::ParseFailure(
"invalid key noxtls_update request value",
));
}
self.noxtls_update_tls13_traffic_keys()?;
self.noxtls_append_transcript(msg);
Ok(())
}
}