website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
Documentation
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
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use chrono::{DateTime, Utc};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::WebPkiServerVerifier;
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_rustls::TlsConnector;
use url::Url;
use x509_parser::extensions::GeneralName;
use x509_parser::prelude::*;

use crate::models::{
    Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, TlsInfo, Verdict,
};

#[derive(Debug, Clone)]
struct CapturedCert {
    der: Vec<u8>,
    verify_error: Option<String>,
}

#[derive(Debug)]
struct InspectingVerifier {
    inner: Arc<WebPkiServerVerifier>,
    captured: Arc<Mutex<Option<CapturedCert>>>,
}

impl ServerCertVerifier for InspectingVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        let res = self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        );
        let verify_error = res.as_ref().err().map(|e| e.to_string());
        if let Ok(mut guard) = self.captured.lock() {
            *guard = Some(CapturedCert {
                der: end_entity.to_vec(),
                verify_error,
            });
        }
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

pub async fn inspect_tls(
    url: &Url,
    timeout_secs: u64,
    auth_context: &str,
) -> (Option<TlsInfo>, Vec<Finding>, CheckOutcome) {
    let mut findings = Vec::new();
    let loc = url.to_string();

    if url.scheme() != "https" {
        findings.push(Finding {
            id: "TLS-NO-HTTPS".into(),
            category: Category::TransportTls,
            severity: Severity::Critical,
            title: "Site is served over unencrypted HTTP (no HTTPS)".into(),
            summary: "Traffic, login forms, cookies, and tokens are transmitted in plaintext and can be intercepted or modified in transit.".into(),
            evidence: Some(loc.clone()),
            remediation: "Configure a TLS certificate (e.g., Let's Encrypt) and enforce a permanent 301/308 redirect from HTTP to HTTPS.".into(),
            standard_ref: Some("OWASP ASVS V9.1.1 / WSTG-CRYP-01".into()),
            confidence: Confidence::High,
        });
        return (
            None,
            findings,
            CheckOutcome {
                check_id: "tls-inspection".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::Fail,
                reason: Some("plaintext HTTP".into()),
            },
        );
    }

    let Some(host) = url.host_str() else {
        return (
            None,
            findings,
            CheckOutcome {
                check_id: "tls-inspection".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("missing host".into()),
            },
        );
    };
    let port = url.port_or_known_default().unwrap_or(443);
    let addr = format!("{host}:{port}");

    let mut root_store = RootCertStore::empty();
    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let Ok(inner_verifier) =
        WebPkiServerVerifier::builder_with_provider(Arc::new(root_store), provider.clone()).build()
    else {
        return (
            None,
            findings,
            CheckOutcome {
                check_id: "tls-inspection".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("verifier build failed".into()),
            },
        );
    };

    let captured = Arc::new(Mutex::new(None));
    let verifier = Arc::new(InspectingVerifier {
        inner: inner_verifier,
        captured: captured.clone(),
    });

    let config = ClientConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()
        .expect("valid default TLS protocol versions")
        .dangerous()
        .with_custom_certificate_verifier(verifier)
        .with_no_client_auth();

    let server_name = match ServerName::try_from(host.to_string()) {
        Ok(name) => name,
        Err(_) => {
            return (
                None,
                findings,
                CheckOutcome {
                    check_id: "tls-inspection".into(),
                    category: Category::TransportTls,
                    location: loc,
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some("invalid server name".into()),
                },
            );
        }
    };

    let dur = Duration::from_secs(timeout_secs);
    let tcp = match timeout(dur, TcpStream::connect(&addr)).await {
        Ok(Ok(stream)) => stream,
        Ok(Err(e)) => {
            findings.push(Finding {
                id: "TLS-CONNECT-ERR".into(),
                category: Category::TransportTls,
                severity: Severity::High,
                title: "Failed to establish TLS connection".into(),
                summary: format!("Could not connect to {addr} to inspect the TLS certificate: {e}"),
                evidence: Some(addr),
                remediation: "Verify port 443 reachability, firewall rules, and web server TLS configuration.".into(),
                standard_ref: Some("OWASP ASVS V9.1".into()),
                confidence: Confidence::High,
            });
            return (
                None,
                findings,
                CheckOutcome {
                    check_id: "tls-inspection".into(),
                    category: Category::TransportTls,
                    location: loc,
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some(e.to_string()),
                },
            );
        }
        Err(_) => {
            findings.push(Finding {
                id: "TLS-TIMEOUT".into(),
                category: Category::TransportTls,
                severity: Severity::High,
                title: "TLS handshake timed out".into(),
                summary: format!("Connection to {addr} exceeded {timeout_secs}s timeout."),
                evidence: Some(addr),
                remediation: "Check network latency and the TLS termination proxy / load balancer."
                    .into(),
                standard_ref: Some("OWASP ASVS V9.1".into()),
                confidence: Confidence::High,
            });
            return (
                None,
                findings,
                CheckOutcome {
                    check_id: "tls-inspection".into(),
                    category: Category::TransportTls,
                    location: loc,
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some("TLS connect timeout".into()),
                },
            );
        }
    };

    let connector = TlsConnector::from(Arc::new(config));
    let tls_stream = match timeout(dur, connector.connect(server_name, tcp)).await {
        Ok(Ok(s)) => s,
        Ok(Err(e)) => {
            findings.push(Finding {
                id: "TLS-HANDSHAKE-ERR".into(),
                category: Category::TransportTls,
                severity: Severity::High,
                title: "TLS handshake failed".into(),
                summary: format!(
                    "Server {addr} rejected the TLS connection or uses unsupported parameters: {e}"
                ),
                evidence: Some(e.to_string()),
                remediation:
                    "Ensure the server supports TLS 1.2 and/or TLS 1.3 with modern cipher suites."
                        .into(),
                standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
                confidence: Confidence::High,
            });
            return (
                None,
                findings,
                CheckOutcome {
                    check_id: "tls-inspection".into(),
                    category: Category::TransportTls,
                    location: loc,
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some(e.to_string()),
                },
            );
        }
        Err(_) => {
            return (
                None,
                findings,
                CheckOutcome {
                    check_id: "tls-inspection".into(),
                    category: Category::TransportTls,
                    location: loc,
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some("TLS handshake timeout".into()),
                },
            );
        }
    };

    let (_, conn) = tls_stream.get_ref();
    let protocol = conn
        .protocol_version()
        .map(|v| format!("{v:?}"))
        .unwrap_or_else(|| "Unknown".into());
    let cipher_suite = conn
        .negotiated_cipher_suite()
        .map(|c| format!("{:?}", c.suite()))
        .unwrap_or_else(|| "Unknown".into());

    let captured_guard = captured.lock().ok().and_then(|g| g.clone());
    let Some(cert_data) = captured_guard else {
        return (
            None,
            findings,
            CheckOutcome {
                check_id: "tls-inspection".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("no peer certificate captured".into()),
            },
        );
    };

    let Ok((_, cert)) = X509Certificate::from_der(&cert_data.der) else {
        return (
            None,
            findings,
            CheckOutcome {
                check_id: "tls-inspection".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("X.509 DER parse failed".into()),
            },
        );
    };

    let subject = cert.subject().to_string();
    let issuer = cert.issuer().to_string();
    let not_before_ts = cert.validity().not_before.timestamp();
    let not_after_ts = cert.validity().not_after.timestamp();

    let not_before = DateTime::from_timestamp(not_before_ts, 0)
        .map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
        .unwrap_or_else(|| not_before_ts.to_string());
    let not_after = DateTime::from_timestamp(not_after_ts, 0)
        .map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
        .unwrap_or_else(|| not_after_ts.to_string());

    let now_ts = Utc::now().timestamp();
    let days_remaining = (not_after_ts - now_ts) / 86_400;

    let mut sans = Vec::new();
    if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
        for name in &san_ext.value.general_names {
            match name {
                GeneralName::DNSName(dns) => sans.push((*dns).to_string()),
                GeneralName::IPAddress(bytes) => {
                    if let Ok(ip) = <[u8; 4]>::try_from(*bytes).map(IpAddr::from) {
                        sans.push(ip.to_string());
                    } else if let Ok(ip) = <[u8; 16]>::try_from(*bytes).map(IpAddr::from) {
                        sans.push(ip.to_string());
                    }
                }
                _ => {}
            }
        }
    }

    let hostname_matches = cert_data.verify_error.is_none();

    if let Some(err) = &cert_data.verify_error {
        findings.push(Finding {
            id: "TLS-CERT-UNTRUSTED".into(),
            category: Category::TransportTls,
            severity: Severity::Critical,
            title: "TLS certificate failed trust verification".into(),
            summary: format!("Browsers will show a security warning for visitors. Reason: {err}"),
            evidence: Some(format!("Subject: {subject} | Issuer: {issuer} | Error: {err}")),
            remediation: "Install a valid certificate from a trusted CA (e.g., Let's Encrypt), include the full intermediate chain, and ensure the hostname is listed in SAN.".into(),
            standard_ref: Some("OWASP ASVS V9.2.1 / WSTG-CRYP-01".into()),
            confidence: Confidence::High,
        });
    } else if days_remaining < 0 {
        findings.push(Finding {
            id: "TLS-CERT-EXPIRED".into(),
            category: Category::TransportTls,
            severity: Severity::Critical,
            title: "TLS certificate has expired".into(),
            summary: format!("Certificate expired on {not_after} ({} days ago).", -days_remaining),
            evidence: Some(format!("notAfter: {not_after}")),
            remediation: "Renew the certificate immediately and configure automated renewal (certbot / acme.sh).".into(),
            standard_ref: Some("OWASP ASVS V9.2.1 / WSTG-CRYP-01".into()),
            confidence: Confidence::High,
        });
    } else if days_remaining <= 14 {
        findings.push(Finding {
            id: "TLS-CERT-EXPIRING-SOON".into(),
            category: Category::TransportTls,
            severity: Severity::High,
            title: "TLS certificate expires soon (<= 14 days)".into(),
            summary: format!("Certificate expires in {days_remaining} days (on {not_after})."),
            evidence: Some(format!("notAfter: {not_after}")),
            remediation: "Check automated certificate renewal (certbot renew / cron / systemd timer).".into(),
            standard_ref: Some("OWASP ASVS V9.2.1".into()),
            confidence: Confidence::High,
        });
    } else if days_remaining <= 30 {
        findings.push(Finding {
            id: "TLS-CERT-EXPIRING-30D".into(),
            category: Category::TransportTls,
            severity: Severity::Low,
            title: "TLS certificate expires within 30 days".into(),
            summary: format!("{days_remaining} days remaining (until {not_after})."),
            evidence: Some(format!("notAfter: {not_after}")),
            remediation: "Ensure automated certificate renewal is scheduled and healthy.".into(),
            standard_ref: Some("OWASP ASVS V9.2.1".into()),
            confidence: Confidence::High,
        });
    } else {
        findings.push(Finding {
            id: "TLS-CERT-OK".into(),
            category: Category::TransportTls,
            severity: Severity::Pass,
            title: "TLS certificate is valid and trusted".into(),
            summary: format!("Negotiated {protocol}; certificate valid for {days_remaining} more days (until {not_after})."),
            evidence: Some(format!("{protocol} | {cipher_suite} | Issuer: {issuer}")),
            remediation: String::new(),
            standard_ref: Some("OWASP ASVS V9.1 / V9.2".into()),
            confidence: Confidence::High,
        });
    }

    if protocol.contains("TLSv1_0") || protocol.contains("TLSv1_1") {
        findings.push(Finding {
            id: "TLS-LEGACY-PROTOCOL".into(),
            category: Category::TransportTls,
            severity: Severity::High,
            title: "Legacy TLS protocol version negotiated".into(),
            summary: format!(
                "Negotiated legacy protocol {protocol}, which has known cryptographic weaknesses."
            ),
            evidence: Some(protocol.clone()),
            remediation: "Disable TLS 1.0 and TLS 1.1; enable only TLSv1.2 and TLSv1.3.".into(),
            standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
            confidence: Confidence::High,
        });
    }

    let info = TlsInfo {
        protocol,
        cipher_suite,
        subject,
        issuer,
        sans,
        not_before,
        not_after,
        days_remaining,
        hostname_matches,
    };

    let any_fail = findings
        .iter()
        .any(|f| f.severity != Severity::Pass && f.severity != Severity::Info);

    (
        Some(info),
        findings,
        CheckOutcome {
            check_id: "tls-inspection".into(),
            category: Category::TransportTls,
            location: loc,
            auth_context: auth_context.to_string(),
            status: ExecutionStatus::Completed,
            verdict: if any_fail {
                Verdict::Fail
            } else {
                Verdict::Pass
            },
            reason: None,
        },
    )
}

