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.
//! Minimal LDAPv3 responder for JNDI (`${jndi:ldap://host:port/<token>}`) callbacks.
//!
//! A real JNDI lookup opens an LDAP connection, sends an anonymous
//! `BindRequest`, and sends the `SearchRequest` that carries the DN (where the
//! token sits) only after a successful `BindResponse`. This module answers the
//! bind with success, reads the search base DN, answers every search with an
//! empty `SearchResultDone` (no entry, no referral: nothing is loaded and the
//! lookup ends) and hands the DN back to the caller, which records it as an
//! OOB callback.
//!
//! Only the BER subset LDAP clients actually send is parsed: definite lengths
//! (short and long form, at most 4 length bytes) and messages up to
//! [`MAX_MESSAGE`] bytes.

use std::time::Duration;

use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

/// Largest LDAP message accepted (a JNDI bind/search is well under 1 KiB).
pub const MAX_MESSAGE: usize = 64 * 1024;
/// Messages read on one connection before giving up.
const MAX_MESSAGES: usize = 8;
/// Idle time allowed between two client messages.
const READ_TIMEOUT: Duration = Duration::from_secs(10);

const TAG_SEQUENCE: u8 = 0x30;
const TAG_INTEGER: u8 = 0x02;
const TAG_OCTET_STRING: u8 = 0x04;
const TAG_ENUMERATED: u8 = 0x0a;
const OP_BIND_REQUEST: u8 = 0x60;
const OP_BIND_RESPONSE: u8 = 0x61;
const OP_UNBIND_REQUEST: u8 = 0x42;
const OP_SEARCH_REQUEST: u8 = 0x63;
const OP_SEARCH_RESULT_DONE: u8 = 0x65;

/// One decoded LDAP request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LdapRequest {
    Bind {
        message_id: Vec<u8>,
    },
    Search {
        message_id: Vec<u8>,
        base_dn: String,
    },
    Unbind,
    /// Any other operation (abandon, extended…): answered with nothing.
    Other {
        message_id: Vec<u8>,
        op: u8,
    },
}

/// Read one BER TLV header from `buf`: (tag, content length, header length).
fn read_header(buf: &[u8]) -> Option<(u8, usize, usize)> {
    let tag = *buf.first()?;
    let first = *buf.get(1)? as usize;
    if first < 0x80 {
        return Some((tag, first, 2));
    }
    let n = first & 0x7f;
    if n == 0 || n > 4 {
        return None; // indefinite form or absurd length
    }
    let mut len = 0usize;
    for i in 0..n {
        len = (len << 8) | *buf.get(2 + i)? as usize;
    }
    Some((tag, len, 2 + n))
}

/// Split one TLV off the front of `buf`: (tag, content, rest).
fn take_tlv(buf: &[u8]) -> Option<(u8, &[u8], &[u8])> {
    let (tag, len, hdr) = read_header(buf)?;
    let end = hdr.checked_add(len)?;
    if buf.len() < end {
        return None;
    }
    Some((tag, &buf[hdr..end], &buf[end..]))
}

/// Decode one complete `LDAPMessage` (the outer SEQUENCE included).
pub fn parse_message(msg: &[u8]) -> Option<LdapRequest> {
    let (tag, body, _) = take_tlv(msg)?;
    if tag != TAG_SEQUENCE {
        return None;
    }
    let (id_tag, message_id, rest) = take_tlv(body)?;
    if id_tag != TAG_INTEGER || message_id.is_empty() {
        return None;
    }
    let message_id = message_id.to_vec();
    let op = *rest.first()?;
    match op {
        OP_BIND_REQUEST => Some(LdapRequest::Bind { message_id }),
        OP_UNBIND_REQUEST => Some(LdapRequest::Unbind),
        OP_SEARCH_REQUEST => {
            let (_, search, _) = take_tlv(rest)?;
            let (dn_tag, dn, _) = take_tlv(search)?;
            if dn_tag != TAG_OCTET_STRING {
                return None;
            }
            Some(LdapRequest::Search {
                message_id,
                base_dn: String::from_utf8_lossy(dn).into_owned(),
            })
        }
        _ => Some(LdapRequest::Other { message_id, op }),
    }
}

