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.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;

use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::any;
use axum::Router;
use serde_json::Value;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{mpsc, Mutex, Notify};

pub mod ldap;

/// How long a new connection may stay silent before it is handed to HTTP.
const SNIFF_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// OOB callback server: HTTP and LDAP on the same port.
///
/// When a target calls back to `http://<host>:<port>/<token>`, the server
/// stores the request details and notifies any waiter on that token.
///
/// A connection whose first byte is `0x30` (a BER SEQUENCE) is served as LDAP
/// instead — the `${jndi:ldap://<host>:<port>/<token>}` lookups of Log4Shell
/// and other JNDI injections. The bind is accepted, the search base DN carries
/// the token, and the search gets an empty result, so nothing is ever loaded
/// by the target (see [`ldap`]).
pub struct OobServer {
    pub host: String,
    pub port: u16,
    callbacks: Arc<Mutex<HashMap<String, Value>>>,
    notifiers: Arc<Mutex<HashMap<String, Arc<Notify>>>>,
}

impl OobServer {
    pub fn new(host: impl Into<String>, port: u16) -> Arc<Self> {
        Arc::new(Self {
            host: host.into(),
            port,
            callbacks: Arc::new(Mutex::new(HashMap::new())),
            notifiers: Arc::new(Mutex::new(HashMap::new())),
        })
    }

    /// Start listening in the background. Returns immediately.
    ///
    /// The bind happens *before* spawning so errors (port already in use, etc.)
    /// surface here rather than being silently swallowed inside the task.
    pub async fn start(self: Arc<Self>) -> crate::error::Result<()> {
        let addr: SocketAddr = format!("0.0.0.0:{}", self.port)
            .parse()
            .map_err(|e| crate::error::NoctisError::Oob(format!("bad addr: {e}")))?;

        let listener = TcpListener::bind(addr)
            .await
            .map_err(|e| crate::error::NoctisError::Oob(format!("bind {addr}: {e}")))?;

        tracing::info!(addr = %addr, "OOB server listening (HTTP + LDAP)");

        self.serve(listener);
        Ok(())
    }

    /// Serve HTTP + LDAP callbacks on an already bound listener (background task).
    fn serve(self: Arc<Self>, listener: TcpListener) {
        let local_addr = listener.local_addr().ok();
        let (tx, rx) = mpsc::channel::<(TcpStream, SocketAddr)>(64);
        let sniffer = self.clone();
        tokio::spawn(async move {
            loop {
                let (stream, peer) = match listener.accept().await {
                    Ok(c) => c,
                    Err(e) => {
                        tracing::debug!("OOB accept error: {e}");
                        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                        continue;
                    }
                };
                let server = sniffer.clone();
                let tx = tx.clone();
                tokio::spawn(async move {
                    server.dispatch(stream, peer, tx).await;
                });
            }
        });

        let shared = self.clone();
        let app = Router::new()
            .route("/{token}", any(handle_callback))
            .route("/{token}/", any(handle_callback))
            .with_state(shared);

        let http_listener = HttpConnections { rx, local_addr };
        tokio::spawn(async move {
            if let Err(e) = axum::serve(http_listener, app).await {
                tracing::error!("OOB server error: {e}");
            }
        });
    }

    /// Peek at the first byte of a new connection: LDAP is served here, anything
    /// else (or silence) goes to the HTTP server.
    async fn dispatch(
        self: Arc<Self>,
        stream: TcpStream,
        peer: SocketAddr,
        http: mpsc::Sender<(TcpStream, SocketAddr)>,
    ) {
        let mut first = [0u8; 1];
        let peeked = tokio::time::timeout(SNIFF_TIMEOUT, stream.peek(&mut first)).await;
        match peeked {
            Ok(Ok(0)) | Ok(Err(_)) => {} // closed before sending anything
            Ok(Ok(_)) if first[0] == 0x30 => self.serve_ldap(stream, peer).await,
            _ => {
                let _ = http.send((stream, peer)).await;
            }
        }
    }

    async fn serve_ldap(self: Arc<Self>, stream: TcpStream, peer: SocketAddr) {
        // Record each search as soon as it arrives: a JNDI client may keep the
        // connection open (pooling) long after its lookup has ended.
        let server = self.clone();
        ldap::serve_connection(stream, move |dn| {
            let token = ldap::token_from_dn(&dn);
            if token.is_empty() {
                return;
            }
            tracing::info!(token = %token, peer = %peer, "OOB LDAP callback received");
            let payload = serde_json::json!({
                "protocol": "ldap",
                "method": "LDAP SEARCH",
                "remote_addr": peer.to_string(),
                "headers": {},
                "query": {},
                "body": format!("LDAP search base DN: {dn}"),
            });
            let server = server.clone();
            tokio::spawn(async move { server.record(&token, payload).await });
        })
        .await;
    }

    /// Wait asynchronously until a callback for `token` arrives.
    /// Returns the captured request payload, or None on timeout (handled by caller).
    pub async fn wait_for_token(&self, token: &str) -> Option<Value> {
        // Register the notifier and arm its `Notified` future *before* checking
        // the map, so a callback recorded in between cannot be missed.
        let notify = {
            let mut notifiers = self.notifiers.lock().await;
            notifiers
                .entry(token.to_string())
                .or_insert_with(|| Arc::new(Notify::new()))
                .clone()
        };
        loop {
            let notified = notify.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            {
                let map = self.callbacks.lock().await;
                if let Some(v) = map.get(token) {
                    return Some(v.clone());
                }
            }
            notified.await;
        }
    }

