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
// 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.2 handshake sequencing and message-shape helpers for `Connection`.
use super::tls12_security::noxtls_parse_tls12_signature_fields;
use super::*;
impl Connection {
/// Processes TLS 1.2 server handshake flight in canonical order.
///
/// Expected sequence:
/// * `ServerHello`
/// * `Certificate`
/// * optional `ServerKeyExchange`
/// * optional `CertificateRequest`
/// * `ServerHelloDone`
///
/// # Arguments
/// * `messages`: Ordered handshake messages from server.
///
/// # Returns
/// `Ok(())` when the full flight validates and transitions to `ServerCertificateVerified`.
/// # 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_process_tls12_server_handshake_flight(
&mut self,
messages: &[Vec<u8>],
) -> Result<()> {
if self.version != TlsVersion::Tls12 {
return Err(Error::StateError(
"tls12 server flight processing requires tls1.2 connection version",
));
}
if self.state != HandshakeState::ClientHelloSent {
return Err(Error::StateError(
"tls12 server flight can only be processed after client hello",
));
}
if messages.len() < 3 {
return Err(Error::ParseFailure(
"tls12 server handshake flight is too short",
));
}
let mut index = 0_usize;
self.noxtls_recv_server_hello(&messages[index])?;
index += 1;
let (next_type, _body) = noxtls_parse_handshake_message(&messages[index])?;
if next_type != HANDSHAKE_CERTIFICATE {
return Err(Error::ParseFailure(
"tls12 server handshake flight expected certificate after server hello",
));
}
self.noxtls_recv_tls12_server_certificate(&messages[index])?;
index += 1;
while index < messages.len() {
let (message_type, _body) = noxtls_parse_handshake_message(&messages[index])?;
if message_type == HANDSHAKE_SERVER_KEY_EXCHANGE {
self.noxtls_recv_tls12_server_key_exchange(&messages[index])?;
index += 1;
continue;
}
if message_type == HANDSHAKE_CERTIFICATE_REQUEST {
self.noxtls_recv_tls12_server_certificate_request(&messages[index])?;
index += 1;
continue;
}
break;
}
if index >= messages.len() {
return Err(Error::ParseFailure(
"tls12 server handshake flight missing server hello done",
));
}
self.noxtls_recv_tls12_server_hello_done(&messages[index])?;
index += 1;
if index != messages.len() {
return Err(Error::ParseFailure(
"unexpected trailing tls12 server handshake messages",
));
}
self.state = HandshakeState::ServerCertificateVerified;
Ok(())
}
/// Records an inbound TLS 1.2 ChangeCipherSpec transition before client Finished.
///
/// # Arguments
///
/// * `self` — `&mut self`.
///
/// # Returns
/// `Ok(())` when the transition is accepted for the current handshake phase.
/// # 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_tls12_change_cipher_spec(&mut self) -> Result<()> {
if self.version != TlsVersion::Tls12 {
return Err(Error::StateError(
"tls12 change cipher spec requires tls1.2 connection version",
));
}
if self.state != HandshakeState::ServerCertificateVerified {
return Err(Error::StateError(
"tls12 change cipher spec can only be processed after server handshake flight",
));
}
self.tls12_change_cipher_spec_seen = true;
Ok(())
}
/// Processes TLS 1.2 client handshake flight after server has sent `ServerHelloDone`.
///
/// Expected sequence:
/// * `ClientKeyExchange`
/// * optional `CertificateVerify`
/// * `Finished` (requires prior `ChangeCipherSpec` signal)
///
/// # Arguments
/// * `messages`: Ordered client handshake messages from the peer.
///
/// # Returns
/// `Ok(())` when client flight validates and 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_process_tls12_client_handshake_flight(
&mut self,
messages: &[Vec<u8>],
) -> Result<()> {
if self.version != TlsVersion::Tls12 {
return Err(Error::StateError(
"tls12 client flight processing requires tls1.2 connection version",
));
}
if self.state != HandshakeState::ServerCertificateVerified {
return Err(Error::StateError(
"tls12 client flight can only be processed after server handshake flight",
));
}
if messages.len() < 2 {
return Err(Error::ParseFailure(
"tls12 client handshake flight is too short",
));
}
let mut index = 0_usize;
let (next_type, _body) = noxtls_parse_handshake_message(&messages[index])?;
if next_type != HANDSHAKE_CLIENT_KEY_EXCHANGE {
return Err(Error::ParseFailure(
"tls12 client handshake flight expected client key exchange first",
));
}
self.noxtls_recv_tls12_client_key_exchange(&messages[index])?;
index += 1;
if index < messages.len() {
let (message_type, _body) = noxtls_parse_handshake_message(&messages[index])?;
if message_type == HANDSHAKE_CERTIFICATE_VERIFY {
self.noxtls_recv_tls12_client_certificate_verify(&messages[index])?;
index += 1;
}
}
if !self.tls12_change_cipher_spec_seen {
return Err(Error::ParseFailure(
"tls12 expected change cipher spec before finished",
));
}
if index >= messages.len() {
return Err(Error::ParseFailure(
"tls12 client handshake flight missing finished message",
));
}
self.noxtls_recv_tls12_client_finished(&messages[index])?;
index += 1;
if index != messages.len() {
return Err(Error::ParseFailure(
"unexpected trailing tls12 client handshake messages",
));
}
self.tls12_change_cipher_spec_seen = false;
self.state = HandshakeState::Finished;
Ok(())
}
/// Processes TLS 1.2 server flight and attempts automatic alert emission on failure.
///
/// # Arguments
/// * `messages`: Ordered handshake messages from server.
///
/// # Returns
/// `Ok(())` on successful processing, or `Err((error, alert_packet))` where `alert_packet`
/// contains the mapped TLS 1.2 alert packet when emission succeeds on this connection.
/// # 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_process_tls12_server_handshake_flight_with_alert(
&mut self,
messages: &[Vec<u8>],
) -> core::result::Result<(), (Error, Option<Vec<u8>>)> {
match self.noxtls_process_tls12_server_handshake_flight(messages) {
Ok(()) => Ok(()),
Err(error) => {
let alert_packet = self
.noxtls_send_tls12_alert_for_handshake_error(&error)
.ok();
Err((error, alert_packet))
}
}
}
/// Processes TLS 1.2 client flight and attempts automatic alert emission on failure.
///
/// # Arguments
/// * `messages`: Ordered handshake messages from client.
///
/// # Returns
/// `Ok(())` on successful processing, or `Err((error, alert_packet))` where `alert_packet`
/// contains the mapped TLS 1.2 alert packet when emission succeeds on this connection.
/// # 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_process_tls12_client_handshake_flight_with_alert(
&mut self,
messages: &[Vec<u8>],
) -> core::result::Result<(), (Error, Option<Vec<u8>>)> {
match self.noxtls_process_tls12_client_handshake_flight(messages) {
Ok(()) => Ok(()),
Err(error) => {
let alert_packet = self
.noxtls_send_tls12_alert_for_handshake_error(&error)
.ok();
Err((error, alert_packet))
}
}
}
/// Maps a TLS 1.2 handshake processing error into a deterministic fatal alert description.
///
/// # Arguments
/// * `error`: Handshake processing error returned by TLS 1.2 sequencing/parsing helpers.
///
/// # Returns
/// `(AlertLevel::Fatal, AlertDescription)` selected for wire-level signaling policy.
#[must_use]
/// # Arguments
///
/// * `error` — `error: &Error`.
///
/// # Returns
///
/// The value described by the return type in the function signature.
///
/// # Panics
///
/// This function does not panic.
///
pub fn noxtls_tls12_alert_for_handshake_error(error: &Error) -> (AlertLevel, AlertDescription) {
let description = match error {
Error::StateError(message) => {
if message.contains("can only be processed")
|| message.contains("expected")
|| message.contains("missing")
{
AlertDescription::UnexpectedMessage
} else {
AlertDescription::InternalError
}
}
Error::ParseFailure(message) | Error::InvalidLength(message) => {
if message.contains("expected")
|| message.contains("missing")
|| message.contains("unexpected trailing")
|| message.contains("invalid")
|| message.contains("malformed")
|| message.contains("must be empty")
|| message.contains("must not be empty")
{
AlertDescription::UnexpectedMessage
} else {
AlertDescription::IllegalParameter
}
}
Error::InvalidEncoding(_message) => AlertDescription::IllegalParameter,
Error::UnsupportedFeature(_message) | Error::CryptoFailure(_message) => {
AlertDescription::HandshakeFailure
}
};
(AlertLevel::Fatal, description)
}
/// Parses and records a TLS 1.2 Certificate handshake message with basic structure checks.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_server_certificate(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::ServerHelloReceived {
return Err(Error::StateError(
"tls12 certificate can only be processed after server hello",
));
}
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_CERTIFICATE {
return Err(Error::ParseFailure(
"invalid tls12 certificate message type",
));
}
let certificates = noxtls_parse_tls12_certificate_list(body)?;
let leaf = noxtls_parse_certificate(&certificates[0])
.map_err(|_| Error::ParseFailure("tls12 server certificate leaf must be valid DER"))?;
self.tls13_server_leaf_public_key_der = Some(leaf.subject_public_key.clone());
if self.tls13_require_certificate_auth {
self.noxtls_validate_tls13_server_certificate_chain(&certificates)?;
}
self.noxtls_append_transcript(msg);
self.state = HandshakeState::ServerCertificateReceived;
Ok(())
}
/// Parses and records a TLS 1.2 ServerKeyExchange message when present.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_server_key_exchange(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::ServerCertificateReceived {
return Err(Error::StateError(
"tls12 server key exchange can only be processed after certificate",
));
}
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_SERVER_KEY_EXCHANGE {
return Err(Error::ParseFailure(
"invalid tls12 server key exchange message type",
));
}
let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
"cipher suite must be selected before tls12 server key exchange",
))?;
let kex_kind = noxtls_tls12_key_exchange_kind(suite)?;
noxtls_parse_tls12_server_key_exchange_body(suite, body)?;
if matches!(
kex_kind,
Tls12KeyExchangeKind::DheSigned | Tls12KeyExchangeKind::EcdheSigned
) {
let signature_offset = if kex_kind == Tls12KeyExchangeKind::DheSigned {
let (_, cursor) = noxtls_parse_tls12_u16_opaque_value(body, "tls12 dhe prime")?;
let (_, cursor) =
noxtls_parse_tls12_u16_opaque_value(cursor, "tls12 dhe generator")?;
let (_, cursor) =
noxtls_parse_tls12_u16_opaque_value(cursor, "tls12 dhe server public key")?;
body.len() - cursor.len()
} else {
let public_len = body[3] as usize;
4 + public_len
};
let (signature_scheme, signature) =
noxtls_parse_tls12_signature_fields(body, signature_offset)?;
self.noxtls_verify_tls12_server_key_exchange_signature(
&body[..signature_offset],
signature_scheme,
signature,
)?;
}
if kex_kind == Tls12KeyExchangeKind::DheSigned {
let (prime, _generator, server_public) =
noxtls_tls12_dhe_server_key_exchange_values(body)?;
self.tls12_dhe_prime = Some(prime);
self.tls12_dhe_server_public_key = Some(server_public);
self.tls12_dhe_client_public_key = None;
}
self.noxtls_append_transcript(msg);
Ok(())
}
/// Parses and records a TLS 1.2 CertificateRequest message when server asks for client auth.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_server_certificate_request(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::ServerCertificateReceived {
return Err(Error::StateError(
"tls12 certificate request can only be processed after certificate",
));
}
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_CERTIFICATE_REQUEST {
return Err(Error::ParseFailure(
"invalid tls12 certificate request message type",
));
}
if body.is_empty() {
return Err(Error::ParseFailure(
"tls12 certificate request body must not be empty",
));
}
self.noxtls_append_transcript(msg);
Ok(())
}
/// Parses and records a TLS 1.2 ServerHelloDone message as end-of-server-flight marker.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_server_hello_done(&mut self, msg: &[u8]) -> Result<()> {
if self.state != HandshakeState::ServerCertificateReceived {
return Err(Error::StateError(
"tls12 server hello done can only be processed after certificate flight",
));
}
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_SERVER_HELLO_DONE {
return Err(Error::ParseFailure(
"invalid tls12 server hello done message type",
));
}
if !body.is_empty() {
return Err(Error::ParseFailure(
"tls12 server hello done body must be empty",
));
}
self.noxtls_append_transcript(msg);
Ok(())
}
/// Parses and records a TLS 1.2 ClientKeyExchange message as client-flight entrypoint.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_client_key_exchange(&mut self, msg: &[u8]) -> Result<()> {
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_CLIENT_KEY_EXCHANGE {
return Err(Error::ParseFailure(
"invalid tls12 client key exchange message type",
));
}
let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
"cipher suite must be selected before tls12 client key exchange",
))?;
noxtls_parse_tls12_client_key_exchange_body(suite, body)?;
match noxtls_tls12_key_exchange_kind(suite)? {
Tls12KeyExchangeKind::StaticRsa => {
self.tls12_rsa_encrypted_pre_master_secret = Some(noxtls_tls12_u16_opaque_value(
body,
"tls12 rsa encrypted pre-master secret",
)?);
}
Tls12KeyExchangeKind::DheSigned => {
self.tls12_rsa_encrypted_pre_master_secret = None;
self.tls12_dhe_client_public_key = Some(noxtls_tls12_u16_opaque_value(
body,
"tls12 dhe client public key",
)?);
}
_ => {
self.tls12_rsa_encrypted_pre_master_secret = None;
self.tls12_dhe_client_public_key = None;
}
}
self.noxtls_append_transcript(msg);
Ok(())
}
/// Parses and records an optional TLS 1.2 client CertificateVerify handshake message.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_client_certificate_verify(&mut self, msg: &[u8]) -> Result<()> {
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_CERTIFICATE_VERIFY {
return Err(Error::ParseFailure(
"invalid tls12 client certificate verify message type",
));
}
noxtls_parse_tls12_certificate_verify_body(body)?;
self.noxtls_append_transcript(msg);
Ok(())
}
/// Parses and records TLS 1.2 client Finished handshake message shape.
///
/// # Arguments
///
/// * `self` — `&mut self`.
/// * `msg` — `msg: &[u8]`.
///
/// # Returns
///
/// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
///
/// # 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.
///
fn noxtls_recv_tls12_client_finished(&mut self, msg: &[u8]) -> Result<()> {
let (message_type, body) = noxtls_parse_handshake_message(msg)?;
if message_type != HANDSHAKE_FINISHED {
return Err(Error::ParseFailure("invalid tls12 finished message type"));
}
if body.is_empty() {
return Err(Error::ParseFailure("tls12 finished body must not be empty"));
}
self.tls12_secure_renegotiation_client_verify_data = body.to_vec();
self.tls12_secure_renegotiation_renegotiating = false;
self.noxtls_append_transcript(msg);
Ok(())
}
}