Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 2

Windows Telemetry for Credential Theft and Lateral Movement

Turn on the Windows telemetry that credential-theft and lateral-movement attacks disturb (advanced audit subcategories, a Sysmon config for lsass, PowerShell 4104), then run Python detections over a shipped JSONL of Security and Sysmon events for Kerberoasting (4769), AS-REP roasting (4768), DCSync (4662), pass-the-hash (4624) and lsass access (Sysmon 10). Each detection has a benign record it must not alert on.

Contentsand lesson path

What you will learn

  • Enable Windows security telemetry (advanced audit policy, Sysmon, PowerShell script block logging) and recognise credential theft and lateral movement such as pass-the-hash, Kerberoasting, DCSync and living-off-the-land binary abuse in the resulting events.

01. Goal and setup

Most attacks on credentials and lateral movement disturb a small set of Windows logs. In this lab you first turn on the telemetry that records them, then write Python detections that find five techniques in a fixed sample of events while staying quiet on benign records that look similar. The detections are the verifiable core you run here; the telemetry steps change a Windows host, so they are marked as not reproducible on this sandbox, with the configuration shown.

The sample is events.jsonl, one JSON object per line in the shape of Get-WinEvent | ConvertTo-Json with the EventData fields flattened to top-level keys. All records are synthetic: documentation IP ranges (192.0.2.0/24), example.invalid names and made-up accounts. A generator builds it, so the data is fixed and your output matches.

You need Python 3.10 or later, standard library only, and a folder detect-lab.

02. Step 1: Turn on the telemetry

Default audit settings vary by Windows version and server role, and may not record everything these detections need, so set the advanced audit subcategories that carry the fields you need explicitly. These commands run on your lab hosts (by Group Policy in a real domain); they are not reproducible in this sandbox. The subcategory names are the verified ones from the Microsoft audit-policy recommendations.

PowerShell · on your lab hosts (illustrative)
auditpol /set /subcategory:'Kerberos Service Ticket Operations' /success:enable
auditpol /set /subcategory:'Kerberos Authentication Service' /success:enable
auditpol /set /subcategory:'Directory Service Access' /success:enable
auditpol /set /subcategory:'Logon' /success:enable /failure:enable
auditpol /set /subcategory:'Process Creation' /success:enable

Each subcategory produces specific events. Kerberos Service Ticket Operations gives 4769 (a service ticket was requested), with the service name and ticket encryption type. Kerberos Authentication Service gives 4768 (a TGT was requested), with the pre-authentication type. Directory Service Access gives 4662 (an operation was performed on an object) on a DC. Logon gives 4624 (a successful logon), with the logon type and authentication package. Process Creation gives 4688; also turn on Include command line in process creation events.

Two subtleties matter. Event 4662 only fires if a system access control list (SACL) is set on the object being watched, so to detect DCSync you must add an audit entry on the domain naming context for the replication rights. And after the CVE-2026-20833 change (KB5073381), DCs assume AES for accounts without an explicit msDS-SupportedEncryptionTypes, so an RC4-only Kerberoasting rule weakens; the detection below also counts distinct service tickets per account.

Add Sysmon, a free Sysinternals service that writes process telemetry to its own event log. Event ID 1 records process creation with the full command line and parent, and Event ID 10 (ProcessAccess) records when one process opens another, which is how you catch a tool reading the memory of lsass.exe, the process that holds credentials. Event 10 carries the SourceImage and TargetImage paths, the GrantedAccess mask and a CallTrace, but no signature field: Sysmon records signatures for driver and image loads (events 6 and 7).

Each event type in a Sysmon config has a filter with onmatch="include" (log only events that match a rule) or onmatch="exclude" (log everything except events that match); when both exist, an exclude match wins. The config below logs every process creation through an empty exclude filter, and only handles opened to lsass through an include filter. A common practice is to start broad and add narrow exclusions from your own baseline, because excluded events cannot be recovered later.

