Skip to content
Tech Interview Prep
Technical interview guide

Directory Services (LDAP, Active Directory)

The centralized store of identities, groups, and attributes that most enterprise authentication and authorization builds on.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v6
Editorial status
Reviewed

Scope: LDAP RFC 4511/4513/4514/4515, Kerberos V5 RFC 4120, and current Microsoft AD DS, CISA, and NIST guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-8

Explain a Kerberos application authentication flow.

Answer

The 90-second answer

A Kerberos application login is three exchanges, and the client never holds a service key.

  1. AS exchange. The client sends an AS-REQ to the KDC (UDP/TCP 88) naming its principal, alice@EXAMPLE.COM, plus pre-authentication data: a timestamp encrypted with a key derived from her password (AES string-to-key. PBKDF2, 4096 iterations, RFC 3962; RFC 8009 adds the SHA-2 enctypes at 32768 iterations). The KDC decrypts it to prove she knows the password and returns an AS-REP: a TGT encrypted with the realm's krbtgt/EXAMPLE.COM key, and a session key encrypted with Alice's key. She can hold the TGT but neither read nor forge it.

  2. TGS exchange. For a named service she sends a TGS-REQ carrying the TGT, an authenticator encrypted with the TGT session key, and the target SPN, HTTP/web01.example.com@EXAMPLE.COM. The KDC returns a service ticket encrypted with web01's long-term key, plus a fresh session key encrypted under the TGT session key.

  3. AP exchange. She sends the ticket plus a new authenticator encrypted with the service session key. web01 decrypts the ticket with its keytab, decrypts the authenticator with the session key inside the ticket, checks the timestamp against clock skew, and records it in a replay cache. If mutual auth is required it returns an AP-REP.

Authentication ends there. Authorization, what Alice may do on web01, is the application's decision, usually from a PAC or an LDAP lookup.

Why the pieces exist

The TGT exists because only the KDC knows every service key; it is the only party that can mint a ticket a service will accept. The authenticator exists because the service ticket is a bearer token: a copy is replayable. The authenticator is fresh per request and single-use: the timestamp bounds it and the replay cache rejects a second copy.

