noctis 0.5.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
//! 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 three actions (`tcp_open`,
//! `tcp_send`, `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 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).
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<TlsStream<TcpStream>>),
}

/// 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,
}

#[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()
}

/// Read until no bytes arrive for `READ_IDLE_MS`, EOF, or the byte cap.
async fn read_reply<S: AsyncReadExt + Unpin>(stream: &mut S) -> Vec<u8> {
    let mut acc = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        match timeout(Duration::from_millis(READ_IDLE_MS), 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,     // idle timeout → 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)
}

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 {
            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 stream = connector
                .connect(server_name, tcp)
                .await
                .map_err(|e| NoctisError::Tcp(format!("TLS handshake {addr}: {e}")))?;
            Ok(Conn::Tls(Box::new(stream)))
        } else {
            Ok(Conn::Plain(tcp))
        }
    }

    /// 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.get_ref().0,
        };
        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 (bounded by the idle gap / byte cap).
    pub async fn read_reply(&mut self) -> Vec<u8> {
        match self {
            Conn::Plain(s) => read_reply(s).await,
            Conn::Tls(s) => read_reply(s).await,
        }
    }
}

#[cfg(test)]
mod tests {
    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
    }

    #[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().await;
        assert_eq!(to_text(&banner), "HELLO");

        // frame 1 → challenge
        c.send(&[0xaa]).await.unwrap();
        let reply = c.read_reply().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().await;
        assert_eq!(to_text(&result), "accepted");
    }

    #[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);
    }
}