XML · detect-lab/sysmon-lsass.xml (illustrative)
<Sysmon schemaversion="4.82">
  <HashAlgorithms>SHA256</HashAlgorithms>
  <EventFiltering>
    <!-- Event 1: an empty exclude filter logs every process creation -->
    <ProcessCreate onmatch="exclude" />
    <!-- Event 10: an include filter logs only handles opened to lsass.exe -->
    <ProcessAccess onmatch="include">
      <TargetImage condition="image">lsass.exe</TargetImage>
    </ProcessAccess>
    <!-- Add narrow exclude rules later, from your own baseline: -->
    <!-- an exclude match wins over an include match for the same event -->
  </EventFiltering>
</Sysmon>

Finally, enable PowerShell script block logging, which records the content of every script block as event 4104 in the Microsoft-Windows-PowerShell/Operational log. The next lesson uses 4104 in depth; here it is enough to know it is on.

03. Step 2: Build the sample events

Save the generator as make_events.py. Read its comments: they mark which records are benign and which are the attack traces, so you can check each detection against a near-miss. Run it to write events.jsonl.

Python · detect-lab/make_events.py
"""Write events.jsonl: a fixed set of Windows Security and Sysmon records.

The shape is one JSON object per line, as if each record from
`Get-WinEvent | ConvertTo-Json` had its EventData flattened to top-level keys.
All data is synthetic: documentation IP ranges (192.0.2.0/24), example.invalid
names and made-up accounts. No real host or account appears.
"""
import json

E = []


def add(**kw):
    E.append(kw)


DC = "DC01.example.invalid"
WS = "WKS07.example.invalid"
FS = "FS01.example.invalid"
GET_CHANGES = "{1131f6aa-9c07-11d1-f79f-00c04fc2dcd2}"
GET_CHANGES_ALL = "{1131f6ad-9c07-11d1-f79f-00c04fc2dcd2}"
DOMAIN_DNS = "{19195a5b-6da0-11d0-afd3-00c04fd930c9}"   # class of the domain object
LSASS = "C:\\Windows\\System32\\lsass.exe"


def k4769(t, user, svc, enc, ip):
    add(Id=4769, Time=t, Computer=DC, TargetUserName=user, ServiceName=svc,
        TicketEncryptionType=enc, Status="0x0", IpAddress=ip)


def k4768(t, user, pre, enc, ip):
    add(Id=4768, Time=t, Computer=DC, TargetUserName=user, PreAuthType=pre,
        TicketEncryptionType=enc, Status="0x0", IpAddress=ip)


def e4662(t, subj, right):
    # %%7688 is the message code for Control Access; then the right, then the class.
    add(Id=4662, Time=t, Computer=DC, SubjectUserName=subj, AccessMask="0x100",
        AccessList="%%7688", Properties=f"%%7688\n\t\t{right}\n\t{DOMAIN_DNS}\n")


def e4624(t, host, user, ltype, pkg, sid, ip):
    add(Id=4624, Time=t, Computer=host, TargetUserName=user, LogonType=ltype,
        AuthenticationPackageName=pkg, LmPackageName="NTLM V2",
        KeyLength="0", SubjectUserSid=sid, IpAddress=ip)


def sysmon10(t, src, access, trace):
    add(Id=10, Channel="Sysmon", Time=t, Computer=WS, SourceImage=src,
        TargetImage=LSASS, GrantedAccess=access, CallTrace=trace)


# --- 4769 service-ticket requests ---------------------------------------------
# Benign: a user and a machine request a few tickets (AES), plus a krbtgt renewal.
k4769("2026-11-16T08:01:00Z", "[email protected]", "FS01", "0x12", "192.0.2.31")
k4769("2026-11-16T08:02:00Z", "[email protected]", "krbtgt", "0x12", "192.0.2.31")
k4769("2026-11-16T08:05:00Z", "[email protected]", "APP01$", "0x12", "192.0.2.40")
# Suspicious: one account asks for tickets to many distinct service accounts fast.
SPNS = ["MSSQLSvc01", "MSSQLSvc02", "HTTP-intranet", "HTTP-reports",
        "CIFS-archive", "svc-backup", "svc-jenkins", "svc-vcenter"]
