TExcelTAD
Home › Windows & Active Directory Security › LDAP, the Schema and userAccountControl

LDAP, the Schema and userAccountControl

By default, every authenticated user can read most of Active Directory: all users, groups, computers, group memberships, which accounts have service principal names, which ones don't require Kerberos pre-authentication, which computers are trusted for delegation. That openness is what makes AD easy to use, and it is why the first thing an intruder does with any domain account is query LDAP. Collectors such as BloodHound's SharpHound, PowerView or Impacket's LDAP examples are, at their core, well-chosen LDAP filters. The same filters are the defender's audit queries. This lesson teaches you to read and write them, and to decode the one attribute that answers half of them: userAccountControl.

LDAP on the wire (BER encoding, bind types, signing) is in LDAP and Kerberos on the Wire; the AD PowerShell cmdlets in PowerShell on Windows.

The schema in one paragraph

The schema defines every object class (user, computer, group, groupPolicyContainer, pKICertificateTemplate…) and every attribute, with its syntax and flags. It is shared by the whole forest, extended by products (Exchange, LAPS, AD CS) and changeable only by Schema Admins on the schema master, and changes can't be undone. Two schema flags matter for security: attributes marked confidential (searchFlags bit 0x80) are readable only with an extra control-access right, which is how the legacy LAPS password attribute was protected; attributes in the RODC filtered attribute set never replicate to read-only DCs.

Filters

An LDAP search has a base DN, a scope and a filter in prefix notation (RFC 4515):

Filter Meaning
(objectClass=user) equality
(servicePrincipalName=*) presence: the attribute has any value
(&(a=1)(b=2)), (|(a=1)(b=2)), (!(a=1)) and, or, not
(userAccountControl:1.2.840.113556.1.4.803:=4194304) bitwise AND matching rule: all these bits set
(memberOf:1.2.840.113556.1.4.1941:=CN=Domain Admins,CN=Users,DC=corp,DC=lab,DC=test) in chain: membership through any depth of nesting

userAccountControl

userAccountControl (UAC, unrelated to User Account Control) is a 32-bit field of flags. The security-relevant bits:

Bit (hex) Name Why a reviewer cares
0x2 ACCOUNTDISABLE disabled accounts: ignore, or delete if stale
0x20 PASSWD_NOTREQD the account may have an empty password
0x80 ENCRYPTED_TEXT_PWD_ALLOWED password stored with reversible encryption
0x200 NORMAL_ACCOUNT a user
0x1000 / 0x2000 WORKSTATION_TRUST_ACCOUNT / SERVER_TRUST_ACCOUNT computer / domain controller
0x10000 DONT_EXPIRE_PASSWORD password never expires
0x80000 TRUSTED_FOR_DELEGATION unconstrained delegation (Delegation)
0x100000 NOT_DELEGATED "account is sensitive and cannot be delegated": good for admins
0x200000 USE_DES_KEY_ONLY DES Kerberos keys only: obsolete
0x400000 DONT_REQ_PREAUTH no Kerberos pre-authentication: AS-REP roastable (Roasting)
0x1000000 TRUSTED_TO_AUTH_FOR_DELEGATION constrained delegation with protocol transition

Audit queries on a synthetic directory

The program implements a small LDAP filter evaluator (equality, presence, and, or, not, the bitwise matching rule) and runs the classic audit filters against a synthetic export of corp.lab.test. Every query here is one a defender should run regularly; it is also, character for character, what reconnaissance tools send.

python · try it yourself
import re

FLAGS = {0x2: "ACCOUNTDISABLE", 0x20: "PASSWD_NOTREQD", 0x80: "ENCRYPTED_TEXT_PWD_ALLOWED",
         0x200: "NORMAL_ACCOUNT", 0x1000: "WORKSTATION_TRUST_ACCOUNT", 0x2000: "SERVER_TRUST_ACCOUNT",
         0x10000: "DONT_EXPIRE_PASSWORD", 0x80000: "TRUSTED_FOR_DELEGATION", 0x100000: "NOT_DELEGATED",
         0x400000: "DONT_REQ_PREAUTH", 0x1000000: "TRUSTED_TO_AUTH_FOR_DELEGATION"}

