ms-rodc 0.1.0

Read-Only Domain Controller (RODC) audit primitives for Active Directory: RODC discovery, per-RODC krbtgt account (krbtgt_NNNNN) naming, msDS-RevealedList / msDS-NeverRevealGroup / msDS-RevealedUsers exposure audit, and RODC-scoped TGT shape checks.
Documentation
//! **ms-rodc** — Read-Only Domain Controller audit primitives.
//!
//! # Why RODCs need their own audit surface
//!
//! An RODC has:
//! * Its own **per-RODC krbtgt account** (`krbtgt_NNNNN`) with its own key.
//!   A ticket forged with the *domain* krbtgt won't validate at an RODC and
//!   vice-versa, but forging a TGT with a per-RODC krbtgt key is often
//!   sufficient to authenticate to services that trust the RODC.
//! * A **Password Replication Policy** (PRP) — the set of accounts whose
//!   secrets the RODC is allowed to cache locally. Two attributes drive it:
//!   - `msDS-RevealOnDemandGroup` (allow list)
//!   - `msDS-NeverRevealGroup` (deny list)
//! * A **revealed set** tracking what has actually been cached:
//!   - `msDS-RevealedList` (constructed, per-RODC list of principals whose
//!     secrets are cached)
//!   - `msDS-RevealedUsers` (per-user link to revealing RODCs — inverse)
//!
//! Silver-lining detection: if a Tier-0 account (Domain Admins, DA-shaped
//! service accounts) shows up in an RODC's `msDS-RevealedList`, physical
//! compromise of that RODC hands the attacker a live secret. If the same
//! account is missing from `msDS-NeverRevealGroup`, that hole was policy,
//! not accident.
//!
//! # What this crate does
//!
//! * [`RodcObject`] — normalize an RODC computer object (`primaryGroupID`
//!   reported as 521, `msDS-KrbTgtLink` pointing at its per-RODC krbtgt).
//! * [`per_rodc_krbtgt_dn`] / [`per_rodc_krbtgt_sam`] — build the expected
//!   name of the per-RODC krbtgt account for a given RODC (or recover one
//!   from `krbtgt_NNNNN` shape).
//! * [`RevealAudit`] — cross-reference `msDS-RevealedList` against the tier
//!   classification of the revealed principals; surface Tier-0 leakage.
//! * [`ldap_filter_rodc_computers`], [`ldap_filter_krbtgt_all`], and
//!   friends — ready LDAP filters for enumeration.
//! * [`is_per_rodc_krbtgt_sam`] — cheap sAMAccountName check
//!   (`krbtgt_NNNNN` or `krbtgt_<numeric>`).
//!
//! # What this crate does not do
//!
//! * No LDAP transport (bring your own — `ldap3`, adhammer's raw client).
//! * No ticket forgery for the per-RODC krbtgt key — that path lives in
//!   `ms-pac-forge` (once the caller has extracted the per-RODC krbtgt key
//!   via DCSync or SAMR).
//! * No Kerberos AP-REQ path to distinguish where a ticket was issued — a
//!   separate RODC-scoped Kerberos client is future work.

use core::fmt;

/// Well-known primary-group RID that identifies an RODC computer account.
/// A DC has `primaryGroupID == 516` (Domain Controllers); an RODC has
/// `primaryGroupID == 521` (Read-Only Domain Controllers).
pub const PRIMARY_GROUP_RID_RODC: u32 = 521;

/// Well-known primary-group RID for a writable DC.
pub const PRIMARY_GROUP_RID_DC: u32 = 516;

/// LDAP filter matching every RODC computer object in a domain.
pub fn ldap_filter_rodc_computers() -> &'static str {
    "(&(objectCategory=computer)(primaryGroupID=521))"
}

/// LDAP filter matching every krbtgt account (domain-wide `krbtgt` plus
/// every per-RODC `krbtgt_NNNNN`). Combined with `msDS-KeyVersionNumber`
/// this drives krbtgt-rotation audits.
pub fn ldap_filter_krbtgt_all() -> &'static str {
    "(sAMAccountName=krbtgt*)"
}

/// LDAP filter matching a specific per-RODC krbtgt by its numeric suffix.
pub fn ldap_filter_per_rodc_krbtgt(suffix: u32) -> String {
    format!("(sAMAccountName=krbtgt_{suffix:05})")
}

/// Cheap sAMAccountName-shape check. Returns the numeric suffix if `sam`
/// looks like a per-RODC krbtgt (`krbtgt_NNNNN` — Microsoft always
/// zero-pads the 5-digit form on RODC provisioning, but we accept any
/// numeric tail for tolerance).
pub fn is_per_rodc_krbtgt_sam(sam: &str) -> Option<u32> {
    let rest = sam.strip_prefix("krbtgt_")?;
    if rest.is_empty() {
        return None;
    }
    rest.parse::<u32>().ok()
}

