noctis 0.6.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
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
//! Persistent raw TCP/TLS socket for multi-round-trip exchanges.
//!
//! Unlike `tcp_connect` (one send, one read) and `tcp_dialogue` (a fixed
//! command/frame list resolved up front), this primitive keeps one connection
//! open across several engine steps so a later frame can be *computed from* an
//! earlier reply. It is the building block for binary challenge–response
//! protocols — e.g. the Erlang distribution handshake
//! (`send NAME_MSG → read challenge → send MD5(cookie+challenge) → read result`)
//! — and mirrors NASL's `open_sock_tcp` / `send` / `recv` / `close`.
//!
//! The engine drives the exchange through `tcp_open`, `tcp_send`,
//! `tcp_starttls` (upgrade the open cleartext socket to TLS in place) and
//! `tcp_close`; between `tcp_send` steps an ordinary `script`
//! step computes the next frame with the existing `unpack` / `md5` / `pack`
//! builtins. No protocol specifics live here — the feed drives every byte.

use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpSocket, TcpStream};
use tokio::time::timeout;
use tokio_rustls::client::TlsStream;
use tokio_rustls::TlsConnector;

use super::legacy_tls::{self, ClientTls};

use rustls::pki_types::ServerName;

use super::tcp::insecure_client_config;
use crate::error::{NoctisError, Result};

/// Idle gap that marks the end of one reply (the socket stays open). The first
/// byte of a reply may take up to the step's `timeout_secs` (#1336).
const READ_IDLE_MS: u64 = 500;
/// Hard cap on bytes accumulated for a single reply.
const MAX_REPLY_BYTES: usize = 64 * 1024;
/// Reserved source ports tried (from the top down) by `reserved_source_port`.
/// BSD r-services accept 512–1023 (`IPPORT_RESERVED / 2 ..= IPPORT_RESERVED - 1`).
const RESERVED_PORT_RANGE: std::ops::RangeInclusive<u16> = 512..=1023;
/// Bound on how many reserved ports are tried when the top ones are busy.
const RESERVED_PORT_ATTEMPTS: usize = 64;

/// A live connection held in the execution context across steps.
pub enum Conn {
    Plain(TcpStream),
    Tls(Box<ClientTls>),
}

/// Result of `tcp_open` — stored via `store_as`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenResult {
    pub connected: bool,
    /// Greeting bytes as lossy text, when `read_banner` captured any.
    pub banner: Option<String>,
    /// Greeting bytes as lowercase hex, when any arrived.
    pub banner_hex: Option<String>,
    /// Local (source) port of the connection; 0 when it could not be opened.
    /// Below 1024 when `reserved_source_port` obtained a reserved port.
    pub local_port: u16,
    pub duration_ms: u64,
}

/// Result of `tcp_send` — stored via `store_as`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendResult {
    /// The handle was open and the frame was written.
    pub sent: bool,
    /// At least one reply byte arrived before the idle gap / EOF.
    pub responded: bool,
    /// Reply as lossy text (ASCII markers inside binary replies survive).
    pub response: Option<String>,
    /// Reply as lowercase hex — use for binary offset parsing (`u32be`, …).
    pub response_hex: Option<String>,
    pub length: usize,
    pub duration_ms: u64,
}

/// Result of `tcp_starttls` — stored via `store_as`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StartTlsResult {
    /// The handle was a cleartext socket and the TLS handshake completed on it.
    pub upgraded: bool,
    /// Negotiated protocol, e.g. `"TLSv1_3"` (same form as `tls_check`).
    pub protocol_version: Option<String>,
    pub cipher_suite: Option<String>,
    /// Leaf certificate fields (the certificate itself is never verified).
    pub cert_subject: Option<String>,
    pub cert_issuer: Option<String>,
    pub cert_expiry: Option<String>,
    pub cert_sans: Vec<String>,
    /// Why the upgrade failed (no such handle, already TLS, handshake error).
    pub error: Option<String>,
    pub duration_ms: u64,
}