def decode(uac):
    return "|".join(name for bit, name in FLAGS.items() if uac & bit)

directory = [
    {"sAMAccountName": "alice", "userAccountControl": 0x200, "adminCount": 1},
    {"sAMAccountName": "svc-sql", "userAccountControl": 0x10200, "servicePrincipalName": ["MSSQLSvc/sql01.corp.lab.test:1433"]},
    {"sAMAccountName": "svc-legacy", "userAccountControl": 0x410200},
    {"sAMAccountName": "kiosk", "userAccountControl": 0x220},
    {"sAMAccountName": "old-intern", "userAccountControl": 0x202},
    {"sAMAccountName": "DC01
quot;, "userAccountControl": 0x82000}, {"sAMAccountName": "FS01
quot;, "userAccountControl": 0x81000}, {"sAMAccountName": "WS01
quot;, "userAccountControl": 0x1000}, ] TOKEN = re.compile(r"\(|\)|[&|!]|[^()]+") def parse(f): toks = TOKEN.findall(f) pos = 0 def node(): nonlocal pos assert toks[pos] == "("; pos += 1 if toks[pos] in "&|!": op = toks[pos]; pos += 1 kids = [] while toks[pos] == "(": kids.append(node()) pos += 1 return (op, kids) item = toks[pos]; pos += 2 return ("item", item) return node() def match(n, obj): kind, val = n if kind == "&": return all(match(k, obj) for k in val) if kind == "|": return any(match(k, obj) for k in val) if kind == "!": return not match(val[0], obj) attr, _, want = val.partition("=") if attr.endswith(":1.2.840.113556.1.4.803:"): # bitwise AND rule bits = int(want) return obj.get(attr.split(":")[0], 0) & bits == bits if want == "*": return attr in obj v = obj.get(attr) return str(want).lower() in [str(x).lower() for x in (v if isinstance(v, list) else [v])] ENABLED = "(!(userAccountControl:1.2.840.113556.1.4.803:=2))" audits = { "Kerberoastable users": f"(&(servicePrincipalName=*)(userAccountControl:1.2.840.113556.1.4.803:=512){ENABLED})", "AS-REP roastable": f"(&(userAccountControl:1.2.840.113556.1.4.803:=4194304){ENABLED})", "password not required": f"(&(userAccountControl:1.2.840.113556.1.4.803:=32){ENABLED})", "unconstrained delegation (non-DC)": "(&(userAccountControl:1.2.840.113556.1.4.803:=524288)(!(userAccountControl:1.2.840.113556.1.4.803:=8192)))", "protected by adminCount": "(adminCount=1)", } for title, flt in audits.items(): tree = parse(flt) hits = [o["sAMAccountName"] for o in directory if match(tree, o)] print(f"{title:34} {', '.join(hits) or '-'}") print() for o in directory[1:6]: print(f"{o['sAMAccountName']:11} 0x{o['userAccountControl']:07x} = {decode(o['userAccountControl'])}")
Kerberoastable users               svc-sql
AS-REP roastable                   svc-legacy
password not required              kiosk
unconstrained delegation (non-DC)  FS01$
protected by adminCount            alice

svc-sql     0x0010200 = NORMAL_ACCOUNT|DONT_EXPIRE_PASSWORD
svc-legacy  0x0410200 = NORMAL_ACCOUNT|DONT_EXPIRE_PASSWORD|DONT_REQ_PREAUTH
kiosk       0x0000220 = PASSWD_NOTREQD|NORMAL_ACCOUNT
old-intern  0x0000202 = ACCOUNTDISABLE|NORMAL_ACCOUNT
DC01$       0x0082000 = SERVER_TRUST_ACCOUNT|TRUSTED_FOR_DELEGATION