/// Encode a BER length.
fn encode_len(len: usize, out: &mut Vec<u8>) {
    if len < 0x80 {
        out.push(len as u8);
    } else {
        let bytes = (len as u32).to_be_bytes();
        let skip = bytes.iter().take_while(|b| **b == 0).count();
        out.push(0x80 | (4 - skip) as u8);
        out.extend_from_slice(&bytes[skip..]);
    }
}

fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
    let mut out = vec![tag];
    encode_len(content.len(), &mut out);
    out.extend_from_slice(content);
    out
}

/// `LDAPMessage { messageID, <op> LDAPResult { success, "", "" } }`.
fn success_result(message_id: &[u8], op: u8) -> Vec<u8> {
    let mut result = tlv(TAG_ENUMERATED, &[0x00]); // resultCode success
    result.extend(tlv(TAG_OCTET_STRING, b"")); // matchedDN
    result.extend(tlv(TAG_OCTET_STRING, b"")); // diagnosticMessage
    let mut body = tlv(TAG_INTEGER, message_id);
    body.extend(tlv(op, &result));
    tlv(TAG_SEQUENCE, &body)
}

pub fn bind_response(message_id: &[u8]) -> Vec<u8> {
    success_result(message_id, OP_BIND_RESPONSE)
}

pub fn search_result_done(message_id: &[u8]) -> Vec<u8> {
    success_result(message_id, OP_SEARCH_RESULT_DONE)
}

/// Read one complete LDAP message from `io`, `None` on EOF, timeout or garbage.
async fn read_message<S: AsyncRead + Unpin>(io: &mut S) -> Option<Vec<u8>> {
    let mut buf = vec![0u8; 2];
    tokio::time::timeout(READ_TIMEOUT, io.read_exact(&mut buf))
        .await
        .ok()?
        .ok()?;
    if buf[0] != TAG_SEQUENCE {
        return None;
    }
    let extra = if buf[1] >= 0x80 {
        (buf[1] & 0x7f) as usize
    } else {
        0
    };
    if extra > 4 {
        return None;
    }
    if extra > 0 {
        let mut len_bytes = vec![0u8; extra];
        tokio::time::timeout(READ_TIMEOUT, io.read_exact(&mut len_bytes))
            .await
            .ok()?
            .ok()?;
        buf.extend_from_slice(&len_bytes);
    }
    let (_, len, hdr) = read_header(&buf)?;
    if len > MAX_MESSAGE {
        return None;
    }
    let mut content = vec![0u8; len];
    tokio::time::timeout(READ_TIMEOUT, io.read_exact(&mut content))
        .await
        .ok()?
        .ok()?;
    debug_assert_eq!(buf.len(), hdr);
    buf.extend_from_slice(&content);
    Some(buf)
}

/// Serve one LDAP connection. Every search base DN is passed to `on_search`.
pub async fn serve_connection<S, F>(mut io: S, mut on_search: F)
where
    S: AsyncRead + AsyncWrite + Unpin,
    F: FnMut(String),
{
    for _ in 0..MAX_MESSAGES {
        let Some(msg) = read_message(&mut io).await else {
            return;
        };
        let reply = match parse_message(&msg) {
            Some(LdapRequest::Bind { message_id }) => bind_response(&message_id),
            Some(LdapRequest::Search {
                message_id,
                base_dn,
            }) => {
                on_search(base_dn);
                search_result_done(&message_id)
            }
            Some(LdapRequest::Unbind) | None => return,
            Some(LdapRequest::Other { op, .. }) => {
                tracing::debug!(op = format!("{op:#04x}"), "OOB LDAP: unsupported operation");
                continue;
            }
        };
        if io.write_all(&reply).await.is_err() {
            return;
        }
        let _ = io.flush().await;
    }
}