#[cfg(test)]
fn to_text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).trim_end().to_string()
}

#[cfg(test)]
fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// How long to wait for the first reply byte: the step's `timeout_secs`, never
/// less than the idle gap (so `timeout_secs: 0` keeps the old 500 ms poll).
pub fn first_byte_wait(timeout_secs: u64) -> Duration {
    Duration::from_millis(timeout_secs.saturating_mul(1000).max(READ_IDLE_MS))
}

/// Read one reply: wait up to `first_wait` for the first byte, then read until
/// no bytes arrive for `READ_IDLE_MS`, EOF, or the byte cap.
async fn read_reply<S: AsyncReadExt + Unpin>(stream: &mut S, first_wait: Duration) -> Vec<u8> {
    let mut acc = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        let wait = if acc.is_empty() {
            first_wait
        } else {
            Duration::from_millis(READ_IDLE_MS)
        };
        match timeout(wait, stream.read(&mut chunk)).await {
            Ok(Ok(0)) => break, // EOF
            Ok(Ok(n)) => {
                acc.extend_from_slice(&chunk[..n]);
                if acc.len() >= MAX_REPLY_BYTES {
                    break;
                }
            }
            Ok(Err(_)) => break, // read error
            Err(_) => break,     // no first byte in time, or idle gap → reply complete
        }
    }
    acc
}

/// Connect to `addr` from a reserved source port, trying ports from 1023 down.
/// `Ok(None)` means no reserved port could be bound (insufficient privilege or
/// every tried port busy) and the caller should connect normally; a connect
/// error other than a busy 4-tuple (refused, unreachable, timeout) is returned.
async fn connect_from_reserved_port(addr: &str, timeout_secs: u64) -> Result<Option<TcpStream>> {
    let target = tokio::net::lookup_host(addr)
        .await
        .map_err(|e| NoctisError::Tcp(format!("resolve {addr}: {e}")))?
        .next()
        .ok_or_else(|| NoctisError::Tcp(format!("resolve {addr}: no address")))?;
    let local_ip: std::net::IpAddr = if target.is_ipv4() {
        std::net::Ipv4Addr::UNSPECIFIED.into()
    } else {
        std::net::Ipv6Addr::UNSPECIFIED.into()
    };
    for src in RESERVED_PORT_RANGE.rev().take(RESERVED_PORT_ATTEMPTS) {
        let sock = if target.is_ipv4() {
            TcpSocket::new_v4()
        } else {
            TcpSocket::new_v6()
        }
        .map_err(|e| NoctisError::Tcp(format!("socket: {e}")))?;
        let _ = sock.set_reuseaddr(true);
        match sock.bind((local_ip, src).into()) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                tracing::warn!(%addr, "reserved source port unavailable (needs root or CAP_NET_BIND_SERVICE); using an ephemeral port");
                return Ok(None);
            }
            Err(_) => continue, // busy — try the next one down
        }
        match timeout(Duration::from_secs(timeout_secs), sock.connect(target)).await {
            Ok(Ok(s)) => return Ok(Some(s)),
            Ok(Err(e))
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::AddrInUse | std::io::ErrorKind::AddrNotAvailable
                ) =>
            {
                continue; // same 4-tuple still in TIME_WAIT
            }
            Ok(Err(e)) => return Err(NoctisError::Tcp(format!("connect {addr}: {e}"))),
            Err(_) => return Err(NoctisError::Tcp(format!("connect {addr}: timed out"))),
        }
    }
    tracing::warn!(%addr, "no free reserved source port; using an ephemeral port");
    Ok(None)
}

