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
// Protocol Tester - Tests which TLS/SSL protocols are supported
use super::{Protocol, ProtocolTestResult};
use crate::Result;
use crate::constants::{BUFFER_SIZE_MAX_TLS_RECORD, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT};
use crate::utils::mtls::MtlsConfig;
use crate::utils::network::Target;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::time::timeout;
/// Trait for protocol testing abstraction (enables mocking in tests)
#[async_trait::async_trait]
pub trait ProtocolTestable: Send + Sync {
async fn test_all_protocols(&self) -> Result<Vec<ProtocolTestResult>>;
async fn test_protocol(&self, protocol: Protocol) -> Result<ProtocolTestResult>;
}
/// Protocol testing configuration
pub struct ProtocolTester {
target: Target,
connect_timeout: Duration,
read_timeout: Duration,
mtls_config: Option<MtlsConfig>,
use_rdp: bool,
enable_bugs_mode: bool,
starttls_protocol: Option<crate::starttls::StarttlsProtocol>,
sni_hostname: Option<String>,
protocol_filter: Option<Vec<Protocol>>,
test_all_ips: bool,
retry_config: Option<crate::utils::retry::RetryConfig>,
}
impl ProtocolTester {
/// Create new protocol tester
pub fn new(target: Target) -> Self {
// Auto-detect RDP based on port
let use_rdp = crate::protocols::rdp::RdpPreamble::should_use_rdp(target.port);
Self {
target,
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
read_timeout: DEFAULT_READ_TIMEOUT,
mtls_config: None,
use_rdp,
enable_bugs_mode: false,
starttls_protocol: None,
sni_hostname: None,
protocol_filter: None,
test_all_ips: false,
retry_config: None,
}
}
/// Create new protocol tester with mTLS configuration
pub fn with_mtls(target: Target, mtls_config: MtlsConfig) -> Self {
// Auto-detect RDP based on port
let use_rdp = crate::protocols::rdp::RdpPreamble::should_use_rdp(target.port);
Self {
target,
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
read_timeout: DEFAULT_READ_TIMEOUT,
mtls_config: Some(mtls_config),
use_rdp,
enable_bugs_mode: false,
starttls_protocol: None,
sni_hostname: None,
protocol_filter: None,
test_all_ips: false,
retry_config: None,
}
}
/// Enable OpenSSL bug workarounds mode
pub fn with_bugs_mode(mut self, enable: bool) -> Self {
self.enable_bugs_mode = enable;
self
}
/// Set STARTTLS protocol
pub fn with_starttls(mut self, protocol: Option<crate::starttls::StarttlsProtocol>) -> Self {
self.starttls_protocol = protocol;
self
}
/// Set custom SNI hostname
pub fn with_sni(mut self, sni: Option<String>) -> Self {
self.sni_hostname = sni;
self
}
/// Set protocol filter
pub fn with_protocol_filter(mut self, protocols: Option<Vec<Protocol>>) -> Self {
self.protocol_filter = protocols;
self
}
/// Set connect timeout
pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
/// Set read timeout
pub fn with_read_timeout(mut self, timeout: Duration) -> Self {
self.read_timeout = timeout;
self
}
/// Enable or disable RDP mode
pub fn with_rdp(mut self, enable: bool) -> Self {
self.use_rdp = enable;
self
}
/// Enable testing all resolved IP addresses (for Anycast pools)
pub fn with_test_all_ips(mut self, enable: bool) -> Self {
self.test_all_ips = enable;
self
}
/// Set retry configuration for handling transient network failures
pub fn with_retry_config(mut self, config: Option<crate::utils::retry::RetryConfig>) -> Self {
self.retry_config = config;
self
}
/// Test all protocols (parallelized for concurrent execution)
pub async fn test_all_protocols(&self) -> Result<Vec<ProtocolTestResult>> {
use futures::stream::{self, StreamExt};
// Determine which protocols to test
let protocols_to_test = self.protocol_filter.clone().unwrap_or_else(Protocol::all);
// Test all protocols concurrently using buffer_unordered
// This parallelizes the testing of all 6 protocols simultaneously
let results: Vec<ProtocolTestResult> = stream::iter(protocols_to_test)
.map(|protocol| async move { self.test_protocol(protocol).await })
.buffer_unordered(6) // Test up to 6 protocols concurrently
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<Vec<_>>>()?;
Ok(results)
}
/// Test specific protocol
pub async fn test_protocol(&self, protocol: Protocol) -> Result<ProtocolTestResult> {
let start = std::time::Instant::now();
let supported = if self.test_all_ips {
// Test all IPs and report minimum capability (like SSL Labs)
// Protocol is supported ONLY if ALL IPs support it
self.test_protocol_all_ips(protocol).await?
} else {
// Test only first IP (default behavior)
let addr = self.target.socket_addrs()[0];
self.test_protocol_on_ip(protocol, addr).await?
};
let handshake_time_ms = if supported {
Some(start.elapsed().as_millis() as u64)
} else {
None
};
// Detect heartbeat extension support for supported protocols (TLS 1.0-1.3)
let heartbeat_enabled =
if supported && !matches!(protocol, Protocol::SSLv2 | Protocol::QUIC) {
self.detect_heartbeat_extension(protocol).await.ok()
} else {
None
};
// Detect session resumption support for supported protocols (TLS 1.0-1.3)
let (session_resumption_caching, session_resumption_tickets) =
if supported && !matches!(protocol, Protocol::SSLv2 | Protocol::QUIC) {
match self.detect_session_resumption(protocol).await {
Ok((caching, tickets)) => (Some(caching), Some(tickets)),
Err(_) => (None, None),
}
} else {
(None, None)
};
// Detect secure renegotiation support for supported protocols (TLS 1.0-1.3)
let secure_renegotiation =
if supported && !matches!(protocol, Protocol::SSLv2 | Protocol::QUIC) {
self.detect_secure_renegotiation(protocol).await.ok()
} else {
None
};
Ok(ProtocolTestResult {
protocol,
supported,
preferred: false, // Will be determined later
ciphers_count: 0, // Will be filled by cipher testing
handshake_time_ms,
heartbeat_enabled,
session_resumption_caching,
session_resumption_tickets,
secure_renegotiation,
})
}
/// Test protocol across all resolved IPs
async fn test_protocol_all_ips(&self, protocol: Protocol) -> Result<bool> {
let addrs = self.target.socket_addrs();
if addrs.is_empty() {
return Ok(false);
}
tracing::info!(
"Testing {} IPs for hostname {} (protocol: {})",
addrs.len(),
self.target.hostname,
protocol
);
let mut all_support = true;
let mut any_tested = false;
let mut per_ip_results = Vec::new();
for (idx, addr) in addrs.iter().enumerate() {
any_tested = true;
let ip_supports = self.test_protocol_on_ip(protocol, *addr).await?;
tracing::debug!(
"IP {} ({}/{}): {} {} - {}",
addr.ip(),
idx + 1,
addrs.len(),
protocol,
if ip_supports {
"supported"
} else {
"NOT supported"
},
if ip_supports { "✓" } else { "✗" }
);
per_ip_results.push((addr.ip(), ip_supports));
if !ip_supports {
all_support = false;
}
}
// Check for inconsistencies
let inconsistent =
per_ip_results.iter().any(|(_, s)| *s) && per_ip_results.iter().any(|(_, s)| !*s);
if inconsistent {
tracing::warn!(
"WARNING: Inconsistent {} support across IPs for {}",
protocol,
self.target.hostname
);
for (ip, supported) in &per_ip_results {
tracing::warn!(
" {} {} - {}",
ip,
protocol,
if *supported {
"SUPPORTED"
} else {
"NOT SUPPORTED"
}
);
}
}
// Report minimum capability (like SSL Labs): supported only if ALL IPs support it
Ok(any_tested && all_support)
}
/// Test protocol on specific IP address
async fn test_protocol_on_ip(
&self,
protocol: Protocol,
addr: std::net::SocketAddr,
) -> Result<bool> {
match protocol {
Protocol::SSLv2 => self.test_sslv2_on_ip(addr).await,
Protocol::SSLv3 | Protocol::TLS10 | Protocol::TLS11 | Protocol::TLS12 => {
self.test_tls_with_openssl_on_ip(protocol, addr).await
}
Protocol::TLS13 => self.test_tls13_on_ip(addr).await,
Protocol::QUIC => self.test_quic_on_ip(addr).await,
}
}
/// Test SSLv2 (custom implementation needed as it's not in modern libraries)
async fn test_sslv2_on_ip(&self, addr: std::net::SocketAddr) -> Result<bool> {
// SSLv2 uses a different handshake format
// For now, we'll use a simple probe
let stream_result = crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
)
.await;
match stream_result {
Ok(mut stream) => {
// Send RDP preamble if needed
if self.use_rdp
&& crate::protocols::rdp::RdpPreamble::send(&mut stream)
.await
.is_err()
{
return Ok(false);
}
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok(false);
}
}
// Send SSLv2 ClientHello
let client_hello = self.build_sslv2_client_hello();
let mut response = vec![0u8; 1024];
match timeout(self.read_timeout, async {
stream.write_all(&client_hello).await?;
stream.read(&mut response).await
})
.await
{
Ok(Ok(n)) if n > 0 => {
// Check if response looks like SSLv2 ServerHello
Ok(response[0] & 0x80 == 0x80)
}
_ => Ok(false),
}
}
_ => Ok(false),
}
}
/// Build SSLv2 ClientHello
fn build_sslv2_client_hello(&self) -> Vec<u8> {
let mut hello = vec![
0x80, // Record header - high bit set
0x00, // Length placeholder
0x01, // Message type (CLIENT-HELLO)
0x00, 0x02, // Version (SSLv2)
];
// Cipher specs length
hello.push(0x00);
hello.push(0x06); // 3 ciphers * 3 bytes
// Session ID length
hello.push(0x00);
hello.push(0x00);
// Challenge length
hello.push(0x00);
hello.push(0x10); // 16 bytes
// Cipher specs (3-byte each)
hello.extend_from_slice(&[0x01, 0x00, 0x80]); // SSL_CK_RC4_128_WITH_MD5
hello.extend_from_slice(&[0x02, 0x00, 0x80]); // SSL_CK_RC4_128_EXPORT40_WITH_MD5
hello.extend_from_slice(&[0x03, 0x00, 0x80]); // SSL_CK_RC2_128_CBC_WITH_MD5
// Challenge (16 random bytes)
hello.extend_from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]);
hello.extend_from_slice(&[0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10]);
// Fix length
let len = hello.len() - 2;
hello[1] = len as u8;
hello
}
/// Test TLS protocols using OpenSSL
async fn test_tls_with_openssl_on_ip(
&self,
protocol: Protocol,
addr: std::net::SocketAddr,
) -> Result<bool> {
use openssl::ssl::{SslConnector, SslMethod, SslVersion};
// Connect TCP with retry logic
let mut stream = match crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
)
.await
{
Ok(s) => s,
Err(_) => return Ok(false),
};
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok(false);
}
}
// Convert to std::net::TcpStream for OpenSSL
let std_stream = stream.into_std()?;
std_stream.set_nonblocking(false)?;
// Build SSL connector
let mut builder = SslConnector::builder(SslMethod::tls())?;
// Disable certificate verification for protocol testing
use openssl::ssl::SslVerifyMode;
builder.set_verify(SslVerifyMode::NONE);
// Set specific protocol version
let (min_version, max_version) = match protocol {
Protocol::SSLv3 => (SslVersion::SSL3, SslVersion::SSL3),
Protocol::TLS10 => (SslVersion::TLS1, SslVersion::TLS1),
Protocol::TLS11 => (SslVersion::TLS1_1, SslVersion::TLS1_1),
Protocol::TLS12 => (SslVersion::TLS1_2, SslVersion::TLS1_2),
_ => return Ok(false),
};
builder.set_min_proto_version(Some(min_version))?;
builder.set_max_proto_version(Some(max_version))?;
// Enable bug workarounds if --bugs flag is set
if self.enable_bugs_mode {
use openssl::ssl::SslOptions;
builder.set_options(SslOptions::ALL);
}
let connector = builder.build();
// Get effective SNI hostname
let sni_host = self.sni_hostname.as_ref().unwrap_or(&self.target.hostname);
// Try to connect
match connector.connect(sni_host, std_stream) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
/// Test TLS 1.3 using rustls
async fn test_tls13_on_ip(&self, addr: std::net::SocketAddr) -> Result<bool> {
use rustls::{ClientConfig, RootCertStore};
use std::sync::Arc;
use tokio_rustls::TlsConnector;
// Connect TCP with retry logic
let mut stream = match crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
)
.await
{
Ok(s) => s,
Err(_) => return Ok(false),
};
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok(false);
}
}
// Build TLS connector with or without client auth
let connector = if let Some(ref mtls_config) = self.mtls_config {
// Use mTLS configuration
match mtls_config.build_tls_connector() {
Ok(c) => c,
Err(_) => return Ok(false),
}
} else {
// Build TLS config (TLS 1.3 only)
let mut root_store = RootCertStore::empty();
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
TlsConnector::from(Arc::new(config))
};
// Try to connect - use custom SNI if specified
let sni_host = self.sni_hostname.as_ref().unwrap_or(&self.target.hostname);
let domain = rustls_pki_types::ServerName::try_from(sni_host.as_str())
.map_err(|_| anyhow::anyhow!("Invalid DNS name"))?
.to_owned();
match timeout(self.read_timeout, connector.connect(domain, stream)).await {
Ok(Ok(_)) => Ok(true),
_ => Ok(false),
}
}
/// Test QUIC support (UDP-based protocol)
///
/// QUIC testing is intentionally not implemented in this version because:
/// 1. QUIC uses UDP instead of TCP, requiring different connection handling
/// 2. Proper QUIC testing requires the quinn crate and additional dependencies
/// 3. QUIC/HTTP3 adoption is still growing and many servers don't support it
/// 4. The complexity-to-benefit ratio is currently not justified for a TLS scanner
///
/// Future implementation would require:
/// - quinn = "0.11" dependency
/// - UDP socket handling
/// - QUIC-specific handshake logic
/// - Version negotiation support
///
/// For now, this always returns false (QUIC not detected)
async fn test_quic_on_ip(&self, _addr: std::net::SocketAddr) -> Result<bool> {
// QUIC testing not implemented - requires UDP transport and quinn crate
// This is a conscious design decision, not an incomplete implementation
Ok(false)
}
/// Get preferred protocol (highest supported)
pub async fn get_preferred_protocol(&self) -> Result<Option<Protocol>> {
let results = self.test_all_protocols().await?;
// Return highest supported protocol
for protocol in [
Protocol::TLS13,
Protocol::TLS12,
Protocol::TLS11,
Protocol::TLS10,
Protocol::SSLv3,
Protocol::SSLv2,
] {
if results
.iter()
.any(|r| r.protocol == protocol && r.supported)
{
return Ok(Some(protocol));
}
}
Ok(None)
}
/// Detect heartbeat extension support for a specific protocol
/// This performs a manual TLS handshake to check if ServerHello contains extension 0x000f
async fn detect_heartbeat_extension(&self, protocol: Protocol) -> Result<bool> {
use super::handshake::{ClientHelloBuilder, ServerHelloParser};
let addr = self.target.socket_addrs()[0];
// Connect TCP
let mut stream = match timeout(
self.read_timeout,
crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
),
)
.await
{
Ok(Ok(s)) => s,
_ => return Ok(false),
};
// Send RDP preamble if needed
if self.use_rdp
&& crate::protocols::rdp::RdpPreamble::send(&mut stream)
.await
.is_err()
{
return Ok(false);
}
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok(false);
}
}
// Build ClientHello with minimal ciphers
let mut builder = ClientHelloBuilder::new(protocol);
builder.add_ciphers(&[0xc030, 0xc02f, 0x009e, 0x0035]);
// Use custom SNI if set, otherwise use target hostname
let sni_hostname = self
.sni_hostname
.as_deref()
.unwrap_or(&self.target.hostname);
let client_hello = builder.build_with_defaults(Some(sni_hostname))?;
// Send ClientHello and receive ServerHello
let response = match timeout(self.read_timeout, async {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
stream.write_all(&client_hello).await?;
// Read ServerHello (up to max TLS record size)
let mut resp = vec![0u8; BUFFER_SIZE_MAX_TLS_RECORD];
let n = stream.read(&mut resp).await?;
resp.truncate(n);
Ok::<Vec<u8>, anyhow::Error>(resp)
})
.await
{
Ok(Ok(resp)) if !resp.is_empty() => resp,
_ => return Ok(false),
};
// Parse ServerHello to check for heartbeat extension
match ServerHelloParser::parse(&response) {
Ok(server_hello) => {
// Check if heartbeat extension is present
Ok(server_hello.supports_heartbeat().unwrap_or(false))
}
Err(_) => Ok(false),
}
}
/// Detect session resumption support (caching and tickets) for a specific protocol
/// Returns (session_id_caching_supported, session_tickets_supported)
/// This performs a manual TLS handshake to check ServerHello for:
/// - Session ID: Non-empty session_id field indicates session ID caching support
/// - Session Tickets: Extension type 0x0023 (35) indicates RFC 5077 session tickets support
async fn detect_session_resumption(&self, protocol: Protocol) -> Result<(bool, bool)> {
use super::handshake::{ClientHelloBuilder, ServerHelloParser};
let addr = self.target.socket_addrs()[0];
// Connect TCP
let mut stream = match timeout(
self.read_timeout,
crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
),
)
.await
{
Ok(Ok(s)) => s,
_ => return Ok((false, false)),
};
// Send RDP preamble if needed
if self.use_rdp
&& crate::protocols::rdp::RdpPreamble::send(&mut stream)
.await
.is_err()
{
return Ok((false, false));
}
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok((false, false));
}
}
// Build ClientHello with minimal ciphers
let mut builder = ClientHelloBuilder::new(protocol);
builder.add_ciphers(&[0xc030, 0xc02f, 0x009e, 0x0035]);
// Use custom SNI if set, otherwise use target hostname
let sni_hostname = self
.sni_hostname
.as_deref()
.unwrap_or(&self.target.hostname);
let client_hello = builder.build_with_defaults(Some(sni_hostname))?;
// Send ClientHello and receive ServerHello
let response = match timeout(self.read_timeout, async {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
stream.write_all(&client_hello).await?;
// Read ServerHello (up to max TLS record size)
let mut resp = vec![0u8; BUFFER_SIZE_MAX_TLS_RECORD];
let n = stream.read(&mut resp).await?;
resp.truncate(n);
Ok::<Vec<u8>, anyhow::Error>(resp)
})
.await
{
Ok(Ok(resp)) if !resp.is_empty() => resp,
_ => return Ok((false, false)),
};
// Parse ServerHello to check for session resumption support
match ServerHelloParser::parse(&response) {
Ok(server_hello) => {
// Session ID caching: Check if session ID is present and non-empty
let session_id_caching = !server_hello.session_id.is_empty();
// Session tickets: Check for SessionTicket extension (type 0x0023)
let session_tickets = server_hello.has_extension(0x0023);
Ok((session_id_caching, session_tickets))
}
Err(_) => Ok((false, false)),
}
}
/// Detect secure renegotiation support (RFC 5746) for a specific protocol
/// This performs a manual TLS handshake to check if ServerHello contains extension 0xff01
async fn detect_secure_renegotiation(&self, protocol: Protocol) -> Result<bool> {
use super::handshake::{ClientHelloBuilder, ServerHelloParser};
let addr = self.target.socket_addrs()[0];
// Connect TCP
let mut stream = match timeout(
self.read_timeout,
crate::utils::network::connect_with_timeout(
addr,
self.connect_timeout,
self.retry_config.as_ref(),
),
)
.await
{
Ok(Ok(s)) => s,
_ => return Ok(false),
};
// Send RDP preamble if needed
if self.use_rdp
&& crate::protocols::rdp::RdpPreamble::send(&mut stream)
.await
.is_err()
{
return Ok(false);
}
// Perform STARTTLS negotiation if needed
if let Some(starttls_proto) = self.starttls_protocol {
let negotiator = crate::starttls::protocols::get_negotiator(
starttls_proto,
self.target.hostname.clone(),
);
if negotiator.negotiate_starttls(&mut stream).await.is_err() {
return Ok(false);
}
}
// Build ClientHello with minimal ciphers
let mut builder = ClientHelloBuilder::new(protocol);
builder.add_ciphers(&[0xc030, 0xc02f, 0x009e, 0x0035]);
// Use custom SNI if set, otherwise use target hostname
let sni_hostname = self
.sni_hostname
.as_deref()
.unwrap_or(&self.target.hostname);
let client_hello = builder.build_with_defaults(Some(sni_hostname))?;
// Send ClientHello and receive ServerHello
let response = match timeout(self.read_timeout, async {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
stream.write_all(&client_hello).await?;
// Read ServerHello (up to max TLS record size)
let mut resp = vec![0u8; BUFFER_SIZE_MAX_TLS_RECORD];
let n = stream.read(&mut resp).await?;
resp.truncate(n);
Ok::<Vec<u8>, anyhow::Error>(resp)
})
.await
{
Ok(Ok(resp)) if !resp.is_empty() => resp,
_ => return Ok(false),
};
// Parse ServerHello to check for secure renegotiation extension
match ServerHelloParser::parse(&response) {
Ok(server_hello) => {
// Check if renegotiation_info extension is present
Ok(server_hello
.supports_secure_renegotiation()
.unwrap_or(false))
}
Err(_) => Ok(false),
}
}
}
#[async_trait::async_trait]
impl ProtocolTestable for ProtocolTester {
async fn test_all_protocols(&self) -> Result<Vec<ProtocolTestResult>> {
self.test_all_protocols().await
}
async fn test_protocol(&self, protocol: Protocol) -> Result<ProtocolTestResult> {
self.test_protocol(protocol).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[ignore] // Requires network access
async fn test_protocol_detection() {
let target = Target::parse("www.google.com:443")
.await
.expect("test assertion should succeed");
let tester = ProtocolTester::new(target);
let results = tester
.test_all_protocols()
.await
.expect("test assertion should succeed");
// Google should support TLS 1.2 and 1.3
assert!(
results
.iter()
.any(|r| r.protocol == Protocol::TLS12 && r.supported)
);
assert!(
results
.iter()
.any(|r| r.protocol == Protocol::TLS13 && r.supported)
);
// Should NOT support SSLv2 or SSLv3
assert!(
results
.iter()
.any(|r| r.protocol == Protocol::SSLv2 && !r.supported)
);
assert!(
results
.iter()
.any(|r| r.protocol == Protocol::SSLv3 && !r.supported)
);
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_preferred_protocol() {
let target = Target::parse("www.google.com:443")
.await
.expect("test assertion should succeed");
let tester = ProtocolTester::new(target);
let preferred = tester
.get_preferred_protocol()
.await
.expect("test assertion should succeed");
// Should prefer TLS 1.3
assert_eq!(preferred, Some(Protocol::TLS13));
}
#[test]
fn test_sslv2_client_hello_build() {
let target = Target::with_ips(
"example.com".to_string(),
443,
vec!["93.184.216.34".parse().unwrap()],
)
.unwrap();
let tester = ProtocolTester::new(target);
let hello = tester.build_sslv2_client_hello();
assert!(hello.len() > 30);
assert_eq!(hello[0], 0x80); // High bit set
assert_eq!(hello[2], 0x01); // CLIENT-HELLO
}
}