/// Recover a per-RODC krbtgt sAMAccountName from a numeric suffix (matches
/// what `Install-ADDSReadOnlyDomainControllerAccount` writes).
pub fn per_rodc_krbtgt_sam(suffix: u32) -> String {
    format!("krbtgt_{suffix:05}")
}

/// Recover a per-RODC krbtgt full DN under the domain's `CN=Users` container.
/// `domain_dn` should be the full defaultNamingContext (e.g.
/// `DC=corp,DC=local`).
pub fn per_rodc_krbtgt_dn(suffix: u32, domain_dn: &str) -> String {
    format!("CN={},CN=Users,{}", per_rodc_krbtgt_sam(suffix), domain_dn)
}

/// A normalized RODC computer object as consumed from AD.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RodcObject {
    /// DN of the RODC computer object.
    pub dn: String,
    /// `sAMAccountName` (usually ends with `$`).
    pub sam_account_name: String,
    /// DN of the per-RODC krbtgt account, from `msDS-KrbTgtLink`.
    pub krbtgt_link_dn: String,
    /// Optional numeric suffix parsed from the linked krbtgt sAMAccountName.
    pub krbtgt_suffix: Option<u32>,
    /// `msDS-RevealedList` — DNs of principals whose secrets are cached
    /// locally on this RODC (constructed attribute).
    pub revealed: Vec<String>,
    /// `msDS-RevealOnDemandGroup` — allow-list (principals eligible to be
    /// cached).
    pub reveal_on_demand: Vec<String>,
    /// `msDS-NeverRevealGroup` — deny-list (principals whose secrets must
    /// never be cached, regardless of the allow-list).
    pub never_reveal: Vec<String>,
}

impl RodcObject {
    /// Construct from raw attribute strings. `krbtgt_link_dn` is expected to
    /// be a DN whose leaf RDN is `CN=krbtgt_NNNNN`; the numeric suffix is
    /// parsed opportunistically and left as `None` if the shape doesn't
    /// match (e.g. a legacy install with a non-standard rename).
    pub fn from_attrs(
        dn: impl Into<String>,
        sam_account_name: impl Into<String>,
        krbtgt_link_dn: impl Into<String>,
        revealed: Vec<String>,
        reveal_on_demand: Vec<String>,
        never_reveal: Vec<String>,
    ) -> Self {
        let dn = dn.into();
        let sam_account_name = sam_account_name.into();
        let krbtgt_link_dn = krbtgt_link_dn.into();
        let krbtgt_suffix = leaf_cn(&krbtgt_link_dn).and_then(is_per_rodc_krbtgt_sam);
        Self {
            dn,
            sam_account_name,
            krbtgt_link_dn,
            krbtgt_suffix,
            revealed,
            reveal_on_demand,
            never_reveal,
        }
    }
}

/// Extract the CN value from the leaf RDN of a DN. Returns `None` if the
/// DN is empty or its leaf isn't a CN.
fn leaf_cn(dn: &str) -> Option<&str> {
    let rdn = dn.split(',').next()?.trim();
    rdn.strip_prefix("CN=").or_else(|| rdn.strip_prefix("cn="))
}

/// A single audit finding produced by [`RevealAudit`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RevealFinding {
    /// DN of the affected RODC.
    pub rodc_dn: String,
    /// DN of the principal whose secret is cached at the RODC.
    pub principal_dn: String,
    /// Whether the principal is Tier-0 (as classified by the caller).
    pub tier: RevealTier,
}

/// Classification the caller applies to a principal to decide the severity
/// of its presence on an RODC.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RevealTier {
    /// Domain Admin, Enterprise Admin, Schema Admin, KRBTGT — full-domain
    /// compromise if the RODC key falls.
    Tier0,
    /// Server administrators, service accounts with local admin on Tier-1
    /// hosts.
    Tier1,
    /// End-user workstations and their users.
    Tier2,
    /// Unclassified — the caller didn't provide a classification.
    Unknown,
}

impl fmt::Display for RevealTier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RevealTier::Tier0 => f.write_str("tier-0"),
            RevealTier::Tier1 => f.write_str("tier-1"),
            RevealTier::Tier2 => f.write_str("tier-2"),
            RevealTier::Unknown => f.write_str("unknown-tier"),
        }
    }
}

/// Auditor: given a set of RODC objects and a per-principal tier lookup,
/// return every `(rodc, principal)` pair whose presence in the RODC's
/// `msDS-RevealedList` warrants attention.
///
/// A finding is produced when:
/// * The principal is classified `Tier0` — always.
/// * The principal is *any* tier AND appears in the RODC's
///   `msDS-RevealedList` but is missing from `msDS-NeverRevealGroup` when
///   it *should* have been denied by the caller's policy. This case is
///   surfaced with `Unknown` if the caller couldn't classify — the caller
///   decides whether that matters.
///
/// The tier lookup is a closure so callers can back it with whatever they
/// already have (BloodHound classification, adhammer graph, static list).
pub struct RevealAudit<'a, F: Fn(&str) -> RevealTier> {
    pub rodcs: &'a [RodcObject],
    pub classify: F,
}