Each hit is a finding with a known fix: svc-sql needs a long random password or a gMSA, svc-legacy needs pre-authentication turned back on, kiosk must get a password (and lose the flag), and FS01$ should move to constrained delegation. DC01$ has unconstrained delegation by design: domain controllers always do, which is why the query excludes SERVER_TRUST_ACCOUNT. alice is listed by adminCount=1, which marks accounts that are, or once were, members of protected groups (Stale and Privileged Accounts).

How reconnaissance is detected

The queries are legitimate, so detection is about who, from where, and how much:

  • Field engineering logging on DCs (the 15 Field Engineering diagnostics value set to 5, plus thresholds) writes Directory Service event 1644 for expensive, inefficient or slow searches, including the filter and the client address. A workstation sending (servicePrincipalName=*) or the DONT_REQ_PREAUTH filter is worth a look; a burst of searches for all users, groups, computers and ACLs from one host, followed by session enumeration against many machines, is the signature of a collector such as SharpHound.
  • Network sensors (Microsoft Defender for Identity, Zeek with an LDAP analyser) profile LDAP queries per source and flag enumeration patterns.
  • Honey objects: a decoy user with an SPN or a decoy admin that no legitimate process ever reads; with a SACL for read access, any 4662 on it is an alert (Honeytokens).
  • SAMR enumeration (net user /domain, session enumeration) shows up as 4661/5145 on DCs and members.

How it is hardened

  • Fix what the audit queries find; then the queries return nothing useful to an attacker either.
  • Restrict anonymous LDAP (the dsHeuristics value should not allow anonymous operations); require LDAP signing and channel binding on DCs.
  • Remove "Authenticated Users" read on sensitive attributes and OUs where business allows (for example on Tier 0 OUs or on msDS-AllowedToActOnBehalfOfOtherIdentity); mark secret-carrying attributes confidential.
  • Restrict session enumeration (NetSessionEnum) on servers and workstations, which feeds attack-path tools with "who is logged on where".
  • Keep Schema Admins empty.

Pitfalls

  • Decimal vs hex. LDAP filters take decimal (4194304), documentation lists hex (0x400000). Converting wrongly silently returns nothing.
  • Forgetting disabled accounts, or forgetting that a disabled account can be re-enabled by anyone with write rights on it.
  • Relying on adminCount for "current admins": the flag stays at 1 after an account leaves the protected groups.
  • memberOf without the in-chain rule misses nested memberships.

Practice

1. Decode 0x410200.

0x400000 DONT_REQ_PREAUTH + 0x10000 DONT_EXPIRE_PASSWORD + 0x200 NORMAL_ACCOUNT: an enabled user whose password never expires and who can be AS-REP roasted.

2. Write a filter for enabled users with constrained delegation and protocol transition.

(&(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=16777216)(!(userAccountControl:1.2.840.113556.1.4.803:=2))) (16777216 = 0x1000000). Add (msDS-AllowedToDelegateTo=*) to list only accounts that have targets.

3. Why is (servicePrincipalName=*) from a single workstation not proof of an attack?

Admin tools, monitoring and audits run it too. Context decides: the account (an admin on a PAW or a regular user?), the time, the source, and whether ticket requests for those SPNs follow (4769 bursts).

Test yourself

Which userAccountControl bit means 'Kerberos pre-authentication not required'?

  1. 0x2
  2. 0x20
  3. 0x80000
  4. 0x400000

What does the matching rule OID 1.2.840.113556.1.4.803 do in an LDAP filter?

  1. Case-insensitive match
  2. Bitwise AND: all given bits are set
  3. Nested group membership
  4. Wildcard match

Why do all domain controllers show TRUSTED_FOR_DELEGATION?

  1. Misconfiguration
  2. DCs have unconstrained delegation by design; audit queries exclude SERVER_TRUST_ACCOUNT
  3. Because they are RODCs
  4. It means they are disabled

Which Directory Service event, with field engineering logging enabled, records expensive or inefficient LDAP searches with their filter?

  1. 2889
  2. 1644
  3. 4662
  4. 4769