for i, spn in enumerate(SPNS):
    enc = "0x17" if i % 2 == 0 else "0x12"    # mixed: an RC4-only rule misses half
    k4769(f"2026-11-16T09:{10 + i:02d}:00Z", "[email protected]", spn, enc,
          "192.0.2.77")

# --- 4768 TGT requests (AS-REP roasting signal = PreAuthType 0) ----------------
k4768("2026-11-16T08:00:10Z", "amira", "2", "0x12", "192.0.2.31")
k4768("2026-11-16T08:03:00Z", "ceo-smartcard", "15", "0x12", "192.0.2.33")
k4768("2026-11-16T09:40:00Z", "legacy-scan", "0", "0x17", "192.0.2.77")

# --- 4662 object access (DCSync = replication rights used) --------------------
# One event per right, as a DC writes them. Benign: a real DC replicating, and
# the Entra Connect sync account (allow-listed by its exact name).
e4662("2026-11-16T08:10:00Z", "DC02$", GET_CHANGES)
e4662("2026-11-16T08:10:00Z", "DC02$", GET_CHANGES_ALL)
e4662("2026-11-16T08:12:00Z", "MSOL_a1b2c3d4e5f6", GET_CHANGES)
e4662("2026-11-16T08:12:00Z", "MSOL_a1b2c3d4e5f6", GET_CHANGES_ALL)
# Suspicious: a workstation's machine account, and a normal user, replicating.
e4662("2026-11-16T09:50:00Z", "WKS07$", GET_CHANGES_ALL)
e4662("2026-11-16T09:55:00Z", "jpeters", GET_CHANGES)
e4662("2026-11-16T09:55:00Z", "jpeters", GET_CHANGES_ALL)

# --- 4624 logons (pass-the-hash = NTLM network logon, no prior credential) ----
# Benign: an interactive Kerberos logon, and an ANONYMOUS NTLM logon to ignore.
add(Id=4624, Time="2026-11-16T08:00:00Z", Computer=WS, TargetUserName="amira",
    LogonType="2", AuthenticationPackageName="Kerberos", LmPackageName="-",
    KeyLength="0", SubjectUserSid="S-1-5-18", IpAddress="192.0.2.31")
e4624("2026-11-16T08:20:00Z", FS, "ANONYMOUS LOGON", "3", "NTLM", "S-1-0-0",
      "192.0.2.50")
# Suspicious: NTLM network logon with a NULL subject SID and zero key length.
e4624("2026-11-16T10:05:00Z", FS, "Administrator", "3", "NTLM", "S-1-0-0",
      "192.0.2.77")

# --- Sysmon EventID 10 (ProcessAccess) on lsass.exe ---------------------------
# Benign: a known system opener, and a backup agent asking only to query (0x1000).
sysmon10("2026-11-16T08:30:00Z", "C:\\Windows\\System32\\svchost.exe", "0x1000",
         "C:\\Windows\\SYSTEM32\\ntdll.dll+...")
sysmon10("2026-11-16T08:40:00Z", "C:\\Program Files\\Contoso\\bkagent.exe",
         "0x1000", "C:\\Windows\\SYSTEM32\\ntdll.dll+...")
# Suspicious: a look-alike name in a writable folder, and a tool in a user folder,
# both asking for memory read (0x10 is part of 0x1010).
sysmon10("2026-11-16T10:11:00Z", "C:\\Windows\\Temp\\svchost.exe", "0x1010",
         "C:\\Windows\\SYSTEM32\\ntdll.dll+...|UNKNOWN(...)")