Trade-offs

  • Mutual auth: off by default. Turn on AP-REP when the client must not hand credentials to an impostor; costs one round trip.
  • Ticket lifetime: the KDC caps each ticket at min(requested lifetime, remaining TGT lifetime, the service principal's max_life). Active Directory's default domain policy is 10 h for user tickets with 7 d renewal; MIT krb5's kdc.conf defaults are max_life 24 h and max_renewable_life 0 (no renewal). Long lifetimes cut KDC traffic but widen the window a stolen ticket is usable.
  • Delegation: constrained (S4U2Self/S4U2Proxy, msDS-AllowedToDelegateTo) limits a service to named backends. Unconstrained delegation hands the service a forwardable TGT for everything: avoid.

Failure modes

SymptomCauseDetection
KRB_AP_ERR_SKEWclocks differ by more than the 300 s default skewNTP drift on either host
KRB_AP_ERR_REPEATauthenticator seen before: replay cache hit, or a client retrying a cached authenticatoracceptor replay cache
Decrypt failure at the serviceSPN mismatch, duplicate SPN on the wrong account, or stale keytab after rotation (kvno mismatch)service logs; klist -k vs KDC kvno
KDC_ERR_S_PRINCIPAL_UNKNOWNservice principal never registeredKDC log
KDC_ERR_PREAUTH_FAILEDclient's cached key is stale after a password changeKDC log; klist on the client
KRB_AP_ERR_TKT_EXPIREDticket past endtime; client should renew or re-authenticateservice log; klist shows expiry

Message trace (KDC on port 88; UDP for small messages, TCP for large)

  1. AS-REQ → KDC: alice@EXAMPLE.COM, PA-ENC-TIMESTAMP.
  2. AS-REP ← TGT (encrypted with krbtgt/EXAMPLE.COM) + TGT session key (encrypted with Alice's key).
  3. TGS-REQ → KDC: TGT + authenticator (TGT session key) + SPN.
  4. TGS-REP ← service ticket (encrypted with web01's key) + service session key (encrypted with TGT session key).
  5. AP-REQ → web01: ticket + authenticator (service session key).
  6. AP-REP ← web01 (optional): timestamp + subkey (service session key).

Worked check

Alice authenticates at 09:00 and gets a TGT with a 10 h lifetime: it expires at 19:00 and is renewable until 09:00 seven days later. At 09:05 she asks for HTTP/web01.example.com; the KDC sets the service ticket's endtime to the minimum of her requested lifetime, the TGT's remaining life, and web01's max_life. Here 19:00, capped by the TGT. At 09:06 she sends the AP-REQ and web01's clock reads 09:08: a 120 s difference, inside the 300 s skew, so it accepts. Had web01 read 09:20, the 840 s gap exceeds skew and it returns KRB_AP_ERR_SKEW; the fix is NTP, not a larger skew.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Secure LDAP client transport and bind behavior.

Answer

Core answer

Assume a service that binds to a directory (OpenLDAP or AD) with a reusable credential over an untrusted network. My answer: no reusable secret crosses the wire without a validated TLS channel, and the client never falls back to cleartext.

Concretely: use SASL GSSAPI (Kerberos) or SASL EXTERNAL (client certificate) so there is no password to steal. If the directory only offers simple bind, require TLS first, set TLS_REQCERT demand, and treat any StartTLS failure as fatal.

Why TLS must precede the bind

Simple bind sends the DN and password as plaintext LDAP BER. TLS is the only thing protecting them. RFC 4513 covers bind and security mechanisms and expects servers to reject password simple binds over a non-confidential channel, but you cannot rely on the server, so the client enforces it.

StartTLS is an extended operation (OID 1.3.6.1.4.1.1466.20037) sent in the clear. If the client treats a failure as non-fatal, it continues on the same connection unencrypted. That is the downgrade. So: call ldap_start_tls_s, and on any non-success return, close the connection and never bind on it. Referrals are the same trap: a referral to ldap:// (not ldaps://) silently drops you to cleartext, so disable referral chasing or refuse ldap:// referrals.

Hostname and EKU

Chain validation proves the cert came from a trusted CA, not that you reached the right server. Hostname validation binds the cert to the name you dialed: it must appear as a SAN dNSName. Dialing by IP, or by a CNAME absent from the SAN, fails: that is the check working. EKU must include id-kp-serverAuth (1.3.6.1.5.5.7.3.1); a cert issued only for clientAuth is mis-issued for this purpose and strict clients reject it. Revocation checking is often off by default in LDAP clients, so decide it explicitly rather than inheriting it.

LDAPS vs StartTLS

LDAPS (ldaps://, 636)StartTLS (ldap://, 389)
TLS from first byteyesno: plaintext extended op first
Downgrade risknone if ldap:// is refusedreal if the failure is ignored
Referralsldaps:// referrals stay encryptedldap:// referrals drop to cleartext
Typical useAD, most modern clientsfirewalls that only allow 389

Choose LDAPS when you control both ends. Choose StartTLS when policy forces 389, and then make the failure fatal.

Failure modes and detection

  • Downgrade: StartTLS errors and the app binds anyway. Detect by logging the StartTLS result code and alerting on any bind on a connection with no TLS.
  • Wrong host: cert valid, SAN mismatch. TLS_REQCERT demand turns it into a hard failure; log the verification error.
  • Anonymous/unauthenticated bind: empty DN with empty password is anonymous; empty DN with a non-empty password is an unauthenticated bind, which servers should reject. Detect via AD event 2889 (unsigned SASL bind) or 2887 (unsigned simple bind); OpenLDAP logs err=49.
  • Credential sprawl: password in a world-readable config. Detect with file-mode checks and secret scanning.

Config

# /etc/ldap/ldap.conf
TLS_CACERT       /etc/ssl/certs/ca.pem
TLS_REQCERT      demand
TLS_PROTOCOL_MIN 3.3
# never TLS_REQCERT never

Bind with SASL EXTERNAL or GSSAPI; fall back to simple bind only after ldap_start_tls_s returns LDAP_SUCCESS.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Prevent LDAP injection in login and search flows.

Answer

What I'd say first

Two flows, two escaping rules, and they are not interchangeable. Search filters follow RFC 4515; bind DNs follow RFC 4514. The special-character sets differ, so escaping a value with the wrong one leaves a hole.

Assumptions: OpenLDAP or AD; the app has a service account for search; login binds as the user; the login identifier is a uid or email.

The answer: never concatenate input into a filter string. Build filters from (attribute, value) pairs with a library that escapes the value: Spring LDAP's EqualsFilter/AndFilter, or ldap3's escape_filter_chars. Input never reaches an attribute name or the filter structure. For the bind, prefer not to build a DN from input at all: search for the user with an escaped filter, read the DN back, bind with that. If you must build the DN, escape per RFC 4514.

Why the two rules differ

RFC 4515 filter specials: *, (, ), \, NUL. RFC 4514 DN specials: ", +, ,, ;, <, >, \, NUL, plus a leading # or space and a trailing space.

charin a filter valuein a DN
*substring wildcard → \2aliteral
( )filter structure → \28 \29literal
, +literalRDN separators → \2c \2b
=literalattr/value separator → \3d
\ NUL\5c \00\5c \00

Escaping * in a DN does nothing useful; failing to escape , in a DN lets the attacker append an RDN and bind as a different entry.

What a wildcard does to the match set

Directory: uid=alice, uid=adam, uid=bob.

  • (uid=a*) → alice, adam. * is a substring operator, not a literal.
  • (uid=a\2a) → nothing. \2a is a literal asterisk.
  • Login template (&(uid=%s)(userPassword=%s)) with uid * and password * → (&(uid=*)(userPassword=*)) → matches every entry holding both attributes. That is the bypass.

Safe construction, traced

Java 17 / Spring LDAP 3.x:

Java
String uid = "*)(uid=*";                       // straight from the login form
Filter f = new AndFilter()
        .and(new EqualsFilter("objectClass", "person"))
        .and(new EqualsFilter("uid", uid));
String encoded = f.encode();
// (&(objectClass=person)(uid=\2a\29\28uid=\2a))

EqualsFilter escapes the value: *→\2a, )→\29, (→\28, uid= literal, *→\2a. AndFilter wraps both clauses. The result matches a literal *)(uid=* uid: i.e. nothing: instead of a wildcard.

Failure modes

  • Auth bypass. Detection: log the encoded filter, not the raw input, and alert on any unescaped *, (, ) outside the template. Cost: full takeover of every account the filter matches.
  • Data exfil. (cn=*) returns the whole subtree. Detection: alert on result counts above the expected page size. Cost: a subtree search over a large directory hits the server's size limit; the client sees SizeLimitExceededException (JNDI) or a truncated result.
  • DoS. An unindexed substring like (cn=*a*) forces a full scan. Detection: OpenLDAP emits ... not indexed candidate lines at stats log level; alert on their rate. Cost: the directory server is shared with authentication, so a search flood becomes a login outage.
  • DN injection. Detection: assert the bind DN sits under the expected base and uses the expected RDN attribute. Cost: bind as an entry outside the intended OU.

Trade-offs

  • Filter builder vs escape-and-concatenate. The builder is safe by default but hides extensible-match filters ((cn:caseExactMatch:=...)) and :dn: modifiers. Hand-escaping keeps full expressiveness, but every call site is a chance to forget. Decide by call-site count: more than a handful, or any fed by a request, use the builder; for an exotic filter, escape by hand and pin it with a unit test asserting the encoded string.
  • Search-then-bind vs build-DN-from-input. Search-then-bind costs one extra round trip and a service account with read access to the user subtree, but removes DN construction from the login path. Build-DN is cheaper but needs RFC 4514 escaping and a fixed base. Decide by whether the login identifier maps to a predictable DN: email or uid under a known base, build it; anything else, search first.

What would change my answer: if the directory is AD and the login identifier is userPrincipalName, the DN is predictable and build-DN is fine; if the stack already ships a filter builder, use it rather than hand-escaping.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain how an application should integrate with a directory.

Answer

The first 90 seconds. Two questions decide the design: does the app need to verify the user, or only read attributes about them? And can it do a browser redirect? If it can redirect, use OIDC or SAML against the directory's IdP: Entra ID, Okta, ADFS. The app never sees a password, MFA and conditional access are enforced at the IdP, and it works off-network. If the clients are domain-joined Windows machines and you need silent auth, use Kerberos via SPNEGO. Only when neither is possible (a legacy appliance, a mainframe gateway, a CLI with no browser) do you bind with a directory password, and then only over LDAPS on 636 or StartTLS on 389, discarding it immediately after the bind.

Attribute lookup is a separate concern from authentication. Use a dedicated service account with read-only rights scoped to one subtree, and key every record on an immutable identifier: objectGUID in AD, entryUUID in OpenLDAP. Never sAMAccountName or userPrincipalName: both are renameable, and a rename silently orphans the account. Then mint your own session; do not re-bind per request.

Why the local session matters. If you bind on every request, the directory is in your request path and a DC outage is a total outage. A local session with cached claims decouples availability: the directory is consulted at login and at refresh, not at 200 ms p99. The cost is revocation latency, and that is the number you have to pick deliberately.

LDAP simple bindKerberos / SPNEGOOIDC / SAML
App sees passwordyesnono
MFA / conditional accessnonoyes, at IdP
Off-network clientsyes, over LDAPSneeds line of sight to a KDCyes
Client requirementanydomain-joined, or a keytabbrowser or device-code flow
Revocation bound bynext bindticket lifetimetoken lifetime

AD's default Kerberos policy is a 10-hour user ticket, 600-minute service ticket, 7-day renewal, so a disabled account can keep using an existing ticket for hours unless you also check userAccountControl on each refresh.

Reading attributes. AD caps a search at MaxPageSize, default 1000 entries; without the paged-results control (RFC 2696) a larger search fails with sizeLimitExceeded. For transitive group membership, AD needs the LDAP_MATCHING_RULE_IN_CHAIN OID 1.2.840.113556.1.4.1941: a plain memberOf check only sees direct membership.

Python
# Python 3.12, ldap3 2.9
from ldap3 import Server, Connection, SUBTREE, ALL

server = Server("dc01.corp.example.com", port=636, use_ssl=True, get_info=ALL)
conn = Connection(server,
                  user="cn=svc-app,ou=svc,dc=corp,dc=example,dc=com",
                  password=os.environ["LDAP_BIND_PW"],
                  auto_bind=True)
conn.search(
    search_base="ou=people,dc=corp,dc=example,dc=com",
    search_filter="(&(objectClass=user)(sAMAccountName=alice))",
    search_scope=SUBTREE,
    attributes=["objectGUID", "displayName", "mail", "userAccountControl"],
    size_limit=1,
)
e = conn.entries[0]
disabled = bool(int(e.userAccountControl) & 0x2)

Trace: the search returns at most one entry. userAccountControl comes back as an integer: 512 for a normal enabled account, 514 for a disabled one (512 | 0x2). 514 & 2 == 2, so disabled is True; 512 & 2 == 0, so it is False. That bit is the only reliable disablement signal; a locked-out account is a different flag and clears itself.

Failure modes and how you see them. Outage: bind error rate and latency spike; mitigated by the local session. Disablement: poll (&(objectClass=user)(uSNChanged>=<watermark>)) every 60 s, ordered by uSNChanged, and terminate matching sessions. uSNChanged is a per-DC monotonic counter, so the watermark is per-DC, not global. Rename: detected by a nightly reconciliation comparing objectGUID counts against your local table. Replication delay: intra-site notification is 15 s, but intersite defaults to 180 minutes, so a disable written on one DC may not reach the DC you read from for three hours. Deprovisioning: SCIM 2.0 (RFC 7643/7644) PATCH active=false if the IdP supports it; otherwise the reconciliation job is your only backstop.

The arithmetic that sets your session length. Say the SLA is "a disabled account loses access within 5 minutes." Intersite replication can take 180 minutes, so the directory cannot be the bound. Cap the local session at 5 minutes and poll every 60 s: worst case is one poll interval plus one session, well inside the SLA. If you set the session to 8 hours instead, your real revocation window is 8 hours regardless of what the directory says.

When collecting the password is right. A legacy appliance that cannot redirect, on a network where the directory is the only IdP, with no MFA requirement: bind over LDAPS, keep the password only for the duration of the bind, and never store it. Even then, if the client is domain-joined, Kerberos costs you a keytab and buys you no password handling at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design performant and safe LDAP searches.

Answer

Core answer (first ~90 seconds)

Three things decide the design before I write a filter: which server (Active Directory and OpenLDAP differ in limits and indexing), whether the caller is interactive or batch, and the latency budget. Assume AD or OpenLDAP, read-heavy, and that we own the client.

Bound the search on four axes: base and scope, filter shape, returned attributes, and limits plus paging. Filter shape is the lever that matters, because it decides whether the server answers from an index or scans every candidate entry.

Why filter shape dominates

A directory keeps per-attribute indexes. Equality, presence, and initial-substring filters can be answered from the index. A leading wildcard has no usable prefix:

(cn=smith*)   -> initial substring, index-usable
(cn=*smith)   -> "any" substring, no prefix, unindexed
(cn=*smith*)  -> unindexed

An unindexed filter forces the server to evaluate the filter against every entry under the base. Active Directory refuses that once it would scan more than its unindexed-search threshold (default 20,000 entries) and returns adminLimitExceeded (11). OpenLDAP has no such guard by default: it just burns CPU and I/O. OpenLDAP's substring index also has a minimum "any" length (index_substr_any_len, default 4), so even (cn=*smi*) falls back to a scan.

Scope compounds it: subtree from dc=example,dc=com touches the whole tree; base scope on a known DN reads one entry.

Limits and paging

sizeLimit and timeLimit of 0 mean "no client limit": server limits still apply. Exceeding them returns sizeLimitExceeded (4) and timeLimitExceeded (3). Set both.

For more results than one response, use the Simple Paged Results control, OID 1.2.840.113556.1.4.319 (RFC 2696). AD's MaxPageSize default is 1000. The cookie is opaque: RFC 2696 says the client must not interpret it, and it is only valid for the same server and the same search. Reusing it after an Abandon, or against another replica, fails.

Trade-offs

choiceuse whencost
Paged Resultssequential scan of a large result setcookie is server-bound; not a snapshot
VLV (2.16.840.113730.3.4.9)random access / jump-to-letter UIneeds a maintained sorted index; stateful
memberOf attributedirect membership, ADonly maintained membership
matching rule 1.2.840.113556.1.4.1941transitive membershipunindexed, slow on large groups

Caching: key on (base, scope, filter, attributes, bind identity). Results depend on the bind identity's ACLs, so never share a cache entry across identities. TTL bounded by the directory's change rate. Don't cache high-cardinality or per-user filters; the hit rate won't pay for the invalidation risk.

Failure modes and how I'd catch them

  • Unindexed search: AD logs event 1644 with the offending filter; OpenLDAP logs "not indexed". Watch for adminLimitExceeded.
  • Cookie misuse: unwillingToPerform (53) or a rejected cookie after Abandon or against a different replica.
  • Duplicate or missing entries across pages: paging is not a snapshot; a concurrent write shifts the result set. Detect by comparing total counts and paging on a stable sort key.
  • Abandoned searches: a client that closes without sending Abandon leaves the server working until timeLimit. Watch the server's active-operations counter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design a least-privilege LDAP service account.

Answer

First 90 seconds. Three things decide the design: which directory (AD and OpenLDAP have different ACL models), what the integration does (search only, or writes too) and where it runs. Then: one account per integration, no group memberships, an ACL scoped to one subtree and a named attribute list, explicit deny on password and replication attributes, no interactive logon right, credential in a managed store, and a retirement date.

Mechanism. ACLs are per-attribute, not per-object. OpenLDAP's olcAccess rules evaluate top-down, first match wins, and a rule can name attrs= and grant read, auth, write or none. auth is the one people miss: it lets a principal use an attribute for a bind without being able to read it. Exactly what a service account needs on userPassword. The bind succeeds; the hash never leaves the server. AD splits the same way: unicodePwd is write-only by design and unreadable by anyone, Domain Admins included, and writing it requires a 128-bit TLS channel.

Bind-time and search-time are separate checks. A bind evaluates the ACL against the bind DN's entry and userPassword; a search evaluates it against every requested attribute of every returned entry. An account can bind cleanly and still get nothing back.

OpenLDAP ACL for a read-only integration:

olcAccess: {0}to attrs=userPassword,shadowLastChange
  by self write
  by anonymous auth
  by dn.exact="cn=svc-app,ou=services,dc=example,dc=com" auth
  by * none
olcAccess: {1}to dn.subtree="ou=people,dc=example,dc=com"
  attrs=cn,uid,mail,memberOf,entry,objectClass
  by dn.exact="cn=svc-app,ou=services,dc=example,dc=com" read
  by * none

Trace:

  1. ldapwhoami -D cn=svc-app,ou=services,dc=example,dc=com -w $PW → rule {0} matches, auth granted → bind returns 0. The account never sees the hash.
  2. ldapsearch -D cn=svc-app,... -b ou=people,dc=example,dc=com '(uid=alice)' cn mail → cn and mail fall to rule {1}, read granted → both returned.
  3. Same search requesting userPassword → rule {0} matches first, auth only → the attribute is silently omitted. Result code is still 0 with zero attributes, not an error. An app that reads "no error" as "no password set" will misbehave.

Rules evaluate top-down, first match wins, so a stock trailing access to * by * read hands the account the whole tree and undoes both rules. Check the last rule before shipping.

AD specifics. Set the query policy rather than trusting defaults:

SettingDefault
MaxPageSize1000 entries
MaxQueryDuration120 s
MaxResultSetSize262144 bytes
MaxConnIdleTime900 s
MaxActiveQueries20

An app that doesn't page gets result code 4 (sizeLimitExceeded) at 1000 entries. Deny DS-Replication-Get-Changes and DS-Replication-Get-Changes-All explicitly: those two rights are DCSync, and an account holding them is a domain-wide hash dump waiting to happen. Deny interactive logon via the "Deny log on locally" and "Deny log on through Remote Desktop Services" user rights.

Trade-offs. A gMSA is strongest on Windows: a 240-byte password rotated every 30 days that no human sees, retrieval restricted by msDS-GroupMSAMembership. It doesn't apply off-domain or where no gMSA helper exists. Kerberos/SASL bind with the app's own machine account plus constrained delegation means no new secret, at the cost of tying identity to a host. A vault-issued password on a plain account works everywhere but you own rotation, and AD allows one password per account, so "rotate with overlap" means two accounts and a cutover, not two live passwords. An LDAP proxy holding the privileged credential behind a narrow API contains blast radius best; you pay with another component to run.

Failure modes.

  • Inherited ACEs: an ACE on the domain root flows to every object. Enumerate with dsacls on the target OU; confirm nothing inherited exceeds the intended attribute list.
  • Readable password attribute: search as the service account for userPassword and confirm zero attributes return. If the hash appears, the app's logs now hold it.
  • DCSync: event 4662 carrying the replication GUIDs from a non-DC principal.
  • Rotation breakage: one password per AD account, so in-place rotation spikes result code 49 / event 4625 until the app re-reads the secret. Two accounts, cut over, retire the old one.
  • Orphaned account: AD's lastLogonTimestamp replicates but is accurate only to ~9-14 days; OpenLDAP has no last-bind by default, so enable the lastbind overlay before deleting anything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design OU, group, and application-role boundaries.

Answer

Assumptions. One forest, one domain, AD DS functional level Windows Server 2016 or later, identities synced to Entra ID, apps from file shares up to a SaaS product with its own RBAC. If a regulator demands administrative isolation, that is a forest decision and it comes before any OU design.

The answer. Forest and domain are the security boundaries. An OU is not: it decides who administers an object and which Group Policy applies, and every administrator of the domain can reach every OU in it. An OU must never be the thing that stops an attacker. Boundaries land in three planes: delegation and policy scope in OUs, entitlements in groups, the application's own permissions in app roles assigned to groups. "Finance approver" belongs in a group, never in an OU name, and a GPO link or group edit that broadens access is a change like any ACL edit.

How access resolves. Effective access is the intersection of your token's SIDs (you plus transitive group membership) with the object's DACL. Deny ACEs are evaluated first; inherited ACEs (flag INHERITED_ACE) come from the parent chain and are recomputed when the object moves; explicit ACEs travel with it. The owner always holds READ_CONTROL and WRITE_DAC, so ownership is both a recovery path and a persistence path. Verify with the Effective Access tab in ADUC (Server 2012+ RSAT), dsacls.exe, or AccessChk -e.

How policy resolves. LSDOU: Local, Site, Domain, then OUs top-down. Last writer wins, an Enforced link beats Block Inheritance, link order breaks ties inside one container. Loopback processing for shared RDS hosts and kiosks; WMI filters and security filtering shrink the target set. Since MS16-072 (June 2016) policy is retrieved in the computer's security context, so removing Authenticated Users' Read on a GPO silently stops its user settings applying - it looks like a client problem.

How entitlements resolve. AGDLP: accounts into Global groups, Global into Domain Local, Domain Local on the ACL. Global groups hold accounts from their own domain and can sit on ACLs across trusts; Domain Local groups can be granted permissions only inside their own domain; Universal groups hold forest-wide members but replicate into the Global Catalog, so keep them small and stable.

App roles. In Entra ID, app roles are declared in the app registration's manifest and emitted in the roles claim, with assignment required; assigning them to groups needs Entra ID P1/P2. They authorise nothing outside the app - an app role is not an Entra directory role and grants no Azure RBAC. Prefer app roles to group claims when the app owns a small fixed permission set: directory group claims hit a documented cap and switch to an overage claim the app must resolve through Microsoft Graph.

PlaneGovernsExample
OUdelegation, GPO scopeOU=Workstations, GPO linked Enforced; the Reset Password extended right delegated to GG-Helpdesk on that OU only
GroupentitlementDomain Local FS-Finance-Modify granted Modify on the finance folder's ACL
App rolein-app permissionroles claim Invoice.Approver on the finance app registration

Trace - a deny you did not mean to inherit. Alice is in GG-Helpdesk and GG-Contractors. OU=Workstations allows Reset Password for DL-Helpdesk-Reset-PW and carries a separate explicit Deny Reset Password for GG-Contractors. Alice's token holds both SIDs; deny is evaluated first, so she cannot reset a password even though the allow was written for her. Detect with a dsacls diff on the OU and its children after any delegation change, and an AccessChk -e sweep when group membership changes.

Failure modes.

  • AdminSDHolder/SDProp: every 60 minutes on the PDC emulator, SDProp copies the AdminSDHolder ACL onto every object with adminCount=1 (Domain Admins, Enterprise Admins, Account Operators and the rest), so an ACE written straight onto one of those accounts is gone within the hour. Keep privileged accounts in their own OU with no delegated rights, and change AdminSDHolder when you need a new permission there.
  • Silent policy loss on move: moving a computer or user between OUs re-evaluates inherited ACEs and GPO scope while explicit ACEs and group membership stay behind. Pilot any reorganisation with a dsacls diff plus gpresult /h on a moved test machine.
  • Token size: each added nesting level lengthens the Kerberos PAC, and once it exceeds MaxTokenSize (default 48,000 bytes, under HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters) logons fail for your widest members and for nobody else. Count transitive groups before adding a level.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Resolve and govern nested group access.

Answer

Assumptions. I'll answer for Active Directory Domain Services on Windows Server 2016 or later, with Kerberos logon, and an application that consumes group membership for authorization. If the directory is Entra ID or Okta the resolution mechanism is different and I'd say so before answering: Entra ID doesn't nest role-assignable groups at all, and Okta group rules are flat.

The core answer. Don't compute transitive membership yourself. The domain controller already does it. Read the tokenGroups constructed attribute on the user object: it returns the transitive set of group SIDs, including nested groups, SID history, and the primary group. For a query-time check without a logon, use the LDAP matching rule LDAP_MATCHING_RULE_IN_CHAIN (OID 1.2.840.113556.1.4.1941) in a filter such as (member:1.2.840.113556.1.4.1941:=<userDN>). Both are evaluated by the DC against the live directory. A hand-rolled memberOf walk is not, and it will miss the primary group, Domain Users is a user's primary group by default and never appears in the member attribute, and it will miss SID history.

Why it behaves this way. At logon the DC builds the PAC, embedding every SID the user resolves to. Group scope decides what can nest where:

scopecan containreplicated to
globalglobal, universal (same domain)all DCs in the domain
domain localglobal, universal, domain local (any domain in the forest)all DCs in the domain
universalglobal, universal (any domain in the forest)the global catalog

That last row is the one that bites: universal group membership is resolved from the GC, so a DC that hasn't converged issues a stale token.

The limit, with arithmetic. MaxTokenSize lives at HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters, REG_DWORD, default 48000 bytes on Windows Server 2012 and later (12000 before that). A SID in the PAC costs roughly 28–32 bytes plus alignment; call it 40. 48000 / 40 ≈ 1200 SIDs, so a user in about a thousand groups is at the edge. When the token exceeds the limit, Kerberos-Key-Distribution-Center logs Event ID 31 and the logon fails or falls back to NTLM.

Trade-offs. Nesting is cheap to administer and mirrors the org chart; flattening membership into the application makes evaluation bounded and auditable but drifts. Flattening is the wrong call when the directory is the authority and the app can query it live, or when membership changes faster than the sync interval: you get stale grants that nobody can trace to a source.

Failure modes and how to detect them.

  • Token bloat: Event ID 31, plus 4627 logon events carrying oversized group lists.
  • Replication delay: compare tokenGroups for the same user across two DCs; a mismatch is the stale-token window.
  • SID history: migrated accounts carry old SIDs that tokenGroups includes, so a group you believe is empty still grants access. Query for sIDHistory explicitly.
  • Deleted group: the app holds a dangling DN and access silently drops.
  • Cycles: AD rejects a write that would nest a group inside itself, so cycles only appear in consumers that compute their own closure. SCIM sync jobs, custom LDAP apps. Test there, not in AD.

Governance. Keep Tier 0 privileged groups shallow and owned, and watch membership changes through 4728/4729 (global), 4732/4733 (domain local) and 4756/4757 (universal).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design delegated directory administration.

Answer

Core answer (first 90 seconds)

Delegation in Active Directory is an ACL problem, not a role problem. You grant a named security principal a specific access-control entry on a specific container, and inheritance carries it down the subtree. So the design reduces to three decisions: which container is the smallest one that holds every object the delegate must touch, which extended right does exactly the job, and what stops the grant from widening.

Assume a single forest, Windows Server 2016+ domain functional level, and RSAT/ADUC available. If any of those don't hold, say so before you design.

Mechanism

ADUC's Delegation of Control Wizard writes ACEs onto the container you pick. Two kinds of right matter:

  • Standard rights (Read, Write, Create Child, Delete Child) on the object.
  • Extended (control-access) rights, each identified by a rightsGuid. "Reset Password" is the User-Force-Change-Password right, rightsGuid 00299570-246d-11d0-a768-00aa006e0529. "Unlock account" is a write to lockoutTime. "Add member" is a write to the member attribute on a group.

Grant the extended right, not Generic All. The table is the design:

TaskRightScope
Reset password, force change at next logonExtended right 00299570-...OU=Users,DC=corp
Unlock accountWrite lockoutTimeOU=Users
Add/remove membersWrite memberthe specific group
Create userCreate Child User + Write on the attributes you allowOU=Users

Granting it in PowerShell:

POWERSHELL
$ou  = "OU=Users,DC=corp,DC=example,DC=com"
$sid = (Get-ADGroup Helpdesk-Tier1).SID
$acl = Get-Acl "AD:$ou"
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
  $sid, "ExtendedRight", "Allow",
  [Guid]"00299570-246d-11d0-a768-00aa006e0529",   # User-Force-Change-Password
  "Descendents", [Guid]"bf967aba-0de6-11d0-a285-00aa003049e2")  # user class
$acl.AddAccessRule($ace)
Set-Acl "AD:$ou" $acl

Descendents is what makes the ACE inherit to every object below the OU; the class GUID restricts it to user objects so it doesn't leak onto computers or groups. Verify with dsacls "OU=Users,DC=corp,DC=example,DC=com" or the Effective Access tab in ADUC.

Trade-offs

The alternative is OU-per-team ownership: hand a team Full Control of their own OU. It is far less work to operate and it survives reorganisation, but Full Control includes the ability to write ACLs and to create objects that inherit them, so a team can grant itself anything the OU inherits, and if the OU ever holds a Tier 0 or Tier 1 object, that is domain compromise. Reject it whenever the OU contains privileged objects; accept it for a leaf OU that holds only unprivileged users.

Role-based groups (Helpdesk-Tier1) beat per-person ACEs: per-person ACEs don't scale and leave orphaned SIDs when someone leaves.

Failure modes

  • Self-escalation via Write member. A delegate with Write member on a group that is nested into Domain Admins can add themselves. Detect with 4728/4732/4756 events; cost is full domain compromise.
  • adminSDHolder overwrite. SDProp runs every 60 minutes on the PDC emulator and rewrites the ACL of every member of a protected group from the adminSDHolder template. Any delegation you place on those objects is reverted. Detect by watching the ACL reappear; cost is a delegation that silently stops working.
  • Object moves. Moving a user to a new OU recalculates inherited ACEs; explicit ACEs travel with the object. A move can grant or strip rights. Detect by comparing effective access before and after.
  • Orphaned SIDs. Deleting the delegate group leaves unresolved SIDs in the ACL; a new group with the same name has a different SID and does not pick up the grant. Detect with dsacls.

Deny ACEs are evaluated before allow, so a broad deny can lock out the very admins you meant to keep. Use them only for a specific, audited exception.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Manage service principal names safely.

Answer

Assume a Windows AD forest: SPNs live in the servicePrincipalName attribute, and what an SPN selects is the Kerberos long-term key of the object that holds it. In a MIT realm with keytabs the problem is identical, with kadmin and ktadd instead of setspn.

What I would say first. An SPN is not a human-readable label; it is the KDC index into key material. The client asks for MSSQLSvc/sql01.corp.example.com:1433, the KDC finds the account carrying that SPN, and encrypts the service ticket with that account's key. Everything else follows from one invariant: one SPN, one key, and the right principal holds both. Four controls follow: ownership, uniqueness, key lifecycle, detection.

Ownership. The SPN goes on the principal whose key the service actually uses. SQL Server running under a domain account needs MSSQLSvc/... on that domain account, not on the computer account; most cases of authentication dying after a service account move are SPNs left behind on the old principal. A DNS alias gets its own SPN registered on the target account. When the SPN is missing the app often does not fail loudly: the client silently falls back to NTLM, so delegation stops working and you see logon type 3 with the NTLM package in event 4624 instead of an error.

Uniqueness. AD does not enforce it. setspn -S checks the global catalog before writing, but two DCs can each accept the same SPN for different accounts and replicate both into a genuine duplicate. The KDC then returns whichever the global catalog gives it, which varies by DC, and when it picks the account whose key the service does not hold the ticket cannot be decrypted: KRB_AP_ERR_MODIFIED (the target principal name is incorrect), a non-zero failure code on event 4769. Intermittent failures that track which DC answered are the signature. Sweep with setspn -X -F. Uniqueness is per forest, so prod and non-prod in separate forests can reuse names freely.

Key lifecycle, with the arithmetic. Default domain policy sets Maximum lifetime for a service ticket at 600 minutes. A manual password change retires the old key, so every service ticket already in a client cache, and every ticket a not-yet-replicated DC issues with the old key, fails until it ages out. Worst-case exposure is 600 minutes; rotating twice inside that window compounds the outage rather than shortening it, so the manual cadence is one rotation per ticket lifetime plus klist purge on hosts you control. Zero-downtime alternatives are a keytab holding both keys, or a gMSA, where the KDC and the host both read msDS-ManagedPassword and there is no window at all:

New-ADServiceAccount -Name gmsa-sql -DNSHostName sql01.corp.example.com -ServicePrincipalNames MSSQLSvc/sql01.corp.example.com:1433 -PrincipalsAllowedToRetrieveManagedPassword SQLHosts

That is a 240-character random password rotated on msDS-ManagedPasswordInterval, 30 days by default, which also puts the account out of Kerberoasting reach. Where a gMSA is not possible, cap the damage: set msDS-SupportedEncryptionTypes to 0x18 (AES only) so the KDC stops issuing RC4 tickets encrypted under the account NT hash, and alert on event 4769 with encryption type 0x17 for any account that holds an SPN.

Registration rights. ms-DS-MachineAccountQuota defaults to 10, so any authenticated user can create ten computer accounts and control SPNs on them. Set it to 0 and grant Validated write to service principal name only to the identity team and the gMSA owners. Audit 4738 and 4742 for changes carrying SPNs, and 5136 on servicePrincipalName where directory-change auditing is on.

Failure modes and detection.

SignalCauseFirst move
Intermittent auth failures that track which DC answeredDuplicate SPN across two accountssetspn -X -F
App works, delegation and audit break, 4624 shows NTLMAlias SPN never registered on the key ownersetspn -Q HTTP/app.corp.example.com
Breaks at rotation, heals by itselfCached tickets under the retired keyklist purge, or wait 600 minutes
4769 with encryption type 0x17 for a service accountKerberoasting, account still RC4-capableMove to gMSA, set msDS-SupportedEncryptionTypes

Trade-offs. Delegation is the other half of this job. msDS-AllowedToDelegateTo (constrained) or msDS-AllowedToActOnBehalfOfOtherIdentity (resource-based) beat the TRUSTED_FOR_DELEGATION flag, because unconstrained delegation means any ticket that lands on that host can be replayed anywhere. And do not over-engineer the register: if prod and non-prod are separate forests, a shared naming convention costs nothing and a cross-forest SPN database is friction with no payoff.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Operate Kerberos time and replay controls.

Answer

Core answer (first 90 seconds)

Assume MIT krb5 KDCs (1.20+) or Active Directory, and that you control both the KDC and the hosts. Kerberos has two independent time controls and they fail differently.

  1. Clock skew. The KDC and every service compare the timestamp in a request or authenticator against their own clock. MIT krb5 default clockskew = 300 seconds (5 min); AD default MaxClockSkew = 5 min. Outside that window the KDC returns KRB_AP_ERR_SKEW (37), and so does a service checking an authenticator.
  2. Ticket lifetime. This bounds how long a captured ticket stays usable. MIT defaults ticket_lifetime = 24h (86400 s) and renew_lifetime = 7d; AD defaults MaxTicketAge = 10h, MaxRenewAge = 7d, MaxServiceAge = 600 min.

The operational answer: run authenticated NTP (chrony with NTS, or AD's w32time hierarchy) so every host sits within a few hundred milliseconds of the KDC, leave clockskew at 5 min, keep ticket lifetimes bounded, and alert on skew errors instead of widening the window. Widening clockskew to 15 min to stop the pager both hides a dead NTP daemon and triples the replay window.

INI
# /etc/krb5.conf — MIT krb5 1.21
[libdefaults]
    clockskew       = 300      # seconds; default 5 min
    ticket_lifetime = 24h      # default 86400 s
    renew_lifetime  = 7d       # default 604800 s
    kdc_timesync    = 1        # client tracks KDC offset (default on)

[realms]
    EXAMPLE.COM = {
        kdc = kdc1.example.com
        kdc = kdc2.example.com
    }

Why it behaves this way. The KDC stamps tickets with its own clock. The client's authenticator carries ctime/cusec from the client clock. The service checks |authenticator.ctime - now| <= clockskew; outside it, KRB_AP_ERR_SKEW. The replay cache is the second half: the service records (client, server, ctime, cusec) and rejects a duplicate within roughly the skew window with KRB_AP_ERR_REPEAT (34). Ticket lifetime is the outer bound: a stolen ticket is usable only until it expires, and renew_lifetime caps total renewal.

Trace: skew rejection. Client clock 12:06:00, service host clock 12:00:00, clockskew = 300.

  1. Client sends AP-REQ with authenticator ctime = 12:06:00.
  2. Service computes |12:06:00 - 12:00:00| = 360 s.
  3. 360 > 300 → service returns KRB_AP_ERR_SKEW; the client logs "Clock skew too great".

Trace: replay. Same authenticator replayed inside the window.

  1. First AP-REQ: cache miss, entry (alice@EXAMPLE.COM, host/svc@EXAMPLE.COM, 12:00:00, 123456) stored, request accepted.
  2. Second AP-REQ with identical ctime/cusec: cache hit → KRB_AP_ERR_REPEAT.
  3. After the entry ages out (~skew window), the same authenticator would be accepted again, which is why the window must be ≥ clockskew and why a backward clock jump is dangerous.

Defaults to compare.

SettingMIT krb5AD
skewclockskew 300 sMaxClockSkew 5 min
user ticketticket_lifetime 24 hMaxTicketAge 10 h
renewalrenew_lifetime 7 dMaxRenewAge 7 d
service ticketmax_life 24 hMaxServiceAge 600 min

Trade-offs and deciding criteria. Set clockskew to the largest NTP offset you actually tolerate plus margin. If chrony holds hosts under 100 ms, 300 s is generous and you can tighten to 60 s to shrink the replay window; tighten only after NTP is proven, or you trade a rare skew error for a frequent one. Shorten ticket_lifetime (e.g. 10 h) to cut exposure of stolen tickets, at the cost of more KDC traffic and re-auths; lengthen it to cut load. Do not widen skew to silence alerts.

Failure modes and detection.

  • NTP/chrony dies on a host → drift → KRB_AP_ERR_SKEW. Detect via chronyc tracking offset and the skew-error rate in service logs.
  • VM snapshot restore or live migration → wall clock jumps. Detect by comparing monotonic vs wall clock and dmesg time-jump messages.
  • KDC replay cache on tmpfs cleared by reboot → replays accepted within the window. Detect by alerting on KDC restarts and replay-cache loss.
  • Multiple KDCs with unsynced clocks → intermittent failures depending on which KDC answers. Detect by comparing KDC logs and klist across KDCs.

Protect time administration. Only the NTP daemon writes the clock; block manual date -s and restrict who can change it, because an attacker who can move a host's clock can replay authenticators or push a ticket outside its validity window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design delegated Kerberos access for a multi-tier service.

Answer

Assumptions and the direct answer. Windows Server AD forest, a front-end web/API tier authenticating users with Integrated Windows Authentication, and a back-end (SQL Server or another service) that must authorize per user: row-level security, per-user audit. If the back end only needs to know which service called, don't delegate at all: run the front-end under its own service account. When it genuinely needs the user's identity, use constrained delegation: resource-based (RBCD) if the back-end team owns the config, otherwise KCD with msDS-AllowedToDelegateTo. Never unconstrained.

How the flow actually works. The KDC is the enforcement point, not the front-end. The client gets a service ticket to the front-end SPN; if the user's account isn't marked NOT_DELEGATED, the TGT is forwardable. The front-end then runs the S4U extensions (MS-SFU):

  • S4U2Self: the front-end asks the KDC for a ticket to itself on behalf of the user. This works even for non-Kerberos logons if the front-end has TRUSTED_TO_AUTH_FOR_DELEGATION (protocol transition). The resulting ticket is non-forwardable unless the user's own TGT was forwardable.
  • S4U2Proxy: the front-end presents that ticket and asks for a ticket to the back-end SPN. The KDC checks the delegation relationship (msDS-AllowedToDelegateTo on the front-end, or msDS-AllowedToActOnBehalfOfOtherIdentity on the back-end) and only then issues a ticket with the user as client and the front-end recorded in the transited-services field.

So the front-end cannot claim an identity the directory hasn't authorized; the check happens at the KDC.

Concrete design.

  • Front-end runs as a dedicated gMSA. msDS-AllowedToDelegateTo lists exactly the back-end SPNs, e.g. MSSQLSvc/db01.contoso.com:1433. No TRUSTED_FOR_DELEGATION (UAC 0x80000).
  • Prefer RBCD: msDS-AllowedToActOnBehalfOfOtherIdentity on the back-end account holds a security descriptor naming the front-end's SID, so the back-end owner controls who may delegate to it. RBCD still needs the front-end to have TRUSTED_TO_AUTH_FOR_DELEGATION (UAC 0x1000000) so S4U2Self yields a usable ticket when the user's own ticket isn't forwardable.
  • Sensitive accounts (domain admins, service accounts) go in Protected Users or get NOT_DELEGATED (UAC 0x100000); the KDC then refuses forwardable tickets and S4U2Proxy fails for them.
  • Every SPN alias must be listed: NetBIOS, FQDN and CNAME are distinct; delegation to one does not cover the others.
  • Cross-forest: the trust must have TGT delegation enabled (trust attribute 0x800), off by default since Server 2012. RBCD does not cross forest boundaries; use KCD with the trust flag.
  • Logging: 4769 records the target SPN, requesting account and transited services; 4624 logon type 3 shows "Impersonation Level: Delegation". Enable Audit Kerberos Service Ticket Operations.

Failure modes.

  • Unconstrained delegation (UAC 0x80000) on a front-end: any host compromise yields forwardable user TGTs replayable to every service in the domain. Detect by auditing UAC bits and the Delegation tab.
  • Protocol transition without need: the front-end can impersonate any user without their credentials, so a compromised front-end is total impersonation.
  • SPN mismatch: configured MSSQLSvc/db01:1433 but the app connects to MSSQLSvc/db01.contoso.com:1433 → S4U2Proxy fails with KDC_ERR_BADOPTION. Same error when a NOT_DELEGATED user is in the path.
  • Revocation isn't instant: removing an SPN from the allowed list applies to the next ticket request; already-issued tickets stay valid until expiry (default 10 hours, max 7 days).

What would change the decision. Back end needs only the service identity → skip delegation, use the front-end's own credentials. Back end can't consume a Kerberos ticket (non-Windows, SaaS) → terminate identity at the front-end and pass a signed JWT. Different forest with no TGT-delegation trust → token-based approach or a middle tier in the resource forest.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design directory identity correlation and rename handling.

Answer

Clarify first: which directories, which sync engine, and is this a single forest or a cross-forest migration? I'll assume AD DS as the source of truth, Entra ID (Azure AD) via Azure AD Connect, one OpenLDAP consumer, and a cross-forest migration in flight.

Correlate on an identifier the directory assigns and never rewrites.

DirectoryKeySizeWhy it holds
AD DSobjectGUID16 bytesassigned at creation; not part of the DN, so rename and intra-forest move leave it alone
AD DS, cross-forestmS-DS-ConsistencyGuid16 bytesAzure AD Connect uses it as the source anchor when objectGUID can't be preserved across forests
OpenLDAPentryUUID (RFC 4530)16 bytesoperational attribute: you must request it explicitly or it won't come back
AD SIDobjectSid24 bytes typicalimmutable inside a domain, but a cross-domain move mints a new SID

Never key on DN, CN, displayName, mail, or SID alone. DNs change on rename and move. altSecurityIdentities is certificate mapping, not an identity key.

Worked trace. A sync engine holds the previous export keyed by GUID and classifies the incoming one:

Python
# Python 3.12
def classify(prev, incoming):          # both: {guid: dn}
    out = []
    for guid, dn in incoming.items():
        if guid not in prev:
            out.append(("NEW", guid, dn))
        elif prev[guid] != dn:
            out.append(("RENAME", guid, prev[guid], dn))
        else:
            out.append(("UNCHANGED", guid, dn))
    for guid, dn in prev.items():
        if guid not in incoming:
            out.append(("DELETE", guid, dn))
    return out

Run it on four records:

Python
prev = {
  "8f3a..01": "CN=John Doe,OU=Sales,DC=contoso,DC=com",
  "8f3a..02": "CN=Ana Ruiz,OU=Sales,DC=contoso,DC=com",
  "8f3a..03": "CN=Bob Lee,OU=IT,DC=contoso,DC=com",
}
incoming = {
  "8f3a..01": "CN=John Smith,OU=Marketing,DC=contoso,DC=com",
  "8f3a..02": "CN=Ana Ruiz,OU=Sales,DC=contoso,DC=com",
  "8f3a..04": "CN=Bob Lee,OU=IT,DC=contoso,DC=com",
}

Trace: ..01 is in prev with a different DN → RENAME. ..02 matches → UNCHANGED. ..04 is absent from prev → NEW. Then the second loop finds ..03 missing from incoming → DELETE.

[("RENAME", "8f3a..01", "CN=John Doe,OU=Sales,...", "CN=John Smith,OU=Marketing,..."),
 ("UNCHANGED", "8f3a..02", "CN=Ana Ruiz,OU=Sales,..."),
 ("NEW", "8f3a..04", "CN=Bob Lee,OU=IT,..."),
 ("DELETE", "8f3a..03", "CN=Bob Lee,OU=IT,...")]

The trap is in the last two rows: Bob Lee's CN is byte-identical in both exports, but the GUID changed, so it is a delete plus a create. A CN-keyed engine would have "matched" them and silently transferred Bob's group memberships to a new account.

Failure modes and detection.

  • Duplicate account: correlation missed, second object created. Detect: two objects sharing employeeID or mail. Cost: one helpdesk ticket per duplicate.
  • Orphan: delete+create lost group memberships. Detect: sync error log, empty memberOf. Cost: lost access, and a security gap until someone notices.
  • False merge: two people collapsed into one. Detect: audit log showing access the user never had. Cost: the worst one; it's an access-control incident.
  • Cross-forest duplicate: mS-DS-ConsistencyGuid unset before the move. Detect: compare objectGUID sets across forests before cutover.

Sizing. Correlation is O(n) with a GUID hash map. A heuristic fallback that compares every pair is O(n²): 40,000 objects is 1.6 billion comparisons, which is why heuristics need a blocking key (mail domain, employeeID prefix) before scoring. Labelled example: a 40,000-account forest with a 1% correlation failure rate is 400 duplicates; at 15 minutes of helpdesk time each, that's 100 hours of queue.

Trade-offs. Hard merge combines attributes and deletes one object: clean, irreversible. Soft merge links them and keeps both: reversible, but two objects now answer to one person and every downstream report has to know. Heuristic fallback (employeeID, mail) is fine as a candidate generator with a confidence threshold and human confirmation; it is not fine as the key. Bound your staleness: AD inter-site replication defaults to 180 minutes, Azure AD Connect's delta cycle defaults to 30 minutes, and tombstone lifetime defaults to 180 days. A delete+create pair older than the tombstone window can't be reconciled from the directory itself.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design applications for directory replication behavior.

Answer

Core answer (first 90 seconds)

Assume Active Directory Domain Services (AD DS) as the directory, and that the app talks LDAP and Kerberos. AD DS is multi-master: every writable domain controller (DC) accepts writes, and each propagates them to the others. So the design question is not "is there a primary" but "how stale can a read be, and where must a write land."

Three rules cover most designs:

  1. Send writes to a writable DC in the client's own site. Never write to a read-only DC (RODC): it returns an LDAP referral instead of accepting the write.
  2. For read-after-write, read from the same DC that accepted the write, or carry the object's version (uSNChanged) and re-read until the replica's copy is at least that version. Do not assume a different DC already has it.
  3. Treat replication as eventual, with a bounded but real lag.

Mechanism: why lag exists

Each DC stamps every change with a USN (Update Sequence Number) from a local monotonic counter. A partner tracks a high-watermark (highest USN it has seen from that DC) and an up-to-dateness vector (highest USN seen from every other DC, used to suppress redundant propagation). The KCC builds the replication topology from sites and site links.

PathTriggerDefault interval
Intra-site (same site)change notification~15 s after a change
Inter-site (across a site link)scheduled180 min (minimum 15 min)
Urgent replication (account lockout, LSA secrets, RID pool)immediateintra-site only
KCC topology recompute—every 15 min

Inter-site replication compresses data and can be scheduled; intra-site uses uncompressed RPC. A write in one site can take up to 3 hours to reach another by default: that is the number to design against.

Read-after-write trace

A client writes user.mail on DC-A at uSNChanged 500123. It immediately reads from DC-B, whose high-watermark for DC-A is 500100. DC-B returns the old value. The app re-reads DC-B every 2 s until its copy shows uSNChanged >= 500123, or reads DC-A directly. Sticky-to-DC-A is simplest; version-checking survives load balancers that spread reads across DCs.

Trade-offs

  • Same-DC read: zero extra latency, but pins the client to one DC. Bad if that DC fails mid-session.
  • Version-aware re-read: works across any DC, costs a poll loop and a bounded wait.
  • Authoritative read (force the query to a specific DC or the global catalog): correct but adds a hop and a single point of dependency.

Choose same-DC for interactive sessions; version-aware for distributed services that can retry.

Failure modes and detection

  • Lingering objects: a DC offline longer than the tombstone lifetime (180 days default) misses a deletion and reanimates the object on reconnect. Detect with lingering-object detection (on by default in forests created on Server 2016+) and replication health scripts; fix by re-deleting.
  • USN rollback: restoring a DC from an old snapshot regresses its USN; partners detect the regression and quarantine replication. Detect via replication-monitor alerts; fix by demoting and re-promoting.
  • RODC credential caching: an RODC caches credentials for principals in its Password Replication Policy Allowed list; a stolen RODC exposes those. Keep privileged accounts on the Denied list.
  • Clock skew: Kerberos rejects tickets with more than 5 min skew, so a DC with a bad clock breaks auth before replication does. Monitor w32time.
  • Concurrent writes: AD resolves per attribute. Higher version wins, then later timestamp, then higher originating DC GUID; multi-valued adds beat deletes. Design so two sites do not own the same attribute.

Testing: partition a site link and confirm the read-after-write path still converges; fail a DC and confirm clients re-target; skew a DC clock; write the same attribute from two sites and check the winner.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How does the Active Directory Recycle Bin differ from tombstone reanimation, and what are the operational requirements and irreversible impacts of enabling it?

Answer

The 60-second version. Both mechanisms recover a deleted object; they differ in what survives deletion. Tombstone reanimation resurrects a stripped shell. The Recycle Bin keeps the object whole.

Without the Recycle Bin, deleting an object leaves a tombstone in CN=Deleted Objects,<domain DN>. The tombstone keeps a fixed minimal set (objectGUID, objectSid, nTSecurityDescriptor, and the RDN) and little else. member, memberOf, unicodePwd, mail, manager, directReports: gone. Reanimation (LDP.exe, or Sysinternals ADRestore.exe) clears isDeleted and moves the object back. Because the SID and GUID survive, ACLs and SIDHistory references still resolve, but you re-add every group membership and attribute by hand, usually from a system-state backup.

With the Recycle Bin enabled, deletion sets isDeleted=TRUE and leaves the object in CN=Deleted Objects with all attributes intact, including link-valued ones like member and memberOf. Restore-ADObject returns it to its original DN (via the lastKnownParent attribute) with memberships, password, and ACLs unchanged. No authoritative restore, no downtime. If the parent OU was also deleted, restore the OU first or pass -TargetPath.

Lifecycle

Delete (isDeleted=TRUE)
  Live object ──────────────► Deleted object      [all attributes intact]
                                  │  msDS-deletedObjectLifetime
                                  │  (default = tombstoneLifetime, 180 d)
                                  ▼
                             Recycled object      [isRecycled=TRUE, attributes stripped]
                                  │  tombstoneLifetime (180 d)
                                  ▼
                             Garbage collected    [pages reused; file not shrunk]

msDS-deletedObjectLifetime defaults to null, so it inherits tombstoneLifetime (180 days). After that the object becomes a recycled object with attributes stripped, then is garbage collected after a further tombstoneLifetime. Default delete-to-GC window: 180 + 180 = 360 days.

MechanismObject stateAttributesmember/memberOfRecovery window
Recycle Bin, deleted objectisDeleted=TRUEAll preservedPreservedmsDS-deletedObjectLifetime (default 180 d)
Recycle Bin, recycled objectisRecycled=TRUEStripped to tombstone setStrippedNot restorable; waits for GC
No Recycle Bin, tombstoneisDeleted=TRUEobjectGUID, objectSid, nTSecurityDescriptor, RDNStrippedtombstoneLifetime (default 180 d), reanimation only

Operational requirements

  • Forest functional level Windows Server 2008 R2 or higher, every DC in the forest at 2008 R2 or later, and the 2008 R2 schema (version 47): that schema supplies msDS-deletedObjectLifetime and msDS-isRecycled.
  • Enabled once per forest, no reboot:
POWERSHELL
Enable-ADOptionalFeature -Identity 'Recycle Bin Feature' `
  -Scope ForestOrConfigurationSet -Target 'corp.example.com'
  • The change replicates. Objects deleted before it reaches a given DC are still tombstones and can only be reanimated.

Irreversible impacts

  • It cannot be turned off. The feature object (GUID 766ddcd8-acd0-445e-a3b9-5f2b477e45d8) has no disable path; the only way back is a forest rebuild.
  • Raising FFL to 2008 R2 is itself irreversible: you cannot lower a forest functional level.
  • DIT growth. Deleted objects hold full attribute sets for up to 360 days. ntds.dit does not shrink on its own; ESE reuses freed pages, and reclaiming space needs an offline defrag (ntdsutil files compact). Backups and new-DC promotion (IFM) carry the larger file.
  • No retroactive protection: objects already tombstoned stay stripped.
  • It covers deletion only, not modification, schema changes, or deletion of a domain or the forest.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Handle restored or long-offline directory replicas safely.

Answer

What I'd say first (90 seconds)

Assume the replica is hostile until proven otherwise. A directory replica restored from a snapshot is not "a DC that's behind": it is a DC that will re-assert state the rest of the forest has already deleted, and it may re-issue identifiers it has already handed out. So keep it off the network, find out how old the snapshot is, and compare that age against the tombstone lifetime. That one comparison decides everything else.

Assumptions I'd state out loud: Active Directory, forest created on Windows Server 2003 SP1 or later, so tombstoneLifetime defaults to 180 days; the replica is a writable DC, not an RODC; and I have a system-state backup plus a known-good DC to compare against.

Why a restored replica diverges

Each DC keeps a local USN counter that only ever increases. Partners track a high-watermark and an up-to-dateness vector per naming context. Restore a DC from a backup taken 200 days ago and its counter resets to the old value, so it re-issues USNs its partners have already consumed. Partners detect this as a USN rollback (Directory Service event 2095) and stop replicating inbound from it: the DC quarantines itself, which is the behaviour you want.

The second mechanism is the invocationID, a GUID identifying that database instance. A restore brings back the old invocationID with lower USNs, which is the same signal. Resetting the invocationID forces a full re-replication of the naming context.

Third, tombstones. Deleted objects live as tombstones for tombstoneLifetime (180 days by default), then are garbage-collected. A replica offline longer than that comes back holding objects the forest deleted and purged, and re-replicates them as lingering objects. With strict replication consistency (default on Windows Server 2003 SP1 and later), the destination DC refuses inbound replication from a source that has not replicated within the tombstone lifetime, event 2042, and lingering objects that do get through raise event 1988.

The same shape holds outside AD: OpenLDAP's contextCSN and 389 Directory Server's replica update vector play the USN/up-to-dateness role, and a restored supplier with a stale RUV is rejected or must be re-initialized.

The decision

Snapshot age vs tombstone lifetimeRestore modeWhat it costs
Younger, and the DC's identity is not reusedNon-authoritative restore, then let replication convergeMinutes; SYSVOL burflags D2
Younger, but specific objects must be forced backAuthoritative restore (ntdsutil), SYSVOL burflags D4Objects re-propagate with bumped versions; can resurrect what you meant to delete
Older than the tombstone lifetimeDo not restore. Rebuild the DC and let it replicate from a healthy partnerHours, but no lingering-object cleanup
Snapshot age unknownTreat as older—

Failure modes and how I'd catch them

  • Lingering objects: repadmin /removelingeringobjects against a known-good DC; event 1988 on the destination.
  • Stale SYSVOL: FRS journal wrap (event 13568) or DFSR dirty shutdown (event 2213); non-authoritative D2 resync.
  • Stale secrets: the DC's machine account password rotates every 30 days by default, so a 200-day-old snapshot has a broken secure channel. krbtgt must be reset twice with replication convergence between resets, or old TGTs stay valid.
  • Duplicate SIDs from a stale RID pool: scan for duplicate SIDs; they silently break ACLs.
  • Time skew: Kerberos tolerates 5 minutes; a restored DC with a stale clock fails authentication before anything else.

Trade-off I'd name out loud

Reconcile is cheaper than rebuild, but only when the snapshot is inside the tombstone lifetime and you can prove the identity was not reused. Past that boundary, rebuild is the honest answer: the cleanup cost of lingering objects across a large forest exceeds the rebuild. And an authoritative restore is a weapon: it re-asserts objects with higher versions, so it will happily resurrect an account you deleted on purpose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Choose directory endpoints for forest-wide lookup.

Answer

Core answer. For a forest-wide lookup, point the client at a global catalog: LDAP on TCP 3268, LDAPS on 3269. A GC is a domain controller that holds a partial, read-mostly replica of every naming context in the forest, so one connection can find an object in any domain. Drop to a domain controller (389 plain, 636 TLS) when you need an attribute the GC doesn't carry, when you need to write, or when you need to authenticate a principal in that domain. If you can't say which of those three you need, you want the GC.

Why the GC is partial. The GC replicates a partial attribute set (PAS), not whole objects. The schema decides membership: an attribute with isMemberOfPartialAttributeSet = TRUE is replicated to every GC in the forest. The default set covers what forest-wide lookups usually need: objectClass, cn, distinguishedName, objectGUID, objectSid, sAMAccountName, userPrincipalName, memberOf. Everything else is absent, including most application attributes added by Exchange or line-of-business schemas. The reason is replication cost: the GC is a forest-wide replica, so every extra attribute multiplies across every GC.

The consequence bites: a GC query for a non-PAS attribute does not error. It returns the objects with the attribute simply missing. That silent empty result is the most common GC bug.

Referrals. A GC accepts writes only for objects in its own domain. Ask it to modify an object in another domain and it returns an LDAP referral (result code 10) pointing at a DC in that domain. Most client stacks do not chase referrals by default: JNDI's java.naming.referral defaults to ignore, OpenLDAP's ldapsearch needs -C, and .NET's DirectorySearcher surfaces the referral as an error. Either chase explicitly or resolve the target domain first and connect there.

Authentication. Password hashes live in the domain naming context, not the GC. A GC can bind principals from its own domain; for a user in another domain, bind against a DC in that user's domain. Kerberos goes to port 88 on a DC, not to the GC.

Deciding table.

NeedEndpoint
Find an object anywhere in the forestGC, 3268 / 3269
Read an attribute outside the PASDomain DC, 389 / 636
Write to an objectDC of the object's domain
Authenticate a userDC of the user's domain, 389/636 or 88
Universal group membershipGC (global groups appear only in their own domain)

Failure modes and how you see them.

  • Non-PAS attribute. Query returns objects, attribute missing. Detect by running the same filter against a domain DC and diffing, or check isMemberOfPartialAttributeSet in the schema.
  • Unchased referral. LDAP result code 10, or a DirectoryServicesCOMException in .NET. Detect by logging the result code, not just the exception message.
  • Port blocked. 3268 filtered while 389 open: forest-wide searches fail, domain queries work. Detect with a port check from the client subnet.
  • Replication lag. Object created in domain A, GC in domain B hasn't seen it. Detect by comparing whenCreated against repadmin /showrepl output.
  • PAS change. Adding an attribute to the PAS forces a full sync of the partial replica across every GC: a replication spike, not an incremental update. Detect it in repadmin /showrepl and GC sync events.

Practical defaults. Page forest-wide searches: AD's default MaxPageSize is 1000 objects, so an unpaged GC search silently truncates. And memberOf on a user shows universal groups forest-wide but global groups only from the user's own domain; domain-local groups need a DC in that domain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Secure LDAP referral and cross-directory behavior.

Answer

Assumptions I'd state up front: an LDAPv3 client (OpenLDAP's libldap or the AD client), the app is bound to one directory, and the real question is whether it should follow referrals out of that directory. My default answer: turn client-side referral chasing off and handle referrals explicitly, unless the app genuinely needs a forest-wide search and runs inside the same forest with the same identity.

Referrals are how a directory says "that naming context isn't mine, ask this other server." They arrive in two wire shapes, and they need different handling.

  • Result code 10 (referral): returned to a bind, search or modify when the server holds no such entry. The whole operation is redirected; the body is a list of LDAP URLs: ldap://host:port/baseDN?attrs?scope?filter.
  • searchResultReference (protocol tag 0x73): zero or more of these arrive during a search, interleaved with searchResultEntry, then searchResultDone. Entries plus unreachable referrals gives done code 9 (partialResults); referrals alone gives 10.

Chasing is a client decision, not a server one. libldap chases by default (LDAP_OPT_REFERRALS is on); AD clients chase within a forest. Chasing means: open a new connection to the referred host, re-issue the operation, and, the security-relevant part, present the same bind identity unless you intervene. That is credential forwarding to a host you didn't choose.

So the first move is ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF) and an explicit handler. When you do chase, these are the controls and why each exists:

  • Scheme: accept only ldaps:// (636) or ldap:// after a successful StartTLS; reject plain ldap://. A referral URI is attacker-influenced if any server in the chain is.
  • TLS identity: validate the certificate against the referral's hostname, not the original server's. Otherwise a referral to evil.example.com carrying a cert for dc1.corp.example passes.
  • Credentials: don't resend a reusable bind DN/password. Use GSSAPI with constrained delegation, or bind per target. AD cross-forest referrals require credentials for the target forest: the same credentials won't work, which is a feature, not a bug.
  • Hops and cycles: cap at 3–5 and keep a visited set of (host, port, baseDN). A cycle otherwise hangs until the server's MaxQueryDuration (AD default 120 s).
  • Scope and attributes: the referral URL can carry its own scope and filter; re-apply your scope and attribute allowlist at the destination rather than trusting the URL.
  • AD policy defaults that bound the blast radius: MaxPageSize 1000, MaxValRange 1500, MaxQueryDuration 120 s.

A search that hits a referral, traced:

client: search base="dc=corp,dc=example" scope=sub filter=(objectClass=user)
server: searchResultEntry ...            (local entries)
server: searchResultReference ldap://dc2.corp.example/dc=emea,dc=corp,dc=example??sub
server: searchResultDone resultCode=9    (partialResults)

If you chase: new connection to dc2.corp.example:636, StartTLS, bind. With what identity?, then re-issue with base dc=emea,.... If you don't: you hold partial results and must decide whether that's acceptable.

Failure modes worth naming:

  • Loop A→B→A: the hop counter trips; the symptom is latency up to MaxQueryDuration, not an error.
  • Kerberos SPN mismatch: the referral host has no registered SPN, so the ticket request fails and surfaces as LDAP 49 or a GSSAPI error, not as a referral error.
  • Partial results treated as success: code 9 silently drops the unreachable branch.
  • DNS rebinding: an allowlisted hostname re-resolves to a new address; re-validate or pin.
codenamemeaning
10referraloperation redirected; no local result
9partialResultsentries returned, some referrals not chased
0successcomplete, no outstanding referrals
49invalidCredentialsoften a failed bind at the referral target

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do one-way and two-way external versus forest trusts differ in Active Directory, and how does SID filtering prevent elevation of privilege across those trust boundaries?

Answer

A trust is an authentication pipeline between two Kerberos realms: the trusting domain's KDC accepts tickets the trusted domain's KDC issued. Direction is named from the trusting side. A one-way incoming trust on A (A trusts B) lets B's accounts reach A's resources; the same link is a one-way outgoing trust on B; a two-way trust creates cross-realm keys in both directions. Direction is orthogonal to transitivity: a two-way external trust and a one-way forest trust are both normal.

External and forest trusts differ in scope, not in direction:

External trustForest trust
EndpointsTwo specific domains in different forests (or a Windows NT 4.0 domain)Forest root domains only; both forests at Windows Server 2003 functional level or higher
TransitivityNone: only the two linked domains authenticateTransitive across every domain in both forests
RoutingDirect domain-to-domain referralsReferrals walk to each forest root, then down; name-suffix routing decides which UPN/SPN suffixes are claimed
Typical useLegacy/NT4, or a narrow one-domain relationshipWhole-forest collaboration

SID filtering

Cross-realm, the trusted KDC packs the user's authorization data into the PAC carried in the TGT and referral tickets: user SID, group SIDs, sIDHistory. Nothing in that PAC is bound to the trusting domain, so a compromised DC in the trusted domain can mint a PAC that appends SIDs the trusting domain will honour: Enterprise Admins (RID 519), Domain Admins (512), and so on.

SID filtering is the trusting domain's defence, on by default for external and forest trusts. The trusting DC's LSA walks the PAC and drops any SID whose domain portion is not in the trusted namespace:

  • External trust: the domain portion must equal the trusted domain's SID exactly.
  • Forest trust: the domain portion must be one of the domains in the trusted forest.

Worked trace. Two forests, contoso.com and fabrikam.com, two-way forest trust. alice@fabrikam.com\eu-west opens a share on contoso.com\na\fileserver.

  1. eu-west KDC issues alice a TGT with PAC: S-1-5-21-<eu-west>-1105 (alice), -513 (Domain Users).
  2. No local SPN match → referral TGT to fabrikam.com root.
  3. fabrikam.com root → referral TGT to contoso.com root (the forest trust).
  4. contoso.com root → referral TGT to contoso.com\na.
  5. na's KDC issues the service ticket; fileserver hands the PAC to na's LSA.
  6. LSA filters: every SID's domain portion is a fabrikam domain → all pass → token built.

Now compromise the eu-west DC and forge S-1-5-21-<contoso-root>-519 (contoso Enterprise Admins). At step 6 the domain portion is contoso's root SID, not in the fabrikam namespace → dropped. No elevation.

The limit: forge S-1-5-21-<fabrikam-root>-519 instead and it passes. That SID is inside the trusted forest. The attacker gains Enterprise Admins in fabrikam's own forest root, a forest they already control. The boundary that holds is the forest, not the domain. Intra-forest trusts apply no filtering at all, which is why a compromised child domain can forge its forest root's Enterprise Admins.

Operating it

  • Get-ADTrust -Filter * exposes SIDFilteringQuarantined, SIDFilteringForestAware, SelectiveAuthentication, ForestTransitive, Direction.
  • netdom trust <trusting> /domain:<trusted> /quarantine:yes|no toggles external-trust filtering; /enablesidhistory:no is the default and blocks sIDHistory across the trust.
  • Selective authentication (/selectiveauth:yes) is the stronger forest-trust control: it requires an explicit "Allowed to Authenticate" ACE on each resource, so a trusted user gets no implicit access.
  • The trust account password rotates every 30 days by default.

SID filtering does nothing against a compromised trusting domain, and it does not remove legitimate group membership a trusted user already holds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design LDAP TLS failure and certificate rotation behavior.

Answer

Assumptions: internal directory (OpenLDAP or AD), LDAPS on 636 with StartTLS on 389 as a fallback path; clients are app servers binding with a service-account password over libldap or Java JNDI; you control the server and the CA but not every client's trust store.

The core rule. A simple bind puts the password in the bind request. So the client must not send a bind until the TLS handshake has completed and the peer certificate has validated against the configured CA and the hostname. If any of those fail, abort the connection, return a generic error to the caller ("directory unavailable"), and write the detail (cert subject, SAN, issuer, expiry, the exact OpenSSL error) to a protected log the caller can't read. Never retry the bind on the same connection, never fall back to 389 cleartext, never set TLS_REQCERT never / trust-all to "make it work."

Why StartTLS stripping is the sharp edge. On 389 the client sends a StartTLS extended request and waits for the server's response. An on-path attacker can drop or rewrite that response so the client believes the server declined StartTLS and proceeds in cleartext: the bind then succeeds and the password is on the wire. The defense is to require TLS: if StartTLS isn't confirmed, fail. LDAPS on 636 has no such downgrade because TLS is the transport from byte one. Prefer 636; if you must use 389, treat "StartTLS not offered" as a hard failure, not a fallback.

What hostname validation actually checks. Per RFC 9525, the client matches the name it dialed against the certificate's SAN dNSName entries; CN fallback is gone in modern clients. A wildcard matches exactly one leftmost label (*.corp.example matches ldap1.corp.example, not a.b.corp.example). This is why a cert reissued for a new VIP name fails even though the chain is fine.

Rotation trade-offs.

strategywhen it winscost
Dual-cert overlapyou control both ends; slow clientsoverlap window must exceed the slowest client's refresh interval
Short-lived (90d) + automationyou can reload without restarta missed renewal is a full outage
ACME / internal step-camany certs, want zero-touchCA must be reachable; a reload path must exist

Deciding criteria: how many trust stores you must touch, whether the server reloads certs without a restart, and the blast radius of a bad issuance.

Failure modes and how you see them.

  • Expired: handshake fails with "certificate has expired"; every bind fails at the same wall-clock second. Detect with expiry alerts at 30/14/7 days.
  • Wrong name: "hostname mismatch"; one client fails after a DNS/VIP change.
  • Unknown chain: "unable to get local issuer certificate"; clients with a stale trust store fail right after a CA rotation.
  • Revoked: OCSP/CRL. Decide soft-fail vs hard-fail explicitly: hard-fail means an unreachable OCSP responder is an outage.
  • Weak protocol: TLS 1.0/1.1 rejected (RFC 8996); an old client fails.
  • StartTLS stripping: the bind succeeds in cleartext. Silent, the worst case. Only caught by requiring TLS and monitoring for cleartext binds.

Config that enforces it (OpenLDAP client):

TLS_CACERT /etc/ssl/certs/internal-ca.pem
TLS_REQCERT hard
TLS_PROTOCOL_MIN 3.3

3.3 is TLS 1.2. Java clients need the same CA in javax.net.ssl.trustStore, with com.sun.jndi.ldap.object.disableEndpointIdentification left at its default (false).

What would change the decision: if clients can't reload certs without a restart, dual-cert overlap becomes mandatory and the overlap window is set by your slowest deploy cycle, not by the cert lifetime.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Roll out LDAP signing and channel-binding requirements.

Answer

Roll out LDAP signing and channel binding

Assumptions: one Active Directory forest on current Windows Server, domain controllers serving LDAP on 389 and LDAPS on 636, the global catalog on 3268/3269; clients are a mix of Windows services, JNDI-based Java apps and vendor appliances; you own the DCs and Group Policy but not the vendor software. If LDAPS isn't healthy on every DC yet, fix that first - nothing below applies without a working TLS listener.

What I'd say first: don't turn enforcement on and work the fallout. Instrument, remediate by owner, then enforce - and split channel binding across its middle value, because that value finds relay paths without breaking clients that cannot send a channel binding token. Microsoft's 2020 plan to enable these by default was postponed, so this is yours to drive.

The knobs

Both DC settings sit under HKLM\SYSTEM\CurrentControlSet\Services\NTDS\Parameters, per DC or pushed by the "Domain controller: LDAP server signing requirements" policy:

ValueControls012
LDAPServerIntegritysigningNoneNegotiate signingRequire signing
LdapEnforceChannelBindingchannel bindingNever (documented default)When supportedAlways

The client-side mirror is HKLM\SYSTEM\CurrentControlSet\Services\ldap\ldapclientintegrity, exposed as "Network security: LDAP client signing requirements".

Why the two fail differently

Signing covers SASL binds - Negotiate, NTLM, Kerberos, Digest. Unsigned, those can be relayed or tampered with; with LDAPServerIntegrity=2 the DC rejects the bind and the client gets LDAP result code 8, strongAuthRequired. Simple binds have no signature or seal to require, so the password crosses the wire in the clear unless TLS wraps it. Different counter, different fix: TLS plus SASL, not a signing value.

Channel binding is TLS-side. Under RFC 5929's tls-server-end-point, the client hashes the DC's TLS certificate into the authentication exchange and the DC recomputes that hash from its own certificate. A relay terminates TLS at the attacker, so the hashes differ and the bind dies with 0x80090346, SEC_E_BAD_BINDINGS. Plain 389 has no TLS channel to bind to, which is why LDAPS is a precondition. LdapEnforceChannelBinding=1 rejects a mismatched token but still accepts a client that sends no token; =2 rejects token-less clients too, and that is the step where JNDI Java and bare OpenLDAP clients stop working.

Instrument before enforcing

POWERSHELL
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\NTDS\Diagnostics' `
  -Name '16 LDAP Interface Events' -Value 2
Get-WinEvent -LogName 'Directory Service' -FilterHashtable @{Id=2886,2887,2889} -MaxEvents 100 |
  Select-Object TimeCreated, Id, Message

2887 counts unsecured SASL binds, 2889 unsecured simple binds, 2886 a bind downgraded from signed to unsigned. Each record carries the client address and the account, which is what turns "something is still binding in the clear" into an owner and a ticket. The owner list is the deliverable here, not the counter.

Phases (sample schedule; tune to the estate)

PhaseDC settingWho breaksExit criteria
1 measureintegrity 1, CBT 0nobodyevery binding client has an owner and a signed/unsigned verdict
2 CBT canaryCBT 1relays presenting a wrong token - that is the pointno unexplained 0x80090346
3 CBT enforceCBT 2token-less clients: JNDI Java, bare OpenLDAP, appliancesonly dated, documented exceptions remain
4 signing enforceintegrity 2unsigned SASL binds fail with strongAuthRequired2887 at zero outside the exception list

Pilot one site's DCs first, and enforce signing after channel binding; signing failures are noisier and would mask the CBT signal.

Worked failure. An app does a simple bind to ldaps://dc1:636 with a hard-coded service account. Phase 2 leaves it alone: JNDI sends no token. Phase 3 rejects the bind at the DC and the app logs error 49 with 0x80090346. In order of preference: move the app to a Kerberos/GSSAPI bind, front it with an LDAP proxy that speaks Kerberos to the DC, or pin it to one DC as a dated exception with a firewall rule limiting that host to 389/636.

When to delay or skip

Scope enforcement per DC through GPO on the DC OU, never forest-wide. Hold a DC back if LDAPS there isn't genuinely healthy - wrong SAN, broken chain, clients that don't trust the issuing CA - because channel binding on a bad listener breaks the clients that were doing the right thing. Hold the whole rollout if the last remaining client can't be changed and can't go behind a proxy; a compensating control (TLS-only, one DC, monitored) beats a broken authentication path. Rank exceptions by blast radius: failing on an authentication path is an incident, failing on a monitoring path is a missing log line.

Test explicitly: load balancers and reverse proxies that terminate and re-originate TLS, a listener certificate rotation, DC failover to a DC whose certificate has a different name, and the non-Windows clients from phase 3. Rollback is one registry value or GPO setting per DC, executable in minutes - though phases 1 and 2 should mean you never need it. Afterwards drop the diagnostic counter back down and let the exceptions expire; the two enforcement settings stay.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Migrate legacy directory service accounts.

Answer

What I'd say first

Assume an on-prem AD domain at Windows Server 2012 functional level or later, and that the accounts in scope are service accounts (non-interactive, used by daemons and scheduled tasks) not human logins. If the domain is older than 2012, gMSA isn't available and the target becomes a certificate or a platform workload identity instead; that one fact decides the whole plan.

The migration is: inventory what actually authenticates, pick a target credential per account, run old and new in parallel, cut over, then delete. Order matters because deletion is the only irreversible step.

Inventory: what to collect and why

Per account: owner, hosts and services that use it, SPNs, logon type, group membership and ACL rights, last use. Two specifics worth knowing:

  • lastLogonTimestamp is replicated but coarse, up to 9–14 days stale, so it answers "is this dead?" and not "did it stop yesterday". lastLogon is per-DC and not replicated; query every DC.
  • Logon type in 4624 tells you the shape: 3 = network, 4 = batch (scheduled task), 5 = service, 10 = RemoteInteractive. A service account showing type 2 or 10 is being used interactively, and that's the first thing to fix.

Choosing the target

targetuse whencost / when not
gMSAWindows service or task on domain-joined hosts, Kerberos-capableneeds 2012+ FL and a KDS root key; no NTLM, no interactive logon; one account can serve a farm
sMSAsingle host, pre-2012 FLno failover, deprecated: don't pick it for new work
certificatenon-Windows or cross-domain clients, TLS/mTLSyou own issuance and renewal; revocation needs CRL/OCSP reachable from every client
workload identityworkload runs in a cloud platform that supports federation for itremoves the secret entirely; only viable if the platform federates that workload

gMSA specifics: the password is 240 random characters, rotated every 30 days by default (-ManagedPasswordIntervalInDays, set at creation only, max 365). A host retrieves it only if it's in PrincipalsAllowedToRetrieveManagedPassword. Run Test-ADServiceAccount before cutover: it fails loudly if the host can't read the password.

Failure modes and how you see them

  • Duplicate SPN. Two accounts registered for the same SPN, so the KDC issues a ticket encrypted with the wrong account's key and the client gets KRB_AP_ERR_MODIFIED (0x7). Find them with setspn -X before and after cutover.
  • Stale Kerberos tickets. After an SPN or account change, clients hold tickets for the old principal until the TGT expires: 10 hours by default. klist purge on the client, or wait it out.
  • gMSA on a host not in the allowed-principals group: the service fails to start, password retrieval denied. Test-ADServiceAccount catches it.
  • NTLM-only application: gMSA doesn't do NTLM, so auth fails and the DC logs 4776. That's the signal to use a certificate instead.
  • Deleting the old account too early: a 4625/4776 storm from a caller you missed. Keep it disabled for 30–90 days and watch those events before deleting.

Sequence

Reduce privilege first: strip domain admin, block interactive logon with "Deny log on locally" and "Deny log on through Remote Desktop Services", restrict -LogonWorkstations. Then create the target, install and test it, run in parallel, cut over, verify with 4769 (Kerberos service ticket) and 4624 on the new identity, remove the old secret and SPN, then retire the account.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Implement urgent directory account containment.

Answer

Assumptions I'd state up front: hybrid AD + Entra ID, the account is privileged (helpdesk admin or a service account), and "urgent" means an active adversary. If it's a plain user with no privileged access, steps 4–6 collapse and you're done at step 3.

Containment is a sequence ordered by time-to-effect, not a checklist. Disabling the account is the fastest reversible control, but it only stops new authentication. Everything already issued (Kerberos tickets, OAuth refresh tokens, live sessions) keeps working until its own lifetime expires. So you disable first, then chase the artefacts that outlive the disable.

  1. Disable in AD (or block sign-in in Entra ID). Effective at the next KDC/IdP check.
  2. Revoke sessions: POST /users/{id}/revokeSignInSessions in Graph (older: Revoke-AzureADUserAllRefreshToken). Kills refresh tokens and browser cookies.
  3. Reset the password and rotate anything the account could read: service account passwords, gMSA, vault secrets it had access to.
  4. Remove privileged group memberships and delegation (AdminSDHolder, ACLs, AD delegation).
  5. Kill live sessions: RDP, VPN, SSH, WinRM. A live session doesn't re-authenticate.
  6. If the account could have read krbtgt (domain admin, or a DC compromise), rotate krbtgt twice with a full replication cycle between.

Why each step is needed: the lifecycle table:

artefactdefault lifetimekilled by disable?killed by
Kerberos TGT10 h (MaxTicketAge)noexpiry, or krbtgt rotation
Kerberos service ticket10 hno: the service validates it offline with its own keyexpiry
OAuth access token1 h (Entra)noexpiry
OAuth refresh tokenup to 90 days of inactivitynorevokeSignInSessions
Group membership in the PACuntil TGT renewal, ≤10 hnore-logon / TGT expiry
Live RDP/VPN sessionindefinitenosession kill

The window arithmetic. Worst case, a disabled account's access persists for replication lag + ticket lifetime. Intra-site AD replication is 15 s (change notification); inter-site is 180 min by default. Entra Connect syncs every 30 min by default. So a hybrid account disabled in AD can keep authenticating to Entra for ~30 min, and its existing service tickets stay valid for up to 10 h. That's the number to put in the incident timeline.

Failure modes and how to detect them:

  • Replication lag. Check repadmin /showrepl and repadmin /replsummary on the DC that holds the change. Watch for the account re-authenticating after the disable time (4624/4625 on the DC).
  • Service tickets validated offline. A service holding a valid ticket keeps accepting it with no KDC call. Correlate 4769 (TGS request) and 4624 on the target host after the disable timestamp.
  • Refresh tokens. Disable alone leaves the app silently refreshing. Detect in Entra sign-in logs by the refresh_token grant type.
  • Break-glass lockout. Don't disable the emergency access account. Keep two cloud-only break-glass accounts excluded from Conditional Access.
  • krbtgt rotation. One rotation leaves the old key valid; two rotations too fast break replication. Wait one full replication cycle (≥180 min inter-site) between them.

Trade-offs.

  • Disable vs delete. Delete frees the SID for reuse, loses the object's audit trail, and breaks any service bound to the SID. Disable is reversible; delete is not. Disable unless forensics says otherwise.
  • Revoke-all vs targeted. Revoke-all logs the user out of everything, including legitimate sessions, but it's the only way to kill refresh tokens you can't enumerate. Targeted revocation requires knowing the client IDs.
  • krbtgt rotation is the highest-cost control: it invalidates every TGT in the domain and causes a re-logon storm. Do it on evidence of ticket forgery (golden ticket), not for a routine account disable.

Measure: time from detection to first denied authentication (seconds), and time to last successful use of a pre-existing ticket (bounded by ticket lifetime). The gap between them is your containment window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design directory security monitoring and response.

Answer

Core answer (first 90 seconds)

Assume on-prem Active Directory with Tier 0 separation and a SIEM. The directory is the control plane: whoever can change groups, ACLs, trusts, GPOs, schema, or replication rights owns every system that trusts it. So the job is not "watch for bad logons": it is change detection on the control plane, plus a response path that can revoke authority in minutes.

Three things to get right: turn on the audit subcategories that actually record directory changes, alert on authority changes with enough context to judge intent, and rehearse containment and rollback before you need them.

What to watch, and why

SignalEvent ID / sourceWhy it mattersFirst response
Group membership change, direct or nested4728, 4732, 4756; 5136 on group objectsNested grants hide privilege: a user added to a group that is itself a member of Domain Admins is a Domain AdminRemove membership, check the transitive path, review actor
ACL or owner change on domain NC or AdminSDHolder5136, 4662 with SACLBackdoor persistence; AdminSDHolder re-applies every 60 minutes via SDPropRestore ACL from known-good, find the grantee
Replication rights granted to a non-DC4662 with GUIDs 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2, 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2, 89e95b76-444d-4c62-991a-0facbeda640cDCSync: attacker pulls password hashes without touching a DCRevoke the right, reset krbtgt twice, hunt the account
Trust create or modify4706, 4707, 4716Cross-domain access, SID filtering bypassRemove trust, review SID history
GPO link or content change5136 on GPO; SYSVOL file integrityGPO can push scripts, scheduled tasks, LAPS read rightsRestore from GPO backup, diff SYSVOL
Schema change5136 on schema NCRare, high impact; requires Schema AdminsTreat as incident, restore from backup
SPN added4742, 5136 with servicePrincipalNameKerberoasting targetRemove SPN, rotate account password
CA key access or cert issuance4886, 4887; CA key file accessGolden Certificate: forge certs for any userRevoke CA, rotate key, reissue
Audit policy change or log clear4719, 1102Attacker blinding youRe-enable, preserve off-box copy
DC software or service install7045, 4688Persistence on the DCIsolate DC, rebuild

Directory Service Changes is not on by default; enable it and set SACLs on Tier 0 objects, or 4662 and 5136 will not fire.

Tradeoffs

Build vs buy: Microsoft Sentinel with the Windows Security Events connector plus Sigma rules is cheap to start but you own the content and the tuning. Defender for Identity or a commercial AD change auditor gives pre-built detections (DCSync, honey accounts, reconnaissance) and less false-positive work, at per-DC or per-user cost. Pick on team size, not tool fashion.

Fidelity vs volume: 4662 fires constantly on a busy DC. Scope SACLs to Tier 0 objects and replication GUIDs; do not ingest every object-access event. A rule that alerts on any 4662 gets muted within a week.

When full ACL monitoring is not worth it: with no Tier 0 separation and no change process, ACL alerts are noise. Fix the process first, or you train the team to ignore the alerts.

Failure modes

  • Nested group grants missed: alerting only on direct Domain Admins membership. Use recursive membership queries and alert on the transitive path.
  • AD Recycle Bin hiding deletions: a deleted object is restorable, and 4726 may be the only signal. Monitor 4726 and 5136 with isDeleted, and treat restore as a change.
  • DCSync from a member server: 4662 with replication GUIDs from a non-DC source. Alert on any, not on a threshold.
  • Golden Certificate: CA private key theft leaves no AD event. Monitor CA key file access and unexpected certificate issuance.
  • Alert fatigue: no owner, no runbook, alerts closed as benign. Track mean time to acknowledge and false-positive rate per rule.

Response

  1. Triage: approved change? Check ticket, actor, source host, session. If not approved, treat as incident.
  2. Contain: disable the account, remove the membership or right, revoke the trust, restore the GPO. For DCSync, reset krbtgt twice (second reset at least 10 hours after the first) and invalidate sessions.
  3. Rollback: AD Recycle Bin restore for deleted objects; authoritative restore from backup if schema or DC is compromised.
  4. Escalate: Tier 0 incident, identity team, preserve evidence. Export security log, snapshot the DC, capture memory if you suspect code execution.
  5. Eradicate: hunt persistence. AdminSDHolder, SID history, ACL backdoors, shadow credentials (msDS-KeyCredentialLink), DCSync rights.

Check

POWERSHELL
# Non-DC principals with replication rights on the domain NC
$nc = "DC=corp,DC=example,DC=com"
(Get-Acl "AD:$nc").Access | Where-Object {
  $_.ObjectType -in @(
    '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2', # Replicating Directory Changes
    '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2', # Replicating Directory Changes All
    '89e95b76-444d-4c62-991a-0facbeda640c'  # Replicating Directory Changes In Filtered Set
  )
} | Select-Object IdentityReference, ObjectType, ActiveDirectoryRights

Run it against each naming context. Any identity that is not a DC computer account is a finding.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and exercise directory forest recovery.

Answer

The 90-second answer. Forest recovery rebuilds the whole AD forest from backup after compromise or corruption has reached every domain controller. Assume the attacker held Domain Admin or Enterprise Admin, so nothing running is trusted: accounts, GPOs, trusts, the krbtgt key. The design has two halves: a restore order that never lets an unvalidated DC replicate, and an exercise that proves that order works before you need it. Restore one DC per domain from isolated media, fence it so it cannot replicate, validate it, then bring the rest back and reconcile downstream identities.

Why order matters: worked trace. AD resolves replication conflicts by object version number, highest wins. Take CN=Jane Doe,OU=Finance,DC=corp,DC=example,DC=com. The attacker added her to Domain Admins on DC2; the DC1 backup predates that.

Object stateversionNumberWhere it lives
Pre-attack (backup)4,123,450DC1, restored
Post-attack (attacker's edit)4,123,456DC2, live

Restore DC1 non-authoritatively and let it replicate: DC2's 4,123,456 beats DC1's 4,123,450, so the attacker's edit survives and re-infects the forest. Authoritative restore of the subtree on DC1 bumps the version by 100,000: 4,123,450 + 100,000 = 4,223,450. Now DC1 outranks DC2 and its copy wins on every partner. That arithmetic is the whole reason the first DC is fenced and the restore is scoped.

Fencing. After the System State restore and before reboot, set DSA Not Writable = 1 under HKLM\SYSTEM\CurrentControlSet\Services\NTDS\Parameters. The DC comes up serving reads but refusing inbound replication: a partner pushing changes gets 8453 (replication access was denied). Clear the flag only after validation passes.

Restore sequence.

  1. Boot the first DC into DSRM (F8, log in as .\Administrator with the DSRM password set at promotion). wbadmin start systemstaterecovery -version:<id> -authsysvol: -authsysvol makes SYSVOL authoritative so GPOs don't merge with a stale copy.
  2. Set DSA Not Writable, reboot into normal mode.
  3. Authoritative restore only for objects that must win: ntdsutil → authoritative restore → restore subtree "OU=Finance,DC=corp,DC=example,DC=com". Whole-forest authoritative restore is rarely needed and expensive.
  4. Seize FSMO roles if the holders are gone: ntdsutil → roles → seize.
  5. Restore remaining DCs non-authoritatively, one per domain, then metadata-cleanup the dead ones.
  6. Reset krbtgt twice with replication between, so every ticket minted under the old key dies. Reset every DSRM password.

Validation gates. dcdiag /v; repadmin /showrepl and /replsummary; SYSVOL share and DFSR backlog; netdom trust /verify; w32tm /monitor: Kerberos fails past the 5-minute default clock skew, so time must be right before anything authenticates.

Trade-offs. A scoped authoritative restore of one OU costs minutes and is right when corruption is contained and the rest of the forest is trusted. A full forest restore costs days and is right when it isn't. Rebuilding a new forest and migrating is the fallback when backups are themselves compromised or older than the business can accept.

Exercise design. Tabletop first: who declares forest recovery, who can authorize taking production offline. Then a full lab drill on an isolated network with no route to production, using real backups and recovery credentials that don't exist in the production forest. Participants: AD engineers, backup, network, IR, app owners, comms. Injects that hurt: newest backup is 26 hours old; DSRM password unknown; PDC emulator's backup corrupt; a rogue DC still online. Measure time to first DC restored, time to forest functional, achieved RPO against target.

Hypothetical drill figures, labelled: first DC restored in 4 h, forest functional in 31 h, RPO 26 h against a 24 h target. The miss is the finding.

Curated: · Written: · Reviewed:

Difficulty: Hard