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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
// TLS Handshake Builder - Constructs ClientHello messages
use super::{Extension, Protocol};
use crate::Result;
use crate::constants::{
COMPRESSION_DEFLATE, COMPRESSION_NULL, CONTENT_TYPE_HANDSHAKE, EXTENSION_ALPN,
EXTENSION_EC_POINT_FORMATS, EXTENSION_ENCRYPT_THEN_MAC, EXTENSION_EXTENDED_MASTER_SECRET,
EXTENSION_KEY_SHARE, EXTENSION_RENEGOTIATION_INFO, EXTENSION_SERVER_NAME,
EXTENSION_SESSION_TICKET, EXTENSION_SIGNATURE_ALGORITHMS, EXTENSION_SUPPORTED_GROUPS,
EXTENSION_SUPPORTED_VERSIONS, HANDSHAKE_TYPE_CLIENT_HELLO, HANDSHAKE_TYPE_SERVER_HELLO,
VERSION_SSL_3_0, VERSION_TLS_1_0, VERSION_TLS_1_2, VERSION_TLS_1_3,
};
use bytes::{BufMut, BytesMut};
/// ClientHello message builder
pub struct ClientHelloBuilder {
protocol: Protocol,
cipher_suites: Vec<u16>,
extensions: Vec<Extension>,
session_id: Vec<u8>,
compression_methods: Vec<u8>,
random: [u8; 32],
}
impl ClientHelloBuilder {
/// Create new ClientHello builder
pub fn new(protocol: Protocol) -> Self {
let mut random = [0u8; 32];
// First 4 bytes are Unix time
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
.as_secs() as u32;
random[0..4].copy_from_slice(×tamp.to_be_bytes());
// Rest is random
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut random[4..]);
Self {
protocol,
cipher_suites: Vec::new(),
extensions: Vec::new(),
session_id: Vec::new(),
compression_methods: vec![COMPRESSION_NULL], // No compression
random,
}
}
/// Add cipher suite by hex code
pub fn add_cipher(&mut self, hexcode: u16) -> &mut Self {
self.cipher_suites.push(hexcode);
self
}
/// Add multiple cipher suites
pub fn add_ciphers(&mut self, hexcodes: &[u16]) -> &mut Self {
self.cipher_suites.extend_from_slice(hexcodes);
self
}
/// Add TLS extension
pub fn add_extension(&mut self, extension: Extension) -> &mut Self {
self.extensions.push(extension);
self
}
/// Add Server Name Indication (SNI)
pub fn add_sni(&mut self, hostname: &str) -> &mut Self {
let mut data = BytesMut::new();
// Server name list length
let list_len = 3 + hostname.len();
data.put_u16(list_len as u16);
// Name type (0 = hostname)
data.put_u8(0);
// Hostname length and value
data.put_u16(hostname.len() as u16);
data.put_slice(hostname.as_bytes());
self.extensions
.push(Extension::new(EXTENSION_SERVER_NAME, data.to_vec()));
self
}
/// Add supported groups (elliptic curves)
pub fn add_supported_groups(&mut self, curves: &[u16]) -> &mut Self {
let mut data = BytesMut::new();
// List length
data.put_u16((curves.len() * 2) as u16);
// Curve IDs
for curve in curves {
data.put_u16(*curve);
}
self.extensions
.push(Extension::new(EXTENSION_SUPPORTED_GROUPS, data.to_vec()));
self
}
/// Add signature algorithms
pub fn add_signature_algorithms(&mut self, algorithms: &[(u8, u8)]) -> &mut Self {
let mut data = BytesMut::new();
// List length
data.put_u16((algorithms.len() * 2) as u16);
// Algorithm pairs (hash, signature)
for (hash, sig) in algorithms {
data.put_u8(*hash);
data.put_u8(*sig);
}
self.extensions.push(Extension::new(
EXTENSION_SIGNATURE_ALGORITHMS,
data.to_vec(),
));
self
}
/// Add ALPN (Application-Layer Protocol Negotiation)
pub fn add_alpn(&mut self, protocols: &[&str]) -> &mut Self {
let mut data = BytesMut::new();
// Calculate total length
let total_len: usize = protocols.iter().map(|p| 1 + p.len()).sum();
data.put_u16(total_len as u16);
// Add protocols
for protocol in protocols {
data.put_u8(protocol.len() as u8);
data.put_slice(protocol.as_bytes());
}
self.extensions
.push(Extension::new(EXTENSION_ALPN, data.to_vec()));
self
}
/// Add ec_point_formats extension
pub fn add_ec_point_formats(&mut self) -> &mut Self {
let mut data = BytesMut::new();
// EC point formats length
data.put_u8(1);
// uncompressed (0)
data.put_u8(0);
self.extensions
.push(Extension::new(EXTENSION_EC_POINT_FORMATS, data.to_vec()));
self
}
/// Add session_ticket extension (empty for new ticket)
pub fn add_session_ticket(&mut self) -> &mut Self {
self.extensions
.push(Extension::new(EXTENSION_SESSION_TICKET, vec![]));
self
}
/// Add encrypt_then_mac extension
pub fn add_encrypt_then_mac(&mut self) -> &mut Self {
self.extensions
.push(Extension::new(EXTENSION_ENCRYPT_THEN_MAC, vec![]));
self
}
/// Add extended master secret extension
pub fn add_extended_master_secret(&mut self) -> &mut Self {
self.extensions
.push(Extension::new(EXTENSION_EXTENDED_MASTER_SECRET, vec![]));
self
}
/// Add renegotiation info extension
pub fn add_renegotiation_info(&mut self) -> &mut Self {
let mut data = BytesMut::new();
data.put_u8(0); // Empty renegotiation info
self.extensions
.push(Extension::new(EXTENSION_RENEGOTIATION_INFO, data.to_vec()));
self
}
/// Add status_request extension (OCSP stapling request)
/// RFC 6066 Section 8: Certificate Status Request
pub fn add_status_request(&mut self) -> &mut Self {
let mut data = BytesMut::new();
// CertificateStatusType: ocsp(1)
data.put_u8(1);
// ResponderIDList length (empty)
data.put_u16(0);
// Extensions length (empty)
data.put_u16(0);
self.extensions.push(Extension::new(0x0005, data.to_vec()));
self
}
/// Add supported versions (TLS 1.3)
pub fn add_supported_versions(&mut self, versions: &[u16]) -> &mut Self {
let mut data = BytesMut::new();
// List length
data.put_u8((versions.len() * 2) as u8);
// Versions
for version in versions {
data.put_u16(*version);
}
self.extensions
.push(Extension::new(EXTENSION_SUPPORTED_VERSIONS, data.to_vec()));
self
}
/// Add key_share extension (TLS 1.3)
pub fn add_key_share(&mut self, group: u16) -> &mut Self {
let mut data = BytesMut::new();
// Generate a valid key share
let public_key = if group == 0x001d {
// X25519 - Generate a real cryptographic key pair
use rand::rngs::OsRng;
use x25519_dalek::{EphemeralSecret, PublicKey};
let secret = EphemeralSecret::random_from_rng(OsRng);
let public = PublicKey::from(&secret);
public.as_bytes().to_vec()
} else if group == 0x0017 {
// secp256r1 - For now use random (would need another crate for proper impl)
use rand::RngCore;
let mut key = vec![0u8; 65];
rand::thread_rng().fill_bytes(&mut key);
key
} else {
// Default to random for unsupported groups
use rand::RngCore;
let mut key = vec![0u8; 32];
rand::thread_rng().fill_bytes(&mut key);
key
};
// Client key share length
let share_len = 4 + public_key.len(); // 2 bytes group + 2 bytes length + key
data.put_u16(share_len as u16);
// Named group
data.put_u16(group);
// Key exchange data length
data.put_u16(public_key.len() as u16);
// Key exchange data
data.put_slice(&public_key);
self.extensions
.push(Extension::new(EXTENSION_KEY_SHARE, data.to_vec()));
self
}
/// Add PSK key exchange modes (TLS 1.3)
pub fn add_psk_key_exchange_modes(&mut self) -> &mut Self {
let mut data = BytesMut::new();
// Length of modes
data.put_u8(1);
// PSK with (EC)DHE key establishment (psk_dhe_ke)
data.put_u8(1);
self.extensions.push(Extension::new(0x002d, data.to_vec()));
self
}
/// Add NPN (Next Protocol Negotiation) extension for SPDY testing
/// Used primarily for CRIME vulnerability testing
pub fn add_npn(&mut self) -> &mut Self {
// NPN Extension (0x3374) - empty extension to request NPN
self.extensions.push(Extension::new(0x3374, vec![]));
self
}
/// Set compression methods (for CRIME vulnerability testing)
/// By default, compression is disabled (only null compression)
pub fn with_compression(&mut self, enable_deflate: bool) -> &mut Self {
if enable_deflate {
self.compression_methods = vec![COMPRESSION_DEFLATE, COMPRESSION_NULL]; // DEFLATE + null
} else {
self.compression_methods = vec![COMPRESSION_NULL]; // null only
}
self
}
/// Configure for vulnerability testing with minimal ciphers
/// Sets up a basic ClientHello suitable for most vulnerability tests
pub fn for_vulnerability_testing(&mut self) -> &mut Self {
// Use common RSA and ECDHE ciphers for broad compatibility
self.add_ciphers(&[
0xc02f, // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
0xc030, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA256
0x009e, // TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
0x009c, // TLS_RSA_WITH_AES_128_GCM_SHA256
0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
0x0035, // TLS_RSA_WITH_AES_256_CBC_SHA
]);
self
}
/// Configure for RSA key exchange only (for ROBOT testing)
pub fn for_rsa_key_exchange(&mut self) -> &mut Self {
self.add_ciphers(&[
0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
0x0035, // TLS_RSA_WITH_AES_256_CBC_SHA
0x009c, // TLS_RSA_WITH_AES_128_GCM_SHA256
]);
self
}
/// Configure for CBC cipher testing (for POODLE, Lucky13, etc.)
pub fn for_cbc_ciphers(&mut self) -> &mut Self {
self.add_ciphers(&[
0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
0x0035, // TLS_RSA_WITH_AES_256_CBC_SHA
0x003c, // TLS_RSA_WITH_AES_128_CBC_SHA256
0x003d, // TLS_RSA_WITH_AES_256_CBC_SHA256
]);
self
}
/// Build a minimal ClientHello without extensions (for simple vulnerability tests)
pub fn build_minimal(&self) -> Result<Vec<u8>> {
let mut buf = BytesMut::new();
// Record Layer
buf.put_u8(CONTENT_TYPE_HANDSHAKE); // Content Type: Handshake (0x16)
// Record version
let record_version = match self.protocol {
Protocol::SSLv3 => VERSION_SSL_3_0,
_ => VERSION_TLS_1_0,
};
buf.put_u16(record_version);
// Length placeholder
let length_pos = buf.len();
buf.put_u16(0);
// Handshake Protocol
let handshake_start = buf.len();
buf.put_u8(HANDSHAKE_TYPE_CLIENT_HELLO); // Handshake Type: ClientHello (0x01)
// Handshake length placeholder
let handshake_length_pos = buf.len();
buf.put_u8(0);
buf.put_u16(0);
// ClientHello content
let hello_start = buf.len();
// Protocol version
let client_version = if matches!(self.protocol, Protocol::TLS13) {
VERSION_TLS_1_2 // TLS 1.3 uses 0x0303 for compatibility (RFC 8446)
} else {
self.protocol.as_hex()
};
buf.put_u16(client_version);
// Random (32 bytes)
buf.put_slice(&self.random);
// Session ID
buf.put_u8(self.session_id.len() as u8);
if !self.session_id.is_empty() {
buf.put_slice(&self.session_id);
}
// Cipher suites
buf.put_u16((self.cipher_suites.len() * 2) as u16);
for cipher in &self.cipher_suites {
buf.put_u16(*cipher);
}
// Compression methods
buf.put_u8(self.compression_methods.len() as u8);
buf.put_slice(&self.compression_methods);
// No extensions in minimal build
// Fill in handshake length
let handshake_len = buf.len() - hello_start;
buf[handshake_length_pos] = ((handshake_len >> 16) & 0xff) as u8;
buf[handshake_length_pos + 1..handshake_length_pos + 3]
.copy_from_slice(&((handshake_len & 0xffff) as u16).to_be_bytes());
// Fill in record length
let record_len = buf.len() - handshake_start;
buf[length_pos..length_pos + 2].copy_from_slice(&(record_len as u16).to_be_bytes());
Ok(buf.to_vec())
}
/// Add signature algorithms cert (TLS 1.3)
pub fn add_signature_algorithms_cert(&mut self, algorithms: &[(u8, u8)]) -> &mut Self {
let mut data = BytesMut::new();
// List length
data.put_u16((algorithms.len() * 2) as u16);
// Algorithm pairs (hash, signature)
for (hash, sig) in algorithms {
data.put_u8(*hash);
data.put_u8(*sig);
}
self.extensions.push(Extension::new(0x0050, data.to_vec()));
self
}
/// Build the complete ClientHello message
pub fn build(&self) -> Result<Vec<u8>> {
let mut buf = BytesMut::new();
// Record Layer
// Content Type: Handshake (0x16)
buf.put_u8(CONTENT_TYPE_HANDSHAKE);
// Legacy version (TLS 1.0 for compatibility)
let record_version = match self.protocol {
Protocol::SSLv3 => VERSION_SSL_3_0,
_ => VERSION_TLS_1_0,
};
buf.put_u16(record_version);
// Length placeholder (will be filled later)
let length_pos = buf.len();
buf.put_u16(0);
// Handshake Protocol
let handshake_start = buf.len();
// Handshake Type: ClientHello (0x01)
buf.put_u8(HANDSHAKE_TYPE_CLIENT_HELLO);
// Length placeholder
let handshake_length_pos = buf.len();
buf.put_u8(0);
buf.put_u16(0);
// ClientHello content
let hello_start = buf.len();
// Protocol version
// For TLS 1.3, use TLS 1.2 (0x0303) for compatibility (RFC 8446)
// The actual version is negotiated via supported_versions extension
let client_version = if matches!(self.protocol, Protocol::TLS13) {
VERSION_TLS_1_2
} else {
self.protocol.as_hex()
};
buf.put_u16(client_version);
// Random (32 bytes)
buf.put_slice(&self.random);
// Session ID
buf.put_u8(self.session_id.len() as u8);
if !self.session_id.is_empty() {
buf.put_slice(&self.session_id);
}
// Cipher suites
buf.put_u16((self.cipher_suites.len() * 2) as u16);
for cipher in &self.cipher_suites {
buf.put_u16(*cipher);
}
// Compression methods
buf.put_u8(self.compression_methods.len() as u8);
buf.put_slice(&self.compression_methods);
// Extensions
if !self.extensions.is_empty() {
let extensions_start = buf.len();
buf.put_u16(0); // Placeholder for total extensions length
for ext in &self.extensions {
buf.put_u16(ext.extension_type);
buf.put_u16(ext.data.len() as u16);
buf.put_slice(&ext.data);
}
// Fill in extensions length
let extensions_len = buf.len() - extensions_start - 2;
buf[extensions_start..extensions_start + 2]
.copy_from_slice(&(extensions_len as u16).to_be_bytes());
}
// Fill in handshake length
let handshake_len = buf.len() - hello_start;
buf[handshake_length_pos] = ((handshake_len >> 16) & 0xff) as u8;
buf[handshake_length_pos + 1..handshake_length_pos + 3]
.copy_from_slice(&((handshake_len & 0xffff) as u16).to_be_bytes());
// Fill in record length
let record_len = buf.len() - handshake_start;
buf[length_pos..length_pos + 2].copy_from_slice(&(record_len as u16).to_be_bytes());
Ok(buf.to_vec())
}
/// Build with default extensions
pub fn build_with_defaults(&mut self, hostname: Option<&str>) -> Result<Vec<u8>> {
// For TLS 1.3, add extensions in OpenSSL order for maximum compatibility
if matches!(self.protocol, Protocol::TLS13) {
// Extension order matches OpenSSL for strict servers
// 1. SNI (0x0000)
if let Some(host) = hostname {
self.add_sni(host);
}
// 2. ec_point_formats (0x000b)
self.add_ec_point_formats();
// 3. supported_groups (0x000a) - Match OpenSSL with ffdhe groups
self.add_supported_groups(&[
0x001d, // x25519
0x0017, // secp256r1
0x001e, // x448
0x0019, // secp521r1
0x0018, // secp384r1
0x0100, // ffdhe2048
0x0101, // ffdhe3072
0x0102, // ffdhe4096
0x0103, // ffdhe6144
0x0104, // ffdhe8192
]);
// 4. session_ticket (0x0023)
self.add_session_ticket();
// 5. encrypt_then_mac (0x0016)
self.add_encrypt_then_mac();
// 6. extended_master_secret (0x0017)
self.add_extended_master_secret();
// 7. status_request (0x0005) - OCSP stapling
self.add_status_request();
// 8. signature_algorithms (0x000d) - Extended list matching OpenSSL
self.add_signature_algorithms(&[
(0x04, 0x03), // ecdsa_secp256r1_sha256
(0x05, 0x03), // ecdsa_secp384r1_sha384
(0x06, 0x03), // ecdsa_secp521r1_sha512
(0x08, 0x07), // ed25519
(0x08, 0x08), // rsa_pss_rsae_sha256
(0x08, 0x09), // rsa_pss_rsae_sha384
(0x08, 0x0a), // rsa_pss_rsae_sha512
(0x08, 0x0b), // rsa_pss_pss_sha256
(0x08, 0x04), // rsa_pss_pss_sha256
(0x08, 0x05), // rsa_pss_pss_sha384
(0x08, 0x06), // rsa_pss_pss_sha512
(0x04, 0x01), // rsa_pkcs1_sha256
(0x05, 0x01), // rsa_pkcs1_sha384
(0x06, 0x01), // rsa_pkcs1_sha512
]);
// 9. supported_versions - ONLY TLS 1.3 for TLS 1.3 tests
self.add_supported_versions(&[VERSION_TLS_1_3]);
// 10. psk_key_exchange_modes (0x002d)
self.add_psk_key_exchange_modes();
// 11. key_share (0x0033)
self.add_key_share(0x001d); // X25519
} else {
// TLS 1.2 and earlier - traditional order
// SNI
if let Some(host) = hostname {
self.add_sni(host);
}
// Supported groups
self.add_supported_groups(&[
0x001d, // X25519
0x0017, // secp256r1
0x0018, // secp384r1
0x0019, // secp521r1
]);
// Signature algorithms
self.add_signature_algorithms(&[
(0x04, 0x03), // SHA256-ECDSA
(0x05, 0x03), // SHA384-ECDSA
(0x06, 0x03), // SHA512-ECDSA
(0x04, 0x01), // SHA256-RSA
(0x05, 0x01), // SHA384-RSA
(0x06, 0x01), // SHA512-RSA
]);
// Session tickets (RFC 5077) - supported in TLS 1.0+
self.add_session_ticket();
// TLS 1.2 specific extensions
self.add_extended_master_secret();
self.add_renegotiation_info();
self.add_status_request();
}
self.build()
}
}
/// Parse ServerHello message
pub struct ServerHelloParser;
impl ServerHelloParser {
/// Parse ServerHello from bytes
pub fn parse(data: &[u8]) -> Result<ServerHello> {
if data.len() < 6 {
crate::tls_bail!("ServerHello too short");
}
let mut offset = 0;
// Skip record header (5 bytes)
if data[0] != CONTENT_TYPE_HANDSHAKE {
crate::tls_bail!("Not a handshake record");
}
offset += 5;
// Handshake type
if data[offset] != HANDSHAKE_TYPE_SERVER_HELLO {
crate::tls_bail!("Not a ServerHello");
}
offset += 1;
// Handshake length (3 bytes)
offset += 3;
// Protocol version
let version = u16::from_be_bytes([data[offset], data[offset + 1]]);
offset += 2;
// Random (32 bytes)
let mut random = [0u8; 32];
random.copy_from_slice(&data[offset..offset + 32]);
offset += 32;
// Session ID
let session_id_len = data[offset] as usize;
offset += 1;
let session_id = data[offset..offset + session_id_len].to_vec();
offset += session_id_len;
// Cipher suite
let cipher_suite = u16::from_be_bytes([data[offset], data[offset + 1]]);
offset += 2;
// Compression method
let compression = data[offset];
offset += 1;
// Extensions (if present)
let mut extensions = Vec::new();
let mut ocsp_stapling_detected = None;
let mut heartbeat_enabled = None;
let mut secure_renegotiation = None;
if offset < data.len() {
let ext_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
let ext_end = offset + ext_len;
while offset < ext_end && offset + 4 <= data.len() {
let ext_type = u16::from_be_bytes([data[offset], data[offset + 1]]);
offset += 2;
let ext_data_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
if offset + ext_data_len <= data.len() {
let ext_data = data[offset..offset + ext_data_len].to_vec();
// RFC 6066 Section 8: status_request extension (OCSP stapling)
// Extension type 5 in ServerHello indicates server acceptance
if ext_type == 0x0005 {
ocsp_stapling_detected = Some(true);
}
// RFC 6520: Heartbeat extension detection
// Extension type 0x000f (15 decimal) in ServerHello indicates server support
if ext_type == 0x000f {
heartbeat_enabled = Some(true);
}
// RFC 5746: Secure Renegotiation extension detection
// Extension type 0xff01 (65281 decimal) in ServerHello indicates server support
if ext_type == 0xff01 {
secure_renegotiation = Some(true);
}
extensions.push(Extension::new(ext_type, ext_data));
offset += ext_data_len;
}
}
}
// If extensions were present but status_request was not found, explicitly mark as false
if !extensions.is_empty() && ocsp_stapling_detected.is_none() {
ocsp_stapling_detected = Some(false);
}
// If extensions were present but heartbeat was not found, explicitly mark as false
if !extensions.is_empty() && heartbeat_enabled.is_none() {
heartbeat_enabled = Some(false);
}
// If extensions were present but renegotiation_info was not found, explicitly mark as false
if !extensions.is_empty() && secure_renegotiation.is_none() {
secure_renegotiation = Some(false);
}
Ok(ServerHello {
version: Protocol::from(version),
random,
session_id,
cipher_suite,
compression,
extensions,
ocsp_stapling_detected,
heartbeat_enabled,
secure_renegotiation,
})
}
}
/// ServerHello message
#[derive(Debug, Clone)]
pub struct ServerHello {
pub version: Protocol,
pub random: [u8; 32],
pub session_id: Vec<u8>,
pub cipher_suite: u16,
pub compression: u8,
pub extensions: Vec<Extension>,
/// Direct detection of OCSP stapling via status_request extension (type 5, RFC 6066)
/// This indicates the server accepted the client's OCSP stapling request
pub ocsp_stapling_detected: Option<bool>,
/// Direct detection of Heartbeat extension (type 0x000f, RFC 6520)
/// This indicates the server supports TLS Heartbeat extension (keepalive mechanism)
/// Note: This is separate from Heartbleed (CVE-2014-0160) vulnerability detection
pub heartbeat_enabled: Option<bool>,
/// Direct detection of Secure Renegotiation extension (type 0xff01, RFC 5746)
/// This indicates the server supports secure renegotiation to prevent MITM attacks
pub secure_renegotiation: Option<bool>,
}
impl ServerHello {
/// Get cipher suite as hex string
pub fn cipher_hex(&self) -> String {
format!("{:04x}", self.cipher_suite)
}
/// Check if extension is present
pub fn has_extension(&self, ext_type: u16) -> bool {
self.extensions.iter().any(|e| e.extension_type == ext_type)
}
/// Get extension by type
pub fn get_extension(&self, ext_type: u16) -> Option<&Extension> {
self.extensions
.iter()
.find(|e| e.extension_type == ext_type)
}
/// Check if OCSP stapling is supported (status_request extension present)
/// RFC 6066 Section 8: Certificate Status Request
/// Returns Some(true) if status_request extension (type 5) was found in ServerHello,
/// Some(false) if extensions were present but status_request was not,
/// None if no extensions were parsed (legacy TLS or parsing error)
pub fn supports_ocsp_stapling(&self) -> Option<bool> {
self.ocsp_stapling_detected
}
/// Check if Heartbeat extension is enabled
/// RFC 6520: Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) Heartbeat Extension
/// Returns Some(true) if heartbeat extension (type 0x000f) was found in ServerHello,
/// Some(false) if extensions were present but heartbeat was not,
/// None if no extensions were parsed (legacy TLS or parsing error)
pub fn supports_heartbeat(&self) -> Option<bool> {
self.heartbeat_enabled
}
/// Check if Secure Renegotiation extension is enabled
/// RFC 5746: Transport Layer Security (TLS) Renegotiation Indication Extension
/// Returns Some(true) if renegotiation_info extension (type 0xff01) was found in ServerHello,
/// Some(false) if extensions were present but renegotiation_info was not,
/// None if no extensions were parsed (legacy TLS or parsing error)
pub fn supports_secure_renegotiation(&self) -> Option<bool> {
self.secure_renegotiation
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client_hello_basic() {
let mut builder = ClientHelloBuilder::new(Protocol::TLS12);
builder.add_ciphers(&[0xc030, 0xc02f, 0x009e]);
let hello = builder.build().expect("test assertion should succeed");
assert!(hello.len() > 40);
assert_eq!(hello[0], CONTENT_TYPE_HANDSHAKE); // Handshake (0x16)
assert_eq!(hello[5], HANDSHAKE_TYPE_CLIENT_HELLO); // ClientHello (0x01)
}
#[test]
fn test_client_hello_with_sni() {
let mut builder = ClientHelloBuilder::new(Protocol::TLS12);
builder.add_ciphers(&[0xc030]);
builder.add_sni("example.com");
let hello = builder.build().expect("test assertion should succeed");
assert!(hello.len() > 60);
}
#[test]
fn test_client_hello_defaults() {
let mut builder = ClientHelloBuilder::new(Protocol::TLS12);
builder.add_ciphers(&[0xc030, 0xc02f]);
let hello = builder
.build_with_defaults(Some("example.com"))
.expect("test assertion should succeed");
assert!(hello.len() > 100); // Should have several extensions
}
#[test]
fn test_client_hello_with_status_request() {
let mut builder = ClientHelloBuilder::new(Protocol::TLS12);
builder.add_ciphers(&[0xc030]);
builder.add_status_request();
let hello = builder.build().expect("test assertion should succeed");
assert!(hello.len() > 40);
// Verify status_request extension is present (type 0x0005)
// Extension should have 5 bytes: type(1) + responder_id_list(2) + request_extensions(2)
let hello_bytes = &hello;
let status_request_present = hello_bytes.windows(2).any(|w| w == [0x00, 0x05]);
assert!(
status_request_present,
"status_request extension should be present"
);
}
#[test]
fn test_server_hello_ocsp_stapling_detected() {
// Build a minimal ServerHello with status_request extension
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x03, // TLS 1.2
0x00, 0x4A, // Length
0x02, // ServerHello type
0x00, 0x00, 0x46, // Handshake length
0x03, 0x03, // TLS 1.2
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite (TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
server_hello.extend_from_slice(&[0xc0, 0x2f]);
// Compression method (null)
server_hello.push(0x00);
// Extensions length
server_hello.extend_from_slice(&[0x00, 0x05]);
// status_request extension (type 0x0005)
server_hello.extend_from_slice(&[0x00, 0x05]);
// Extension data length (1 byte)
server_hello.extend_from_slice(&[0x00, 0x01]);
// Extension data (empty OCSP response placeholder)
server_hello.push(0x00);
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
assert_eq!(parsed.ocsp_stapling_detected, Some(true));
assert!(parsed.supports_ocsp_stapling().unwrap());
assert!(parsed.has_extension(0x0005));
}
#[test]
fn test_server_hello_no_ocsp_stapling() {
// Build a minimal ServerHello WITHOUT status_request extension
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x03, // TLS 1.2
0x00, 0x4A, // Length
0x02, // ServerHello type
0x00, 0x00, 0x46, // Handshake length
0x03, 0x03, // TLS 1.2
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite
server_hello.extend_from_slice(&[0xc0, 0x2f]);
// Compression method (null)
server_hello.push(0x00);
// Extensions length
server_hello.extend_from_slice(&[0x00, 0x08]);
// SNI extension (type 0x0000) - different extension
server_hello.extend_from_slice(&[0x00, 0x00]);
server_hello.extend_from_slice(&[0x00, 0x04]);
server_hello.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
assert_eq!(parsed.ocsp_stapling_detected, Some(false));
assert!(!parsed.supports_ocsp_stapling().unwrap());
assert!(!parsed.has_extension(0x0005));
}
#[test]
fn test_server_hello_no_extensions() {
// Build a minimal ServerHello with NO extensions (legacy TLS)
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x01, // TLS 1.0
0x00, 0x2A, // Length
0x02, // ServerHello type
0x00, 0x00, 0x26, // Handshake length
0x03, 0x01, // TLS 1.0
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite
server_hello.extend_from_slice(&[0x00, 0x35]);
// Compression method (null)
server_hello.push(0x00);
// No extensions section
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
assert_eq!(parsed.ocsp_stapling_detected, None);
assert_eq!(parsed.supports_ocsp_stapling(), None);
}
#[test]
fn test_server_hello_heartbeat_detected() {
// Build a minimal ServerHello with heartbeat extension
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x03, // TLS 1.2
0x00, 0x4A, // Length
0x02, // ServerHello type
0x00, 0x00, 0x46, // Handshake length
0x03, 0x03, // TLS 1.2
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite (TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
server_hello.extend_from_slice(&[0xc0, 0x2f]);
// Compression method (null)
server_hello.push(0x00);
// Extensions length
server_hello.extend_from_slice(&[0x00, 0x05]);
// heartbeat extension (type 0x000f)
server_hello.extend_from_slice(&[0x00, 0x0f]);
// Extension data length (1 byte)
server_hello.extend_from_slice(&[0x00, 0x01]);
// Extension data (peer_allowed_to_send = 1)
server_hello.push(0x01);
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
assert_eq!(parsed.heartbeat_enabled, Some(true));
assert!(parsed.supports_heartbeat().unwrap());
assert!(parsed.has_extension(0x000f));
}
#[test]
fn test_server_hello_no_heartbeat() {
// Build a minimal ServerHello WITHOUT heartbeat extension
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x03, // TLS 1.2
0x00, 0x4A, // Length
0x02, // ServerHello type
0x00, 0x00, 0x46, // Handshake length
0x03, 0x03, // TLS 1.2
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite
server_hello.extend_from_slice(&[0xc0, 0x2f]);
// Compression method (null)
server_hello.push(0x00);
// Extensions length
server_hello.extend_from_slice(&[0x00, 0x08]);
// SNI extension (type 0x0000) - different extension
server_hello.extend_from_slice(&[0x00, 0x00]);
server_hello.extend_from_slice(&[0x00, 0x04]);
server_hello.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
assert_eq!(parsed.heartbeat_enabled, Some(false));
assert!(!parsed.supports_heartbeat().unwrap());
assert!(!parsed.has_extension(0x000f));
}
#[test]
fn test_server_hello_heartbeat_and_ocsp() {
// Build a ServerHello with BOTH heartbeat and OCSP stapling extensions
let mut server_hello = vec![
0x16, // Handshake record type
0x03, 0x03, // TLS 1.2
0x00, 0x50, // Length
0x02, // ServerHello type
0x00, 0x00, 0x4C, // Handshake length
0x03, 0x03, // TLS 1.2
];
// Random (32 bytes)
server_hello.extend_from_slice(&[0u8; 32]);
// Session ID length (0)
server_hello.push(0x00);
// Cipher suite
server_hello.extend_from_slice(&[0xc0, 0x2f]);
// Compression method (null)
server_hello.push(0x00);
// Extensions length (two extensions)
server_hello.extend_from_slice(&[0x00, 0x0A]);
// status_request extension (type 0x0005)
server_hello.extend_from_slice(&[0x00, 0x05]);
server_hello.extend_from_slice(&[0x00, 0x01]);
server_hello.push(0x00);
// heartbeat extension (type 0x000f)
server_hello.extend_from_slice(&[0x00, 0x0f]);
server_hello.extend_from_slice(&[0x00, 0x01]);
server_hello.push(0x01);
let parsed =
ServerHelloParser::parse(&server_hello).expect("test assertion should succeed");
// Both should be detected
assert_eq!(parsed.ocsp_stapling_detected, Some(true));
assert_eq!(parsed.heartbeat_enabled, Some(true));
assert!(parsed.supports_ocsp_stapling().unwrap());
assert!(parsed.supports_heartbeat().unwrap());
assert!(parsed.has_extension(0x0005));
assert!(parsed.has_extension(0x000f));
}
}