sysmon10("2026-11-16T10:12:00Z", "C:\\Users\\jpeters\\Temp\\d.exe", "0x1010",
         "C:\\Windows\\SYSTEM32\\ntdll.dll+...|UNKNOWN(...)")

with open("events.jsonl", "w") as fh:
    fh.writelines(json.dumps(e) + "\n" for e in E)
print(len(E), "events written to events.jsonl")
Terminal
cd detect-lab
python3 make_events.py
Expected output
28 events written to events.jsonl

04. Step 3: Run the detections

detect.py holds five detections. Each prints ALERT for a suspicious record and ok for the benign near-miss it correctly ignores, so the false-positive control is visible in the output. Save it and run it.

Python · detect-lab/detect.py
"""Five detections over events.jsonl, each with a built-in benign check.

Every rule prints ALERT lines for suspicious records and ok lines for the
near-misses it correctly ignores, so you can see the false-positive control
working. Thresholds and allow-lists are lab values; build yours from your data.
"""
import json
import re
from collections import defaultdict

AES = {"0x11", "0x12"}                       # AES128, AES256
REPL_RIGHTS = {"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2": "Get-Changes",
               "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2": "Get-Changes-All"}
GUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
KERBEROAST_MIN_SPNS = 6                       # distinct service names from one account
KNOWN_DCS = {"dc01$", "dc02$"}                # this lab's domain controllers
DCSYNC_ALLOW = {"msol_a1b2c3d4e5f6"}          # the exact Entra Connect sync account
LSASS_OPENERS = {                             # full paths seen in this lab's baseline
    "c:\\windows\\system32\\svchost.exe",
    "c:\\windows\\system32\\wininit.exe",
    "c:\\windows\\system32\\csrss.exe",
}
PROCESS_VM_READ = 0x10                        # access right needed to read memory

events = [json.loads(line) for line in open("events.jsonl")]
by_id = defaultdict(list)
for e in events:
    by_id[e["Id"]].append(e)


def is_machine(name):
    return name.split("@")[0].endswith("$")


print("== Kerberoasting (T1558.003) over 4769 ==")
tickets = defaultdict(list)
for e in by_id[4769]:
    svc = e["ServiceName"]
    if svc == "krbtgt" or svc.endswith("$") or is_machine(e["TargetUserName"]):
        continue                              # renewals and machine traffic are normal
    tickets[e["TargetUserName"]].append(e)
for user, evs in sorted(tickets.items()):
    spns = {e["ServiceName"] for e in evs}
    rc4 = [e for e in evs if e["TicketEncryptionType"] not in AES]
    if len(spns) >= KERBEROAST_MIN_SPNS or rc4:
        print(f"ALERT {user}: {len(evs)} tickets, {len(spns)} distinct SPNs, "
              f"{len(rc4)} non-AES")
    else:
        print(f"ok    {user}: {len(evs)} tickets, {len(spns)} distinct SPNs")

print("== AS-REP roasting (T1558.004) over 4768 ==")
for e in by_id[4768]:
    if e["PreAuthType"] == "0":
        print(f"ALERT {e['TargetUserName']}: TGT requested with pre-auth disabled "
              f"(enc {e['TicketEncryptionType']})")
    else:
        print(f"ok    {e['TargetUserName']}: pre-auth type {e['PreAuthType']}")

print("== DCSync (T1003.006) over 4662 ==")
rights_by_subject = defaultdict(set)
for e in by_id[4662]:
    guids = GUID.findall(e["Properties"].lower())   # ignores braces and %% codes
    used = {REPL_RIGHTS[g] for g in guids if g in REPL_RIGHTS}
    if used:
        rights_by_subject[e["SubjectUserName"]] |= used
for subj, used in rights_by_subject.items():
    names = "+".join(sorted(used))
    if subj.lower() in KNOWN_DCS or subj.lower() in DCSYNC_ALLOW:
        print(f"ok    {subj}: {names} (a known DC or the sync account)")
    else:
        print(f"ALERT {subj}: {names} by an account that is not a known DC")