/// Checks whether plain HTTP (`http://host`) properly redirects to `https://`.
pub async fn check_http_redirect(
    https_url: &Url,
    auth_context: &str,
) -> (Option<Finding>, CheckOutcome) {
    if https_url.scheme() != "https" {
        return (
            None,
            CheckOutcome {
                check_id: "http-redirect".into(),
                category: Category::TransportTls,
                location: https_url.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Skipped,
                verdict: Verdict::NotApplicable,
                reason: Some("target scheme is not https".into()),
            },
        );
    }

    let mut http_url = https_url.clone();
    if http_url.set_scheme("http").is_err() {
        return (
            None,
            CheckOutcome {
                check_id: "http-redirect".into(),
                category: Category::TransportTls,
                location: https_url.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("failed to construct http URL".into()),
            },
        );
    }
    if https_url.port() == Some(443) {
        let _ = http_url.set_port(None);
    }

    let no_redir = match reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(Duration::from_secs(6))
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            return (
                None,
                CheckOutcome {
                    check_id: "http-redirect".into(),
                    category: Category::TransportTls,
                    location: http_url.to_string(),
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Error,
                    verdict: Verdict::Inconclusive,
                    reason: Some(e.to_string()),
                },
            );
        }
    };

    let resp = match no_redir
        .get(http_url.as_str())
        .header(reqwest::header::USER_AGENT, "web-vuln-scanner")
        .send()
        .await
    {
        Ok(r) => r,
        Err(_) => {
            return (
                Some(Finding {
                    id: "TLS-HTTP-CLOSED".into(),
                    category: Category::TransportTls,
                    severity: Severity::Info,
                    title: "HTTP port (80) is not reachable".into(),
                    summary: "Port 80 is closed or unreachable. Visitors typing http:// will not be redirected unless HSTS Preload is active.".into(),
                    evidence: Some(http_url.to_string()),
                    remediation: "Optionally configure a lightweight 301 redirect from HTTP to HTTPS.".into(),
                    standard_ref: Some("OWASP ASVS V9.1.1".into()),
                    confidence: Confidence::Medium,
                }),
                CheckOutcome {
                    check_id: "http-redirect".into(),
                    category: Category::TransportTls,
                    location: http_url.to_string(),
                    auth_context: auth_context.to_string(),
                    status: ExecutionStatus::Completed,
                    verdict: Verdict::Pass,
                    reason: Some("port 80 unreachable".into()),
                },
            );
        }
    };

    let status = resp.status();
    let location = resp
        .headers()
        .get(reqwest::header::LOCATION)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    if status.is_redirection() && location.starts_with("https://") {
        (
            Some(Finding {
                id: "TLS-HTTP-REDIRECT-OK".into(),
                category: Category::TransportTls,
                severity: Severity::Pass,
                title: "HTTP redirects cleanly to HTTPS".into(),
                summary: format!("HTTP request returned status {status} -> {location}."),
                evidence: Some(format!("{http_url} -> {status} {location}")),
                remediation: String::new(),
                standard_ref: Some("OWASP ASVS V9.1.1".into()),
                confidence: Confidence::High,
            }),
            CheckOutcome {
                check_id: "http-redirect".into(),
                category: Category::TransportTls,
                location: http_url.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::Pass,
                reason: None,
            },
        )
    } else if status.is_success() {
        (
            Some(Finding {
                id: "TLS-HTTP-NO-REDIRECT".into(),
                category: Category::TransportTls,
                severity: Severity::Medium,
                title: "Site serves content over plain HTTP without redirecting to HTTPS".into(),
                summary: "Accessing http:// does not upgrade the user to https://, enabling SSL stripping / downgrade attacks.".into(),
                evidence: Some(format!("{http_url} -> HTTP {status}")),
                remediation: "Add a 301/308 redirect rule from http:// to https:// in Nginx/Caddy/Cloudflare.".into(),
                standard_ref: Some("OWASP ASVS V9.1.1 / WSTG-CRYP-01".into()),
                confidence: Confidence::High,
            }),
            CheckOutcome {
                check_id: "http-redirect".into(),
                category: Category::TransportTls,
                location: http_url.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::Fail,
                reason: None,
            },
        )
    } else {
        (
            None,
            CheckOutcome {
                check_id: "http-redirect".into(),
                category: Category::TransportTls,
                location: http_url.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::Pass,
                reason: Some(format!("HTTP {status}")),
            },
        )
    }
}