/// TLS client handshake over `tcp` (any certificate accepted). `timeout_secs`
/// bounds the handshake when given.
async fn tls_handshake(
    tcp: TcpStream,
    host: &str,
    timeout_secs: Option<u64>,
) -> Result<TlsStream<TcpStream>> {
    let peer = match tcp.peer_addr() {
        Ok(a) => format!("{host}:{}", a.port()),
        Err(_) => host.to_string(),
    };
    let connector = TlsConnector::from(Arc::new(insecure_client_config()?));
    let server_name = ServerName::try_from(host.to_string())
        .map_err(|e| NoctisError::Tcp(format!("invalid host for TLS SNI: {e}")))?;
    let handshake = connector.connect(server_name, tcp);
    let res = match timeout_secs {
        Some(secs) => timeout(Duration::from_secs(secs.max(1)), handshake)
            .await
            .map_err(|_| NoctisError::Tcp(format!("TLS handshake {peer}: timed out")))?,
        None => handshake.await,
    };
    res.map_err(|e| NoctisError::Tcp(format!("TLS handshake {peer}: {e}")))
}

impl Conn {
    /// Open a connection (optionally wrapped in TLS). Does not read anything.
    ///
    /// `reserved_source_port` connects from a reserved source port (512–1023),
    /// which BSD r-services (rshd/rlogind) demand of their clients. When no
    /// reserved port can be bound (no root / CAP_NET_BIND_SERVICE, or all busy)
    /// the connection falls back to an ordinary ephemeral source port; callers
    /// read the port actually used with [`Conn::local_port`].
    pub async fn open(
        host: &str,
        port: u16,
        use_tls: bool,
        timeout_secs: u64,
        reserved_source_port: bool,
    ) -> Result<Conn> {
        let addr = format!("{host}:{port}");
        let reserved = if reserved_source_port {
            connect_from_reserved_port(&addr, timeout_secs).await?
        } else {
            None
        };
        let tcp = match reserved {
            Some(s) => s,
            None => {
                match timeout(Duration::from_secs(timeout_secs), TcpStream::connect(&addr)).await {
                    Ok(Ok(s)) => s,
                    Ok(Err(e)) => return Err(NoctisError::Tcp(format!("connect {addr}: {e}"))),
                    Err(_) => return Err(NoctisError::Tcp(format!("connect {addr}: timed out"))),
                }
            }
        };
        if use_tls {
            // rustls first, then the legacy OpenSSL stack on a new connection
            // (from a reserved port again when one was asked for, #2446).
            let config = Arc::new(insecure_client_config()?);
            let reconnect = || async move {
                let again = if reserved_source_port {
                    connect_from_reserved_port(&addr, timeout_secs).await?
                } else {
                    None
                };
                match again {
                    Some(s) => Ok(s),
                    None => {
                        match timeout(Duration::from_secs(timeout_secs), TcpStream::connect(&addr))
                            .await
                        {
                            Ok(Ok(s)) => Ok(s),
                            Ok(Err(e)) => Err(NoctisError::Tcp(format!("connect {addr}: {e}"))),
                            Err(_) => Err(NoctisError::Tcp(format!("connect {addr}: timed out"))),
                        }
                    }
                }
            };
            let tls = legacy_tls::connect(
                tcp,
                host,
                config,
                Some(Duration::from_secs(timeout_secs.max(1))),
                reconnect,
            )
            .await
            .map_err(|e| NoctisError::Tcp(format!("TLS handshake {host}:{port}: {e}")))?;
            Ok(Conn::Tls(Box::new(tls)))
        } else {
            Ok(Conn::Plain(tcp))
        }
    }