print("== Pass-the-hash (T1550.002) over 4624 ==")
for e in by_id[4624]:
    ntlm = e["AuthenticationPackageName"] == "NTLM"
    pth = (e["LogonType"] == "3" and ntlm and e["SubjectUserSid"] == "S-1-0-0"
           and e["KeyLength"] == "0")
    if pth and e["TargetUserName"] != "ANONYMOUS LOGON":
        print(f"ALERT {e['TargetUserName']} on {e['Computer']}: NTLM network logon "
              f"from {e['IpAddress']}")
    elif e["TargetUserName"] == "ANONYMOUS LOGON":
        print(f"ok    {e['TargetUserName']}: ignored (expected on the network)")
    else:
        print(f"ok    {e['TargetUserName']}: {e['AuthenticationPackageName']} "
              f"type {e['LogonType']}")

print("== LSASS access (T1003.001) over Sysmon event 10 ==")
for e in by_id[10]:
    if not e["TargetImage"].lower().endswith("\\lsass.exe"):
        continue
    src = e["SourceImage"]
    access = int(e["GrantedAccess"], 16)
    if src.lower() in LSASS_OPENERS:
        print(f"ok    {src}: known opener in the lab baseline")
    elif not access & PROCESS_VM_READ:
        print(f"ok    {src}: query only ({e['GrantedAccess']}), no memory read")
    else:
        print(f"ALERT {src}: memory read on lsass (access {e['GrantedAccess']})")
Terminal
python3 detect.py
Expected output
== Kerberoasting (T1558.003) over 4769 ==
ok    [email protected]: 1 tickets, 1 distinct SPNs
ALERT [email protected]: 8 tickets, 8 distinct SPNs, 4 non-AES
== AS-REP roasting (T1558.004) over 4768 ==
ok    amira: pre-auth type 2
ok    ceo-smartcard: pre-auth type 15
ALERT legacy-scan: TGT requested with pre-auth disabled (enc 0x17)
== DCSync (T1003.006) over 4662 ==
ok    DC02$: Get-Changes+Get-Changes-All (a known DC or the sync account)
ok    MSOL_a1b2c3d4e5f6: Get-Changes+Get-Changes-All (a known DC or the sync account)
ALERT WKS07$: Get-Changes-All by an account that is not a known DC
ALERT jpeters: Get-Changes+Get-Changes-All by an account that is not a known DC
== Pass-the-hash (T1550.002) over 4624 ==
ok    amira: Kerberos type 2
ok    ANONYMOUS LOGON: ignored (expected on the network)
ALERT Administrator on FS01.example.invalid: NTLM network logon from 192.0.2.77
== LSASS access (T1003.001) over Sysmon event 10 ==
ok    C:\Windows\System32\svchost.exe: known opener in the lab baseline
ok    C:\Program Files\Contoso\bkagent.exe: query only (0x1000), no memory read
ALERT C:\Windows\Temp\svchost.exe: memory read on lsass (access 0x1010)
ALERT C:\Users\jpeters\Temp\d.exe: memory read on lsass (access 0x1010)

05. Step 4: Read each detection

Kerberoasting (T1558.003) requests service tickets for accounts that have an SPN, then tries password guesses against them offline. The trace is a burst of 4769 events from one account for many different services. The rule groups 4769 by requesting account, ignoring krbtgt renewals and machine accounts (names ending in $), and alerts on many distinct service names or any non-AES ticket. amira asked for one ticket and stays ok; jpeters asked for eight distinct services, half of them RC4, and alerts. Counting distinct SPNs keeps the rule working now that RC4 is no longer the default.

AS-REP roasting (T1558.004) targets accounts with pre-authentication disabled. The KDC answers a TGT request for such an account without proof of the password, and part of its reply (the AS-REP) is encrypted with a key derived from the password, so it can be guessed offline. In 4768 the signal is PreAuthType = 0. The smart-card user (type 15) and the normal user (type 2) stay ok; legacy-scan alerts.