/// The OOB token carried by a search base DN.
///
/// JNDI sends the URL path as the DN, so `ldap://h:p/<token>` gives `<token>`.
/// A DN such as `<token>,dc=x` or a path such as `<token>/a` keeps its first
/// component; a leading `/` is ignored.
pub fn token_from_dn(dn: &str) -> String {
    let dn = dn.trim().trim_start_matches('/');
    let end = dn.find([',', '/', '?']).unwrap_or(dn.len());
    let first = &dn[..end];
    // `cn=<token>` style: keep the value
    match first.split_once('=') {
        Some((_, v)) => v.to_string(),
        None => first.to_string(),
    }
}

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

    /// Real anonymous BindRequest sent by Log4j 2.14.1 (vulhub solr:8.11.0).
    const LOG4J_BIND: &str = "300c020101600702010304008000";

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

    /// SearchRequest for base `dn`, shaped like the JDK LDAP client's.
    fn search_request(id: u8, dn: &str) -> Vec<u8> {
        let mut search = tlv(TAG_OCTET_STRING, dn.as_bytes());
        search.extend(tlv(TAG_ENUMERATED, &[0x00])); // scope baseObject
        search.extend(tlv(TAG_ENUMERATED, &[0x03])); // derefAliases always
        search.extend(tlv(TAG_INTEGER, &[0x00])); // sizeLimit
        search.extend(tlv(TAG_INTEGER, &[0x00])); // timeLimit
        search.extend(tlv(0x01, &[0x00])); // typesOnly false
        search.extend(tlv(0x87, b"objectClass")); // present filter
        search.extend(tlv(TAG_SEQUENCE, b"")); // attributes
        let mut body = tlv(TAG_INTEGER, &[id]);
        body.extend(tlv(OP_SEARCH_REQUEST, &search));
        // JDK appends controls (ManageDsaIT) — must be ignored
        body.extend(tlv(
            0xa0,
            &tlv(
                TAG_SEQUENCE,
                &tlv(TAG_OCTET_STRING, b"2.16.840.1.113730.3.4.2"),
            ),
        ));
        tlv(TAG_SEQUENCE, &body)
    }

    #[test]
    fn parses_real_log4j_bind() {
        assert_eq!(
            parse_message(&hex(LOG4J_BIND)),
            Some(LdapRequest::Bind {
                message_id: vec![1]
            })
        );
    }

    #[test]
    fn bind_response_matches_reference_bytes() {
        assert_eq!(bind_response(&[1]), hex("300c02010161070a010004000400"));
    }

    #[test]
    fn parses_search_base_dn() {
        let msg = search_request(2, "4f7c2a1e-token");
        assert_eq!(
            parse_message(&msg),
            Some(LdapRequest::Search {
                message_id: vec![2],
                base_dn: "4f7c2a1e-token".into()
            })
        );
    }

    #[test]
    fn long_form_lengths_round_trip() {
        let dn = "x".repeat(300);
        let msg = search_request(7, &dn);
        assert_eq!(msg[1], 0x82, "outer length must use the long form");
        match parse_message(&msg) {
            Some(LdapRequest::Search { base_dn, .. }) => assert_eq!(base_dn, dn),
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn rejects_truncated_and_non_ldap() {
        let msg = search_request(2, "tok");
        assert_eq!(parse_message(&msg[..msg.len() - 5]), None);
        assert_eq!(parse_message(b"GET / HTTP/1.1\r\n\r\n"), None);
        assert_eq!(parse_message(&hex("3084ffffffff")), None);
    }

    #[test]
    fn token_from_dn_forms() {
        assert_eq!(token_from_dn("abc-123"), "abc-123");
        assert_eq!(token_from_dn("/abc-123"), "abc-123");
        assert_eq!(token_from_dn("abc-123/a"), "abc-123");
        assert_eq!(token_from_dn("cn=abc-123,dc=example"), "abc-123");
        assert_eq!(token_from_dn("abc-123,dc=x"), "abc-123");
    }

    #[tokio::test]
    async fn full_jndi_exchange() {
        let (mut client, server) = tokio::io::duplex(4096);
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen2 = seen.clone();
        let task = tokio::spawn(async move {
            serve_connection(server, move |dn| seen2.lock().unwrap().push(dn)).await;
        });

        client.write_all(&hex(LOG4J_BIND)).await.unwrap();
        let mut reply = vec![0u8; 14];
        client.read_exact(&mut reply).await.unwrap();
        assert_eq!(reply, hex("300c02010161070a010004000400"));

        client
            .write_all(&search_request(2, "tok-42"))
            .await
            .unwrap();
        let mut done = vec![0u8; 14];
        client.read_exact(&mut done).await.unwrap();
        assert_eq!(done, hex("300c02010265070a010004000400"));

        client.write_all(&hex("30050201034200")).await.unwrap(); // unbind
        task.await.unwrap();
        assert_eq!(*seen.lock().unwrap(), vec!["tok-42".to_string()]);
    }
}