    /// STARTTLS: run a TLS client handshake on an open cleartext connection
    /// and return the TLS-wrapped connection, with the negotiated session
    /// details. Same insecure config as `tls: true` (any certificate is
    /// accepted). The handshake is bounded by `timeout_secs`.
    ///
    /// An already-TLS connection is handed back unchanged in `Err`, so the
    /// caller keeps it; a failed handshake consumes the socket (its state is
    /// undefined mid-handshake) and returns `Err((None, …))`.
    pub async fn starttls(
        self,
        host: &str,
        timeout_secs: u64,
    ) -> std::result::Result<(Conn, StartTlsResult), (Option<Conn>, NoctisError)> {
        let tcp = match self {
            Conn::Plain(tcp) => tcp,
            tls @ Conn::Tls(_) => {
                return Err((
                    Some(tls),
                    NoctisError::Tcp("socket is already TLS".to_string()),
                ))
            }
        };
        // rustls only: a failed handshake leaves the upgraded session unusable
        // and the cleartext prelude cannot be replayed, so there is no legacy
        // OpenSSL retry here (unlike `tls: true` connections).
        let stream = ClientTls::Rustls(Box::new(
            tls_handshake(tcp, host, Some(timeout_secs))
                .await
                .map_err(|e| (None, e))?,
        ));
        let session = stream.session_info();
        let cert = super::tls::cert_info(session.chain.first().map(Vec::as_slice));
        let result = StartTlsResult {
            upgraded: true,
            protocol_version: session.protocol_version,
            cipher_suite: session.cipher_suite,
            cert_subject: cert.subject,
            cert_issuer: cert.issuer,
            cert_expiry: cert.expiry,
            cert_sans: cert.sans,
            error: None,
            duration_ms: 0,
        };
        Ok((Conn::Tls(Box::new(stream)), result))
    }

    /// Local (source) port of the underlying TCP connection, 0 if unknown.
    pub fn local_port(&self) -> u16 {
        let tcp = match self {
            Conn::Plain(s) => s,
            Conn::Tls(s) => s.tcp(),
        };
        tcp.local_addr().map(|a| a.port()).unwrap_or(0)
    }

    /// Write a frame verbatim.
    pub async fn send(&mut self, bytes: &[u8]) -> Result<()> {
        let r = match self {
            Conn::Plain(s) => s.write_all(bytes).await,
            Conn::Tls(s) => s.write_all(bytes).await,
        };
        r.map_err(|e| NoctisError::Tcp(format!("send: {e}")))
    }

    /// Read one reply: up to `first_wait` for the first byte (see
    /// [`first_byte_wait`]), then until the idle gap / EOF / byte cap.
    pub async fn read_reply(&mut self, first_wait: Duration) -> Vec<u8> {
        match self {
            Conn::Plain(s) => read_reply(s, first_wait).await,
            Conn::Tls(s) => read_reply(s, first_wait).await,
        }
    }
}

/// Test-only STARTTLS server (SMTP-shaped): cleartext `220 ready` greeting,
/// `STARTTLS` → `220 go ahead`, then a TLS handshake on the same socket with a
/// self-signed certificate (CN `noctis-starttls-test`, SAN `starttls.test`);
/// over TLS it answers `PING` with `PONG-TLS`. Any other cleartext command is
/// answered `502 no` and the session ends. Shared with the runner tests.
#[cfg(test)]
pub(crate) mod starttls_test_server {
    use std::sync::Arc;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;
    use tokio_rustls::TlsAcceptor;

    use rustls::pki_types::pem::PemObject;
    use rustls::pki_types::{CertificateDer, PrivateKeyDer};

