msldap-ext 0.1.0-dev

Encoder/decoder for MS-ADTS LDAP extension controls (Paged Results, ExtendedDN, SDFlags, ShowDeleted, DirSync, VLV). Pure BER — no transport.
Documentation
//! ExtendedDN control — 1.2.840.113556.1.4.529 (MS-ADTS §3.1.1.3.4.1.5).
//!
//! Request value:
//! ```asn1
//! ExtendedDnRequestValue ::= SEQUENCE { flag INTEGER }  -- 0=hex, 1=std string
//! ```
//! Response side: each DN attribute is returned as `<GUID=...>;<SID=...>;<DN>`
//! (SID absent for non-security-principal objects). We parse both forms.

use crate::ber;
use crate::Error;
use uuid::Uuid;

pub const OID: &str = "1.2.840.113556.1.4.529";

/// Format the server picks for GUIDs/SIDs in the response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtendedDnFormat {
    /// Raw hex — the default (flag = 0).
    Hex = 0,
    /// GUID as {8-4-4-4-12}, SID as S-1-…-… string form (flag = 1).
    Standard = 1,
}

#[derive(Debug, Clone)]
pub struct ExtendedDnRequest {
    pub format: ExtendedDnFormat,
}

impl ExtendedDnRequest {
    pub fn new(format: ExtendedDnFormat) -> Self {
        Self { format }
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut body = Vec::with_capacity(6);
        ber::write_u32(&mut body, self.format as u32);
        ber::wrap_sequence(&body)
    }
}

/// A DN string decorated by the server after an ExtendedDN request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtendedDn {
    pub guid: Uuid,
    /// Present for security principals only. Raw bytes: for `Hex` format the
    /// server sends a hex blob we decode; for `Standard` format we store the
    /// SID string ("S-1-5-…") as UTF-8 bytes so callers can round-trip either
    /// format without lossy conversion.
    pub sid: Option<Vec<u8>>,
    pub dn: String,
}

impl ExtendedDn {
    /// Parse "<GUID=…>;[<SID=…>;]DN". Accepts both hex and standard GUID forms.
    pub fn parse(s: &str) -> Result<Self, Error> {
        let rest = s
            .strip_prefix("<GUID=")
            .ok_or(Error::Malformed("missing <GUID= prefix"))?;
        let (guid_str, rest) = rest
            .split_once(">;")
            .ok_or(Error::Malformed("unterminated GUID segment"))?;
        let guid = parse_guid(guid_str)?;

        let (sid, dn) = if let Some(after_sid_tag) = rest.strip_prefix("<SID=") {
            let (sid_str, dn) = after_sid_tag
                .split_once(">;")
                .ok_or(Error::Malformed("unterminated SID segment"))?;
            (Some(parse_sid(sid_str)?), dn.to_string())
        } else {
            (None, rest.to_string())
        };

        Ok(Self { guid, sid, dn })
    }
}

fn parse_guid(s: &str) -> Result<Uuid, Error> {
    // Standard form contains hyphens; hex form is 32 contiguous hex chars in
    // little-endian on-wire order. Uuid::parse_str handles the standard form;
    // for hex form we decode the 16 bytes and byte-swap the first three
    // fields per RFC 4122 § the AD-on-wire convention.
    if s.contains('-') {
        return Uuid::parse_str(s).map_err(|_| Error::Malformed("bad GUID"));
    }
    if s.len() != 32 {
        return Err(Error::Malformed("hex GUID must be 32 chars"));
    }
    let mut bytes = [0u8; 16];
    for i in 0..16 {
        bytes[i] = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
            .map_err(|_| Error::Malformed("bad hex in GUID"))?;
    }
    // AD sends the mixed-endian wire form: swap first 4, next 2, next 2.
    bytes[0..4].reverse();
    bytes[4..6].reverse();
    bytes[6..8].reverse();
    Ok(Uuid::from_bytes(bytes))
}

fn parse_sid(s: &str) -> Result<Vec<u8>, Error> {
    // Return the string form as UTF-8 for lossless callback. Full SID→binary
    // decoding is deferred until this crate grows an ms-dtyp companion.
    Ok(s.as_bytes().to_vec())
}