    async fn record(&self, token: &str, data: Value) {
        {
            let mut map = self.callbacks.lock().await;
            map.insert(token.to_string(), data);
        }
        let notifiers = self.notifiers.lock().await;
        if let Some(n) = notifiers.get(token) {
            n.notify_waiters();
        }
    }
}

/// Connections the sniffer classified as HTTP, fed to `axum::serve`.
struct HttpConnections {
    rx: mpsc::Receiver<(TcpStream, SocketAddr)>,
    local_addr: Option<SocketAddr>,
}

impl axum::serve::Listener for HttpConnections {
    type Io = TcpStream;
    type Addr = SocketAddr;

    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
        match self.rx.recv().await {
            Some(conn) => conn,
            // The accept loop never ends while the server lives; park forever.
            None => std::future::pending().await,
        }
    }

    fn local_addr(&self) -> std::io::Result<Self::Addr> {
        self.local_addr
            .ok_or_else(|| std::io::Error::other("OOB listener has no local address"))
    }
}

// ── Axum handler ──────────────────────────────────────────────────────────

async fn handle_callback(
    Path(token): Path<String>,
    Query(params): Query<HashMap<String, String>>,
    State(server): State<Arc<OobServer>>,
    method: axum::http::Method,
    headers: axum::http::HeaderMap,
    body: axum::body::Bytes,
) -> StatusCode {
    tracing::info!(token = %token, "OOB callback received");

    let header_map: HashMap<String, String> = headers
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    let payload = serde_json::json!({
        "protocol": "http",
        "method": method.to_string(),
        "headers": header_map,
        "query": params,
        "body": String::from_utf8_lossy(&body).to_string(),
    });

    server.record(&token, payload).await;
    StatusCode::OK
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    async fn start_local() -> (Arc<OobServer>, SocketAddr) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let srv = OobServer::new("127.0.0.1", addr.port());
        srv.clone().serve(listener);
        (srv, addr)
    }

    fn unhex(s: &str) -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }

    async fn wait(srv: &OobServer, token: &str) -> Option<Value> {
        tokio::time::timeout(std::time::Duration::from_secs(5), srv.wait_for_token(token))
            .await
            .ok()
            .flatten()
    }

    #[tokio::test]
    async fn ldap_jndi_lookup_records_token() {
        let (srv, addr) = start_local().await;
        let mut c = TcpStream::connect(addr).await.unwrap();
        // Real Log4j anonymous bind
        c.write_all(&unhex("300c020101600702010304008000"))
            .await
            .unwrap();
        let mut reply = [0u8; 14];
        c.read_exact(&mut reply).await.unwrap();
        assert_eq!(reply[5], 0x61, "BindResponse expected");
        assert_eq!(reply[9], 0x00, "bind must succeed");

        // SearchRequest, base DN = token
        let dn = b"ldap-tok-1";
        let mut search = vec![0x04, dn.len() as u8];
        search.extend_from_slice(dn);
        search.extend_from_slice(&unhex(
            "0a01000a0103020100020100010100870b6f626a656374436c6173733000",
        ));
        let mut body = vec![0x02, 0x01, 0x02, 0x63, search.len() as u8];
        body.extend_from_slice(&search);
        let mut msg = vec![0x30, body.len() as u8];
        msg.extend_from_slice(&body);
        c.write_all(&msg).await.unwrap();
        let mut done = [0u8; 14];
        c.read_exact(&mut done).await.unwrap();
        assert_eq!(done[5], 0x65, "SearchResultDone expected");

        let got = wait(&srv, "ldap-tok-1")
            .await
            .expect("LDAP callback recorded");
        assert_eq!(got["protocol"], "ldap");
        assert!(got["body"].as_str().unwrap().contains("ldap-tok-1"));
    }

    #[tokio::test]
    async fn http_callback_still_works_on_same_port() {
        let (srv, addr) = start_local().await;
        let mut c = TcpStream::connect(addr).await.unwrap();
        c.write_all(b"GET /http-tok-1?x=1 HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n")
            .await
            .unwrap();
        let mut resp = Vec::new();
        c.read_to_end(&mut resp).await.unwrap();
        assert!(resp.starts_with(b"HTTP/1.1 200"));
        let got = wait(&srv, "http-tok-1")
            .await
            .expect("HTTP callback recorded");
        assert_eq!(got["protocol"], "http");
        assert_eq!(got["query"]["x"], "1");
    }

    #[tokio::test]
    async fn garbage_ldap_records_nothing_and_does_not_block_http() {
        let (srv, addr) = start_local().await;
        let mut junk = TcpStream::connect(addr).await.unwrap();
        junk.write_all(&[0x30, 0x84, 0xff, 0xff, 0xff, 0xff])
            .await
            .unwrap();
        // A silent connection must not stall the others either
        let _silent = TcpStream::connect(addr).await.unwrap();
        let mut c = TcpStream::connect(addr).await.unwrap();
        c.write_all(b"GET /http-tok-2 HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n")
            .await
            .unwrap();
        let mut resp = Vec::new();
        c.read_to_end(&mut resp).await.unwrap();
        assert!(resp.starts_with(b"HTTP/1.1 200"));
        assert!(wait(&srv, "http-tok-2").await.is_some());
        let mut buf = [0u8; 1];
        let n = tokio::time::timeout(std::time::Duration::from_secs(5), junk.read(&mut buf))
            .await
            .unwrap()
            .unwrap_or(0);
        assert_eq!(n, 0, "garbage LDAP connection must be closed");
    }
}