    // Throwaway test-only key pair (self-signed, never used outside tests).
    const CERT_PEM: &str = concat!(
        "-----BEGIN CERTIFICATE-----\n",
        "MIIBrzCCAVWgAwIBAgIUKg76qQzhtbXlhzEbsNXErDF4wB4wCgYIKoZIzj0EAwIw\n",
        "HzEdMBsGA1UEAwwUbm9jdGlzLXN0YXJ0dGxzLXRlc3QwIBcNMjYxMjA2MDI1NzEz\n",
        "WhgPMjEyNjExMTIwMjU3MTNaMB8xHTAbBgNVBAMMFG5vY3Rpcy1zdGFydHRscy10\n",
        "ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEbWAea7QK96/TWtffI20VYenj\n",
        "gVPHjGj41W1J+LUe0mIC7PYB6DT2irMaDN4lUwoTJdN754YpBYgqlxG5+Me35qNt\n",
        "MGswHQYDVR0OBBYEFC8KECW5aKeTwoSDXyTzhLNTLnfnMB8GA1UdIwQYMBaAFC8K\n",
        "ECW5aKeTwoSDXyTzhLNTLnfnMA8GA1UdEwEB/wQFMAMBAf8wGAYDVR0RBBEwD4IN\n",
        "c3RhcnR0bHMudGVzdDAKBggqhkjOPQQDAgNIADBFAiA/H9S0zglvwI/tksax09e/\n",
        "GdB6CCJZbk7hrm3GX4lvRwIhAMKdXEk9fSCoY/YmYHCTkIPmVEakyvlEVUlV+M+R\n",
        "lHz3\n",
        "-----END CERTIFICATE-----\n",
    );
    const KEY_PEM: &str = concat!(
        "-----BEGIN PRIVATE KEY-----\n",
        "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPIRVbPqQqeP172rz\n",
        "eA5Kp63Sie7kpx0dDA9893Mbbg+hRANCAARtYB5rtAr3r9Na198jbRVh6eOBU8eM\n",
        "aPjVbUn4tR7SYgLs9gHoNPaKsxoM3iVTChMl03vnhikFiCqXEbn4x7fm\n",
        "-----END PRIVATE KEY-----\n",
    );

    fn acceptor() -> TlsAcceptor {
        let cert = CertificateDer::from_pem_slice(CERT_PEM.as_bytes()).unwrap();
        let key = PrivateKeyDer::from_pem_slice(KEY_PEM.as_bytes()).unwrap();
        let config =
            rustls::ServerConfig::builder_with_provider(crate::checks::tcp::crypto_provider())
                .with_safe_default_protocol_versions()
                .unwrap()
                .with_no_client_auth()
                .with_single_cert(vec![cert], key)
                .unwrap();
        TlsAcceptor::from(Arc::new(config))
    }

    /// Serve direct TLS (no STARTTLS prelude) with this modern rustls config,
    /// keeping each session open briefly; returns the port.
    pub(crate) async fn spawn_direct_tls() -> (u16, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let h = tokio::spawn(async move {
            while let Ok((sock, _)) = listener.accept().await {
                tokio::spawn(async move {
                    if let Ok(_tls) = acceptor().accept(sock).await {
                        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
                    }
                });
            }
        });
        (port, h)
    }