DCSync (T1003.006) abuses directory replication rights to pull password hashes from a DC, including krbtgt. In 4662 the signal is a replication extended-right GUID in Properties. A real record writes that field as an access code such as %%7688 (Control Access), the right's GUID in braces, then the class GUID of the domain object, separated by tabs and line breaks. So the rule lowercases the field, pulls out every GUID with a regular expression and checks them against the two replication rights. One request can produce a separate 4662 for each right, so the rule collects rights per account before deciding.

Only DCs should replicate, so the rule alerts on any account that is neither a known DC nor the allow-listed Entra Connect sync account, both listed by exact name. Trusting every name ending in $ would miss WKS07$, a workstation's machine account with no reason to replicate; trusting every MSOL_ prefix would let a look-alike name hide. DC02$ and the sync account stay ok; WKS07$ and jpeters alert.

Pass-the-hash (T1550.002) reuses a stolen NTLM hash to authenticate without the password. One honest signal in 4624 is an NTLM network logon (type 3) with a NULL subject SID (S-1-0-0) and a zero key length. The rule alerts on that but ignores ANONYMOUS LOGON, which produces the same shape harmlessly and is common. NTLM network logons are normal in many environments, so this rule has real false positives and needs context such as the source host and account. It is a lead, not a verdict.

LSASS access (T1003.001) is the memory-reading step behind many of the above. Sysmon event 10 records which process opened lsass.exe and with which rights. The rule trusts only the exact full paths in its allow-list, not anything under C:\Windows\, because folders such as C:\Windows\Temp are writable by ordinary users. It then reads GrantedAccess: a handle that includes PROCESS_VM_READ (0x10) can read lsass memory, while 0x1000 only queries limited information. So svchost.exe from System32 stays ok, the backup agent asking only to query stays ok for later review, and the look-alike svchost.exe in C:\Windows\Temp and the tool in a user folder alert.

Neither the sample nor a real event 10 has a signature field, so the rule cannot claim an opener is signed; for that, join the record to other telemetry such as an image-load event or your file inventory. Some endpoint agents read lsass too, so keep the allow-list short, built from your own baseline, and review it.

06. Troubleshooting

07. Check your understanding

Practice check · 3 questions

Reading the detections

Three questions about the telemetry and detections you just ran.

Q1. Since the April 2026 KDC change, DCs assume AES for accounts without an explicit encryption-types attribute. Why does the Kerberoasting rule count distinct SPNs per account, not just RC4 tickets?
Q2. To avoid editing `DCSYNC_ALLOW` after an Entra Connect reinstall, a colleague proposes trusting any subject whose lowercased name starts with `msol_`. What is the risk?
Q3. On your own DC, the DCSync detection never produces a 4662 event even during a test replication. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the skill project, take the detections further with prepared data:

  • Add records to make_events.py: a third DC that replicates (add it to KNOWN_DCS), a service account that requests five distinct service tickets, and an agent in C:\Program Files that opens lsass with 0x1010. Predict each result, then run detect.py.
  • Try KERBEROAST_MIN_SPNS at 3 and at 10, and write one sentence on what each value catches and misses here.
  • Write a negative test: a short script that exits non-zero if any record marked benign in the generator raises an ALERT. Run it after every rule change.
  • Add a sixth detection, for example 4625 failed-logon bursts, with its own benign record, and note its likely false positives.

09. Review prompt

Without looking back, explain: which audit subcategory gives 4769, 4768, 4662 and 4624; why 4662 needs a SACL; the trace that marks Kerberoasting, AS-REP roasting, DCSync and pass-the-hash; why the Kerberoasting rule counts distinct SPNs after the RC4 change; why the DCSync rule must allow-list the MSOL_ account; and why the pass-the-hash and lsass rules need honest false-positive handling.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check