fn build_client_hello(major: u8, minor: u8, sni_host: Option<&str>) -> Vec<u8> {
    let mut ext = Vec::new();
    if let Some(host) = sni_host {
        if host.parse::<IpAddr>().is_err() && !host.is_empty() && host.len() < 250 {
            let host_bytes = host.as_bytes();
            let list_len = (host_bytes.len() + 3) as u16;
            let ext_len = list_len + 2;
            ext.extend_from_slice(&[0x00, 0x00]); // server_name extension
            ext.extend_from_slice(&ext_len.to_be_bytes());
            ext.extend_from_slice(&list_len.to_be_bytes());
            ext.push(0x00); // host_name
            ext.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
            ext.extend_from_slice(host_bytes);
        }
    }

    let ciphers: &[u8] = &[
        0xc0, 0x2f, // ECDHE-RSA-AES128-GCM-SHA256
        0xc0, 0x13, // ECDHE-RSA-AES128-SHA
        0xc0, 0x14, // ECDHE-RSA-AES256-SHA
        0x00, 0x9c, // RSA-AES128-GCM-SHA256
        0x00, 0x2f, // RSA-AES128-SHA
        0x00, 0x35, // RSA-AES256-SHA
    ];

    let mut body = Vec::new();
    body.push(major);
    body.push(minor);
    body.extend_from_slice(&[0x42; 32]); // Client random
    body.push(0x00); // Session ID len
    body.extend_from_slice(&(ciphers.len() as u16).to_be_bytes());
    body.extend_from_slice(ciphers);
    body.push(0x01); // Compression methods len
    body.push(0x00); // null compression
    if !ext.is_empty() {
        body.extend_from_slice(&(ext.len() as u16).to_be_bytes());
        body.extend_from_slice(&ext);
    }

    let mut handshake = Vec::with_capacity(body.len() + 4);
    handshake.push(0x01); // ClientHello
    let bl = body.len() as u32;
    handshake.push(((bl >> 16) & 0xff) as u8);
    handshake.push(((bl >> 8) & 0xff) as u8);
    handshake.push((bl & 0xff) as u8);
    handshake.extend_from_slice(&body);

    let mut record = Vec::with_capacity(handshake.len() + 5);
    record.push(0x16); // Handshake
    record.push(0x03);
    record.push(0x01); // Record layer TLS 1.0 compatibility
    record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
    record.extend_from_slice(&handshake);
    record
}