    /// Serve one connection; returns the listening address.
    pub async fn spawn() -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let Ok((mut sock, _)) = listener.accept().await else {
                return;
            };
            let _ = sock.write_all(b"220 ready\r\n").await;
            let mut buf = [0u8; 256];
            let n = sock.read(&mut buf).await.unwrap_or(0);
            if &buf[..n] != b"STARTTLS\r\n" {
                let _ = sock.write_all(b"502 no\r\n").await;
                return;
            }
            let _ = sock.write_all(b"220 go ahead\r\n").await;
            let Ok(mut tls) = acceptor().accept(sock).await else {
                return;
            };
            let n = tls.read(&mut buf).await.unwrap_or(0);
            if &buf[..n] == b"PING" {
                let _ = tls.write_all(b"PONG-TLS").await;
                let _ = tls.flush().await;
            }
            // keep the session up past the client's read
            tokio::time::sleep(std::time::Duration::from_secs(3)).await;
        });
        addr
    }
}

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

    /// A scripted challenge–response server mirroring the Erlang flow:
    /// greet, then reply to frame 1 with a 4-byte challenge, and to frame 2
    /// with "ok" only when it carries the expected digest bytes.
    async fn challenge_server() -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((mut sock, _)) = listener.accept().await {
                let _ = sock.write_all(b"HELLO\r\n").await;
                let mut buf = [0u8; 1024];
                // frame 1 → challenge 0x01020304
                if let Ok(n) = sock.read(&mut buf).await {
                    if n > 0 {
                        let _ = sock.write_all(&[0x00, 0x01, 0x02, 0x03, 0x04]).await;
                    }
                }
                // frame 2 → "accepted" when the last 4 bytes are the digest
                if let Ok(n) = sock.read(&mut buf).await {
                    if n >= 4 && buf[n - 4..n] == [0xde, 0xad, 0xbe, 0xef] {
                        let _ = sock.write_all(b"accepted").await;
                    } else {
                        let _ = sock.write_all(b"denied").await;
                    }
                }
            }
        });
        addr
    }

    /// `tcp_open` with `tls: true` reaches an RSA-key-exchange-only server
    /// through the legacy OpenSSL retry (#2446).
    #[tokio::test]
    async fn tls_open_falls_back_to_legacy_stack() {
        use crate::checks::legacy_tls::test_server::{spawn, Mode};
        let port = spawn(Mode::RsaKex).await;
        let mut c = Conn::open("127.0.0.1", port, true, 5, false).await.unwrap();
        assert!(c.local_port() > 0);
        c.send(b"PING\n").await.unwrap();
        let reply = c.read_reply(first_byte_wait(5)).await;
        assert_eq!(to_text(&reply), "PONG-LEGACY");
    }

    #[tokio::test]
    async fn multi_round_trip_computed_frame() {
        let addr = challenge_server().await;
        let mut c = Conn::open(&addr.ip().to_string(), addr.port(), false, 5, false)
            .await
            .unwrap();

        // banner
        let banner = c.read_reply(first_byte_wait(5)).await;
        assert_eq!(to_text(&banner), "HELLO");

        // frame 1 → challenge
        c.send(&[0xaa]).await.unwrap();
        let reply = c.read_reply(first_byte_wait(5)).await;
        let hex = to_hex(&reply);
        assert_eq!(hex, "0001020304");
        // parse the big-endian u32 challenge at byte offset 1 (hex offset 2)
        assert_eq!(&hex[2..], "01020304");

        // frame 2 → built from the "computed" digest bytes
        c.send(&[0xde, 0xad, 0xbe, 0xef]).await.unwrap();
        let result = c.read_reply(first_byte_wait(5)).await;
        assert_eq!(to_text(&result), "accepted");
    }

    /// Replies to the first frame only after `delay_ms` (#1336 / #1417).
    async fn slow_server(delay_ms: u64) -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((mut sock, _)) = listener.accept().await {
                let mut buf = [0u8; 64];
                if let Ok(n) = sock.read(&mut buf).await {
                    if n > 0 {
                        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                        let _ = sock.write_all(b"late").await;
                        // a pause shorter than the idle gap keeps the reply in one piece
                        tokio::time::sleep(Duration::from_millis(100)).await;
                        let _ = sock.write_all(b" reply").await;
                    }
                }
                // keep the socket open past the reads
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        });
        addr
    }

    #[tokio::test]
    async fn first_byte_waits_up_to_timeout_secs() {
        let addr = slow_server(1200).await;
        let mut c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        c.send(b"go").await.unwrap();
        let reply = c.read_reply(first_byte_wait(3)).await;
        assert_eq!(to_text(&reply), "late reply");
    }

    #[tokio::test]
    async fn first_byte_wait_is_bounded() {
        let addr = slow_server(3000).await;
        let mut c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        c.send(b"go").await.unwrap();
        let start = std::time::Instant::now();
        let reply = c.read_reply(first_byte_wait(1)).await;
        assert!(reply.is_empty());
        let took = start.elapsed();
        assert!(took >= Duration::from_millis(950) && took < Duration::from_millis(2500));
    }

    #[test]
    fn first_byte_wait_never_below_idle_gap() {
        assert_eq!(first_byte_wait(0), Duration::from_millis(READ_IDLE_MS));
        assert_eq!(first_byte_wait(10), Duration::from_secs(10));
        assert_eq!(first_byte_wait(u64::MAX), Duration::from_millis(u64::MAX));
    }

    #[tokio::test]
    async fn open_failure_is_an_error() {
        // Nothing listening on this port → connect error.
        let err = Conn::open("127.0.0.1", 1, false, 2, false).await;
        assert!(err.is_err());
    }

    #[tokio::test]
    async fn reserved_source_port_or_ephemeral_fallback() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (_sock, peer) = listener.accept().await.unwrap();
            peer.port()
        });
        let c = Conn::open("127.0.0.1", addr.port(), false, 5, true)
            .await
            .unwrap();
        let local = c.local_port();
        assert_eq!(server.await.unwrap(), local);
        // Root / CAP_NET_BIND_SERVICE gets a reserved port; otherwise the
        // connection still succeeds from an ephemeral one.
        assert!(local != 0);
        if local < 1024 {
            assert!(RESERVED_PORT_RANGE.contains(&local));
        }
    }

    #[tokio::test]
    async fn plain_open_uses_ephemeral_port() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        assert!(c.local_port() >= 1024);
    }

    #[tokio::test]
    async fn starttls_upgrades_the_open_socket() {
        let addr = starttls_test_server::spawn().await;
        let mut c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        assert_eq!(
            to_text(&c.read_reply(first_byte_wait(5)).await),
            "220 ready"
        );
        c.send(b"STARTTLS\r\n").await.unwrap();
        assert_eq!(
            to_text(&c.read_reply(first_byte_wait(5)).await),
            "220 go ahead"
        );

        let Ok((mut c, info)) = c.starttls("127.0.0.1", 5).await else {
            panic!("STARTTLS handshake failed");
        };
        assert!(info.upgraded);
        assert!(matches!(c, Conn::Tls(_)));
        assert!(info
            .protocol_version
            .as_deref()
            .unwrap()
            .starts_with("TLSv1_"));
        assert!(info.cipher_suite.is_some());
        assert!(info
            .cert_subject
            .as_deref()
            .unwrap()
            .contains("noctis-starttls-test"));
        assert_eq!(info.cert_sans, vec!["starttls.test".to_string()]);

        // the same connection now carries TLS records
        c.send(b"PING").await.unwrap();
        assert_eq!(to_text(&c.read_reply(first_byte_wait(5)).await), "PONG-TLS");

        // a second upgrade is refused and the TLS socket is handed back intact
        match c.starttls("127.0.0.1", 5).await {
            Err((Some(Conn::Tls(_)), _)) => {}
            _ => panic!("already-TLS socket must be returned unchanged"),
        }
    }

    #[tokio::test]
    async fn starttls_on_a_non_tls_peer_fails() {
        // The peer answers the ClientHello with cleartext and closes.
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((mut sock, _)) = listener.accept().await {
                let mut buf = [0u8; 1024];
                let _ = sock.read(&mut buf).await;
                let _ = sock.write_all(b"500 what?\r\n").await;
            }
        });
        let c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        match c.starttls("127.0.0.1", 5).await {
            Err((None, e)) => assert!(e.to_string().contains("TLS handshake")),
            _ => panic!("handshake against a cleartext peer must fail"),
        }
    }

    #[tokio::test]
    async fn starttls_handshake_is_bounded_by_timeout() {
        // The peer accepts and never answers the ClientHello.
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((_sock, _)) = listener.accept().await {
                tokio::time::sleep(Duration::from_secs(10)).await;
            }
        });
        let c = Conn::open("127.0.0.1", addr.port(), false, 5, false)
            .await
            .unwrap();
        let start = std::time::Instant::now();
        let res = c.starttls("127.0.0.1", 1).await;
        assert!(matches!(res, Err((None, _))));
        assert!(start.elapsed() < Duration::from_secs(3));
    }
}