impl<'a, F: Fn(&str) -> RevealTier> RevealAudit<'a, F> {
    pub fn run(&self) -> Vec<RevealFinding> {
        let mut out = Vec::new();
        for rodc in self.rodcs {
            for principal in &rodc.revealed {
                let tier = (self.classify)(principal);
                if matches!(tier, RevealTier::Tier0) {
                    out.push(RevealFinding {
                        rodc_dn: rodc.dn.clone(),
                        principal_dn: principal.clone(),
                        tier,
                    });
                }
            }
        }
        out
    }
}

/// Attributes commonly requested when auditing an RODC.
pub const RODC_AUDIT_ATTRS: &[&str] = &[
    "sAMAccountName",
    "distinguishedName",
    "primaryGroupID",
    "msDS-KrbTgtLink",
    "msDS-RevealedList",
    "msDS-RevealOnDemandGroup",
    "msDS-NeverRevealGroup",
    "msDS-RevealedUsers",
];

/// Attributes commonly requested when auditing a krbtgt account (either
/// domain-wide or per-RODC).
pub const KRBTGT_AUDIT_ATTRS: &[&str] = &[
    "sAMAccountName",
    "distinguishedName",
    "msDS-KeyVersionNumber",
    "pwdLastSet",
    "msDS-RevealedListBL",
];

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

    #[test]
    fn per_rodc_krbtgt_naming_roundtrip() {
        let sam = per_rodc_krbtgt_sam(23179);
        assert_eq!(sam, "krbtgt_23179");
        assert_eq!(is_per_rodc_krbtgt_sam(&sam), Some(23179));

        let dn = per_rodc_krbtgt_dn(23179, "DC=corp,DC=local");
        assert_eq!(dn, "CN=krbtgt_23179,CN=Users,DC=corp,DC=local");
    }

    #[test]
    fn per_rodc_krbtgt_shape_rejects_non_rodc_krbtgt() {
        assert_eq!(is_per_rodc_krbtgt_sam("krbtgt"), None);
        assert_eq!(is_per_rodc_krbtgt_sam("krbtgt_"), None);
        assert_eq!(is_per_rodc_krbtgt_sam("krbtgt_notnumeric"), None);
        assert_eq!(is_per_rodc_krbtgt_sam("something-else"), None);
    }

    #[test]
    fn per_rodc_krbtgt_short_suffix_still_matches() {
        // Some legacy installs use unpadded numeric suffixes; our detector
        // should tolerate them even if we don't emit them.
        assert_eq!(is_per_rodc_krbtgt_sam("krbtgt_1"), Some(1));
        assert_eq!(is_per_rodc_krbtgt_sam("krbtgt_00042"), Some(42));
    }

    #[test]
    fn rodc_object_parses_krbtgt_suffix() {
        let rodc = RodcObject::from_attrs(
            "CN=RODC01,OU=Domain Controllers,DC=corp,DC=local",
            "RODC01$",
            "CN=krbtgt_54321,CN=Users,DC=corp,DC=local",
            vec!["CN=alice,CN=Users,DC=corp,DC=local".into()],
            vec![],
            vec![],
        );
        assert_eq!(rodc.krbtgt_suffix, Some(54321));
        assert_eq!(rodc.revealed.len(), 1);
    }

    #[test]
    fn reveal_audit_flags_tier0_leakage() {
        let rodc = RodcObject::from_attrs(
            "CN=RODC01,OU=Domain Controllers,DC=corp,DC=local",
            "RODC01$",
            "CN=krbtgt_54321,CN=Users,DC=corp,DC=local",
            vec![
                "CN=alice,CN=Users,DC=corp,DC=local".into(),
                "CN=Administrator,CN=Users,DC=corp,DC=local".into(),
                "CN=svc-web,OU=Services,DC=corp,DC=local".into(),
            ],
            vec![],
            vec![],
        );
        let rodcs = vec![rodc];

        let audit = RevealAudit {
            rodcs: &rodcs,
            classify: |dn: &str| {
                if dn.contains("Administrator") {
                    RevealTier::Tier0
                } else if dn.contains("svc-web") {
                    RevealTier::Tier1
                } else {
                    RevealTier::Tier2
                }
            },
        };
        let findings = audit.run();
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].tier, RevealTier::Tier0);
        assert!(findings[0].principal_dn.contains("Administrator"));
    }

    #[test]
    fn ldap_filters_shape() {
        assert!(ldap_filter_rodc_computers().contains("primaryGroupID=521"));
        assert!(ldap_filter_krbtgt_all().contains("krbtgt"));
        let f = ldap_filter_per_rodc_krbtgt(12);
        assert_eq!(f, "(sAMAccountName=krbtgt_00012)");
    }

    #[test]
    fn well_known_rids() {
        assert_eq!(PRIMARY_GROUP_RID_RODC, 521);
        assert_eq!(PRIMARY_GROUP_RID_DC, 516);
    }
}