async fn accepts_legacy_tls_version(
    host: &str,
    port: u16,
    minor: u8,
    dur: Duration,
) -> Result<bool, String> {
    let addr = format!("{host}:{port}");
    let mut stream = timeout(dur, TcpStream::connect(&addr))
        .await
        .map_err(|_| "connect timeout".to_string())?
        .map_err(|e| e.to_string())?;

    let hello = build_client_hello(0x03, minor, Some(host));
    timeout(dur, stream.write_all(&hello))
        .await
        .map_err(|_| "write timeout".to_string())?
        .map_err(|e| e.to_string())?;

    let mut buf = [0u8; 64];
    let n = match timeout(dur, stream.read(&mut buf)).await {
        Ok(Ok(n)) => n,
        _ => return Ok(false),
    };
    // TLS Handshake record (0x16), ServerHello (buf[5] == 0x02), server_version (buf[9..=10])
    if n >= 11 && buf[0] == 0x16 && buf[5] == 0x02 {
        return Ok(buf[9] == 0x03 && buf[10] == minor);
    }
    Ok(false)
}

pub async fn probe_legacy_tls_versions(
    url: &Url,
    timeout_secs: u64,
    auth_context: &str,
) -> (Vec<Finding>, CheckOutcome) {
    let loc = url.to_string();
    if url.scheme() != "https" {
        return (
            Vec::new(),
            CheckOutcome {
                check_id: "tls-legacy-versions".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::NotApplicable,
                reason: Some("plaintext HTTP target".into()),
            },
        );
    }

    let Some(host) = url.host_str() else {
        return (
            Vec::new(),
            CheckOutcome {
                check_id: "tls-legacy-versions".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some("missing host".into()),
            },
        );
    };

    let port = url.port_or_known_default().unwrap_or(443);
    let dur = Duration::from_secs(timeout_secs.clamp(1, 5));

    let mut accepted = Vec::new();
    let mut probe_err: Option<String> = None;

    for (minor, label) in [(0x01u8, "TLS 1.0"), (0x02u8, "TLS 1.1")] {
        match accepts_legacy_tls_version(host, port, minor, dur).await {
            Ok(true) => accepted.push(label),
            Ok(false) => {}
            Err(e) => probe_err = Some(e),
        }
    }

    if !accepted.is_empty() {
        let joined = accepted.join(", ");
        return (
            vec![Finding {
                id: "TLS-LEGACY-PROTOCOL".into(),
                category: Category::TransportTls,
                severity: Severity::High,
                title: format!("Deprecated TLS protocol enabled: {joined}"),
                summary: "Server negotiated deprecated TLS 1.0/1.1 protocols, which have known cryptographic weaknesses and violate modern compliance baselines.".into(),
                evidence: Some(format!("{host}:{port} accepted {joined}")),
                remediation: "Disable TLS 1.0 and TLS 1.1 on the reverse proxy / CDN and allow only TLS 1.2 and TLS 1.3.".into(),
                standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
                confidence: Confidence::High,
            }],
            CheckOutcome {
                check_id: "tls-legacy-versions".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Completed,
                verdict: Verdict::Fail,
                reason: Some(joined),
            },
        );
    }

    if let Some(err) = probe_err {
        return (
            Vec::new(),
            CheckOutcome {
                check_id: "tls-legacy-versions".into(),
                category: Category::TransportTls,
                location: loc,
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some(err),
            },
        );
    }

    (
        vec![Finding {
            id: "TLS-LEGACY-DISABLED".into(),
            category: Category::TransportTls,
            severity: Severity::Pass,
            title: "Deprecated TLS 1.0 and TLS 1.1 are disabled".into(),
            summary: format!(
                "TLS 1.0 and TLS 1.1 handshake probes were rejected on {host}:{port}."
            ),
            evidence: None,
            remediation: String::new(),
            standard_ref: Some("OWASP ASVS V9.1.2".into()),
            confidence: Confidence::High,
        }],
        CheckOutcome {
            check_id: "tls-legacy-versions".into(),
            category: Category::TransportTls,
            location: loc,
            auth_context: auth_context.to_string(),
            status: ExecutionStatus::Completed,
            verdict: Verdict::Pass,
            reason: None,
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::net::TcpListener;

    #[tokio::test]
    async fn detects_legacy_tls_10_server_hello() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        tokio::spawn(async move {
            for _ in 0..2 {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut req = [0u8; 256];
                let n = sock.read(&mut req).await.unwrap_or(0);
                // Echo ServerHello only if client requested TLS 1.0 (req[10] == 0x01)
                if n >= 11 && req[9] == 0x03 && req[10] == 0x01 {
                    let sh: [u8; 11] = [
                        0x16, 0x03, 0x01, 0x00, 0x07, 0x02, 0x00, 0x00, 0x03, 0x03, 0x01,
                    ];
                    let _ = sock.write_all(&sh).await;
                } else {
                    let alert: [u8; 7] = [0x15, 0x03, 0x02, 0x00, 0x02, 0x02, 0x46];
                    let _ = sock.write_all(&alert).await;
                }
            }
        });

        let url = Url::parse(&format!("https://127.0.0.1:{}/", addr.port())).unwrap();
        let (findings, outcome) = probe_legacy_tls_versions(&url, 3, "anonymous").await;
        assert_eq!(outcome.verdict, Verdict::Fail);
        assert!(findings.iter().any(|f| f.id == "TLS-LEGACY-PROTOCOL"));
    }
}