Lesson 05 · 55 minutes
Read Windows security events and find a guessed password, an odd logon and a cleared log
- Name the fields of a Windows event and the events that an analyst meets first
- Parse an exported event file with Python and count and filter the events
- Find a brute force, a logon of an odd type and a cleared log in a fixed sample
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Fernwood Press runs Windows machines next to the Linux web server: a domain controller (the server that holds the company's accounts and checks passwords), a file server FILE01 and five desktops. The team lead says: "Most alerts now come from Windows. Here is one day of events from these machines, exported as XML. Tell me if someone guessed a password, whether it worked, what they did next, and whether they tried to hide it." No Windows machine is needed.
Recall
Lesson 2: why does the parser turn every time into UTC?
Logs from different machines can be joined only on one clock. UTC is that clock.
Lesson 3: which three numbers does rule R1 use to find password guessing?
A condition (failed logins), a group (the address) and a threshold in a window (5 in 300 seconds).
The idea
Windows writes events into named logs, called channels. The Security channel holds audit events: logons, account changes, new processes and cleared logs, some only when the audit policy (what Windows records) is on. System (services) and Microsoft-Windows-PowerShell/Operational matter too. PowerShell is the Windows command shell that admins and attackers use, and this channel holds what it ran.
An event is an XML record. XML writes data between tags. <EventID>4625</EventID> is a tag with its text. A tag can hold other tags: <System> holds <EventID>. An opening tag can carry an attribute, a name="value" pair, as in <Data Name="LogonType">2</Data>.
Event Viewer shows an event on the Details tab. wevtutil qe Security /f:xml /e:Events /c:100 /rd:true prints the 100 newest events of a log as XML (qe is query-events, /f:xml the format, /e:Events wraps the events in one root tag, /c:100 the count, /rd:true newest first). Get-WinEvent is the PowerShell command that reads events as objects. This lesson uses XML, because every export has the same shape.
- Event channels → export.xml: Event Viewer or wevtutil
- export.xml → winevents.py: one dictionary for each event
- winevents.py → win_hunt.py: count, filter and join
- win_hunt.py → Analyst: findings in time order
Every event has a System part (the same fields for every kind of event) and a data part: EventData with <Data Name="..."> fields, or UserData for 1102 and 104. This is the failed logon of step 2:
A logon session starts when an account logs on. 4624 gives it a TargetLogonId, and later events of that session carry the same value as SubjectLogonId. Microsoft names it as a way to correlate events. A field that ends in Sid holds a SID, the unique number of an account.
The events that you meet first (the cheat sheet lists more; Field notes say which lines Microsoft documents):
| ID | Log | What it says | Read these fields |
|---|---|---|---|
| 4624 | Security | A logon session was created (on the machine that was accessed) | LogonType, TargetUserName, IpAddress, TargetLogonId |
| 4625 | Security | A logon failed | Status, SubStatus, LogonType, TargetUserName, IpAddress |
| 4672 | Security | Sensitive privileges, such as SeDebugPrivilege, went to a new logon | SubjectUserName, PrivilegeList |
| 4688 | Security | A new process started | NewProcessName, ParentProcessName, CommandLine |
| 4720 | Security | A user account was created | TargetUserName, SubjectUserName |
| 4732 | Security | A member was added to a security-enabled local group | TargetUserName (the group), MemberSid |
| 4698 | Security | A scheduled task was created | TaskName, TaskContent |
| 1102 | Security | The Security log was cleared | SubjectUserName (in UserData) |
| 104 | System | A log was cleared (System) | Channel |
| 7045 | System | A service was installed | ServiceName, ImagePath |
| 4104 | PowerShell | Script block logging: the text of a script block | ScriptBlockText |
Two facts: 4672 appears for every logon of SYSTEM, so it is mostly noise. The CommandLine of 4688 is empty unless the policy "Include command line in process creation events" is on.
The logon type says how the user logged on:
| Type | Name | Meaning |
|---|---|---|
| 2 | Interactive | At the keyboard of this machine |
| 3 | Network | Over the network, for example a file share |
| 4, 5 | Batch, Service | A scheduled job, a service |
| 10 | RemoteInteractive | Remote Desktop |
Types 7, 8, 9 and 11 are in the cheat sheet.
In 4625, Status and SubStatus are NTSTATUS codes (result numbers of Windows). Microsoft names 0xC0000064 (bad user name), 0xC000006A (bad password), 0xC000006D (the generic logon failure), 0xC0000234 (account locked out), 0xC0000072 (account disabled) and 0xC000006F (outside the allowed hours). In this sample Status holds the generic 0xC000006D and SubStatus the specific reason.
Worked example
1. Make the sample
The generator gen_winevents.py writes one day of invented events for 7 machines into data/win/export.xml, in the XML shape of wevtutil. Its seed is fixed, so your file is the same as mine. You do not need to read it.
The finished file: gen_winevents.py
gen_winevents.py
"""gen_winevents.py: write one day of invented Windows events, in the XML that wevtutil makes.
python3 gen_winevents.py [day] [folder] day 1 (default) or 2: Fernwood Press; day 3: Ironwood Freight
(the scenario test); folder default: data/win
The same day always gives the same file. Every name, address and command is invented.
"""
import hashlib
import random
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from xml.sax.saxutils import escape
# day: seed, date, address of the intruder, account that it uses, machine that it attacks, first guess, guesses, account that it adds
DAYS = {
1: (21, (2026, 11, 24), "203.0.113.66", "svc-backup", "FILE01", (13, 20), 36, "svc-helpdesk"),
2: (22, (2026, 12, 1), "198.51.100.200", "svc-print", "APP01", (9, 5), 28, "support-tmp"),
3: (23, (2026, 12, 3), "192.0.2.171", "kfoster", "FILES01", (7, 6), 0, "helpdesk3"), # no guesses: it knows the password
}
day = int(sys.argv[1]) if len(sys.argv) > 1 else 1
out = Path(sys.argv[2] if len(sys.argv) > 2 else "data/win")
seed, ymd, INTRUDER, VICTIM, TARGET, (ah, am), FAILS, NEWACCT = DAYS[day]
r = random.Random(seed) # only random() is used: the same numbers on every Python version
def rnd(n):
return int(r.random() * n)
def pick(items):
return items[rnd(len(items))]
# company: domain, DNS name, domain SID, file server, start of product names, hours that its working day starts later, staff
FERNWOOD = ("FERNWOOD", "fernwood.example.com", "S-1-5-21-1180699209-877415012-3182924384-", "FILE01", "Fern", 0,
{"alice": ("WS-ALICE", "192.0.2.101"), "bob": ("WS-BOB", "192.0.2.102"), "carol": ("WS-CAROL", "192.0.2.103"),
"mwebb": ("WS-MWEBB", "192.0.2.104"), "pdiaz": ("WS-PDIAZ", "192.0.2.105")})
IRONWOOD = ("IRONWOOD", "ironwood.example.com", "S-1-5-21-2650137411-306417822-1974082317-", "FILES01", "Iron", 6,
{"lnguyen": ("WS-LNGUYEN", "192.0.2.112"), "tomas": ("WS-TOMAS", "192.0.2.113"), "amir": ("WS-AMIR", "192.0.2.114")})
DOMAIN, FQDN, SID, SERVER, BRAND, SHIFT, WS = IRONWOOD if day == 3 else FERNWOOD
USERS = list(WS)
RID = {"alice": 1104, "bob": 1105, "carol": 1106, "mwebb": 1107, "pdiaz": 1108, "adm-ops": 1110, "svc-backup": 1111,
"svc-print": 1112, NEWACCT: 1120, "tmp-contractor": 1115, "kfoster": 1131, "lnguyen": 1132, "tomas": 1133, "amir": 1134}
DAY = datetime(*ymd, tzinfo=timezone.utc)
events = [] # (time, computer, channel, provider, id, kind, data)
PRIV = "SeTcbPrivilege SeSecurityPrivilege SeBackupPrivilege SeRestorePrivilege SeDebugPrivilege SeImpersonatePrivilege"
def at(h, m=0, s=0):
return DAY + timedelta(hours=h, minutes=m, seconds=s)
def life(h, m=0, s=0): # a time of the normal working day of the company
return at(h + SHIFT, m, s)
def sid(user):
return SID + str(RID.get(user, 1999))
def logid():
return hex(0x100000 + rnd(0x900000))
def add(t, host, eid, data, channel="Security", provider="Microsoft-Windows-Security-Auditing", kind="EventData"):
events.append((t, host, channel, provider, eid, kind, data))
def logon(t, host, user, ltype, ip="-", package="Negotiate", process="Kerberos", workstation="-", lid=None, priv=False):
"""4624, and 4672 with the same logon id when the logon holds special privileges."""
lid = lid or logid()
add(t, host, 4624, {"SubjectUserSid": "S-1-5-18", "SubjectUserName": host + "$", "SubjectDomainName": DOMAIN,
"SubjectLogonId": "0x3e7", "TargetUserSid": sid(user), "TargetUserName": user,
"TargetDomainName": DOMAIN, "TargetLogonId": lid, "LogonType": ltype,
"LogonProcessName": process, "AuthenticationPackageName": package, "WorkstationName": workstation,
"ProcessId": "0x0", "ProcessName": "-", "IpAddress": ip, "IpPort": str(49152 + rnd(16000)) if ip != "-" else "0",
"ElevatedToken": "%%1842" if priv else "%%1843"})
if priv:
add(t, host, 4672, {"SubjectUserSid": sid(user), "SubjectUserName": user, "SubjectDomainName": DOMAIN,
"SubjectLogonId": lid, "PrivilegeList": PRIV})
return lid
def fail(t, host, user, ltype, ip, status, sub, workstation="-"):
add(t, host, 4625, {"SubjectUserSid": "S-1-0-0", "SubjectUserName": "-", "SubjectDomainName": "-", "SubjectLogonId": "0x0",
"TargetUserSid": "S-1-0-0", "TargetUserName": user, "TargetDomainName": DOMAIN, "Status": status,
"FailureReason": "%%2313", "SubStatus": sub, "LogonType": ltype, "LogonProcessName": "NtLmSsp ",
"AuthenticationPackageName": "NTLM", "WorkstationName": workstation, "ProcessId": "0x0",
"ProcessName": "-", "IpAddress": ip, "IpPort": str(49152 + rnd(16000))})
def proc(t, host, user, lid, image, cmd, parent):
add(t, host, 4688, {"SubjectUserSid": sid(user), "SubjectUserName": user, "SubjectDomainName": DOMAIN, "SubjectLogonId": lid,
"NewProcessId": hex(0x400 + rnd(0x3000)), "NewProcessName": image, "TokenElevationType": "%%1938",
"ProcessId": hex(0x400 + rnd(0x3000)), "CommandLine": cmd, "ParentProcessName": parent})
def subject(user, lid):
return {"SubjectUserSid": sid(user), "SubjectUserName": user, "SubjectDomainName": DOMAIN, "SubjectLogonId": lid}
def account(t, host, eid, actor, lid, target, extra=None):
add(t, host, eid, {"TargetUserName": target, "TargetDomainName": DOMAIN, "TargetSid": sid(target), **subject(actor, lid), **(extra or {})})
def services(t, host, name, image, who):
add(t, host, 7045, {"ServiceName": name, "ImagePath": image, "ServiceType": "user mode service", "StartType": "auto start",
"AccountName": "LocalSystem"}, channel="System", provider="Service Control Manager")
def task(t, host, actor, lid, name, command):
body = f'<Task><Actions><Exec><Command>{command}</Command></Exec></Actions></Task>'
add(t, host, 4698, {**subject(actor, lid), "TaskName": name, "TaskContent": body})
def script(t, host, text):
add(t, host, 4104, {"MessageNumber": "1", "MessageTotal": "1", "ScriptBlockText": text,
"ScriptBlockId": "{%08x-0000-4000-8000-%012x}" % (rnd(2**31), rnd(2**40)), "Path": ""},
channel="Microsoft-Windows-PowerShell/Operational", provider="Microsoft-Windows-PowerShell")
def cleared(t, host, actor, lid, channel, eid, provider):
d = subject(actor, lid)
if eid == 104:
d = {**d, "Channel": channel, "BackupPath": ""}
add(t, host, eid, d, channel=channel, provider=provider, kind="UserData")
# 1. Normal life
for name, (ws, ip) in WS.items():
t = life(7 + rnd(2), rnd(60), rnd(60))
lid = logon(t, ws, name, 2, "127.0.0.1", "Negotiate", "User32", ws)
for image, cmd in [(r"C:\Program Files\Mozilla Firefox\firefox.exe", "firefox.exe"),
(r"C:\Windows\System32\notepad.exe", "notepad.exe"),
(r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE", f'WINWORD.EXE "C:\\Users\\{name}\\Documents\\plan.docx"')]:
t += timedelta(seconds=60 + rnd(1200))
proc(t, ws, name, lid, image, cmd, r"C:\Windows\explorer.exe")
for _ in range(3):
t += timedelta(seconds=30 + rnd(900))
logon(t, SERVER, name, 3, ip, "Kerberos", "Kerberos", ws)
add(t, "DC01", 4769, {"TargetUserName": f"{name}@{FQDN.upper()}", "TargetDomainName": FQDN.upper(), "ServiceName": SERVER + "$",
"TicketEncryptionType": "0x12", "IpAddress": "::ffff:" + ip, "IpPort": "49800", "Status": "0x0"})
add(life(7, 50, rnd(600)), "DC01", 4768, {"TargetUserName": name, "TargetDomainName": FQDN.upper(), "ServiceName": "krbtgt",
"TicketEncryptionType": "0x12", "Status": "0x0", "IpAddress": "::ffff:" + ip, "IpPort": "50100"})
add(life(10, 2, 11), "DC01", 4776, {"PackageName": "MICROSOFT_AUTHENTICATION_PACKAGE_V1_0", "TargetUserName": USERS[2], "Workstation": "PRN-OLD", "Status": "0x0"})
t = life(8, 31, 5) # a typing mistake that is far below any sensible limit
for _ in range(3):
fail(t, WS[USERS[0]][0], USERS[0], 2, "127.0.0.1", "0xc000006d", "0xc000006a", WS[USERS[0]][0])
t += timedelta(seconds=5 + rnd(5))
logon(t, WS[USERS[0]][0], USERS[0], 2, "127.0.0.1", "Negotiate", "User32", WS[USERS[0]][0])
for h in (1, 2, 3): # system start of the file server
logon(life(0, h, rnd(60)), SERVER, "SYSTEM", 5, process="Advapi", package="Negotiate", priv=True)
lid = logon(life(1, 0, 3), SERVER, "svc-backup", 4, process="Advapi", package="Negotiate") # the nightly backup
proc(life(1, 0, 9), SERVER, "svc-backup", lid, rf"C:\Program Files\{BRAND}Backup\backup.exe", r"backup.exe /nightly", r"C:\Windows\System32\svchost.exe")
lid = logon(life(9, 40, 2), SERVER, "adm-ops", 10, "192.0.2.50", "Negotiate", "User32", "ADMPC01", priv=True) # the administrator
proc(life(9, 41), SERVER, "adm-ops", lid, r"C:\Windows\System32\mmc.exe", r"mmc.exe compmgmt.msc", r"C:\Windows\explorer.exe")
services(life(9, 44), SERVER, f"{BRAND}Backup Agent", rf"C:\Program Files\{BRAND}Backup\agent.exe", "adm-ops")
task(life(9, 47), SERVER, "adm-ops", lid, rf"\{BRAND}Backup\Nightly", rf"C:\Program Files\{BRAND}Backup\backup.exe")
script(life(9, 52), SERVER, "Get-Service | Where-Object Status -eq Stopped")
account(life(9, 55), SERVER, 4722, "adm-ops", lid, USERS[1])
account(life(9, 58), SERVER, 4726, "adm-ops", lid, "tmp-contractor", {"PrivilegeList": "-"})
# 2. The intruder: guesses (none on day 3), then one account that works
t = at(ah, am, 4)
names = ["administrator", "admin", "backup", "scanner", "helpdesk", "guest", "svc-sql", VICTIM]
for i in range(FAILS):
user = names[i % len(names)] if i < FAILS - 4 else VICTIM
unknown = user != VICTIM
fail(t, TARGET, user, 3, INTRUDER, "0xc000006d", "0xc0000064" if unknown else "0xc000006a")
t += timedelta(seconds=2 + rnd(4))
t += timedelta(seconds=40)
lid = logon(t, TARGET, VICTIM, 10, INTRUDER, "Negotiate", "User32", "-", priv=True)
steps = [(1, r"C:\Windows\System32\whoami.exe", "whoami /all"), (2, r"C:\Windows\System32\net.exe", f"net user {NEWACCT} * /add"),
(3, r"C:\Windows\System32\net.exe", f"net localgroup Administrators {NEWACCT} /add")]
for m, image, cmd in steps:
proc(t + timedelta(minutes=m), TARGET, VICTIM, lid, image, cmd, r"C:\Windows\System32\cmd.exe")
account(t + timedelta(minutes=2, seconds=1), TARGET, 4720, VICTIM, lid, NEWACCT, {"SamAccountName": NEWACCT})
add(t + timedelta(minutes=3, seconds=1), TARGET, 4732, {"MemberName": "-", "MemberSid": sid(NEWACCT), "TargetUserName": "Administrators",
"TargetDomainName": "Builtin", "TargetSid": "S-1-5-32-544", **subject(VICTIM, lid)})
script(t + timedelta(minutes=5), TARGET, r"Get-ChildItem D:\Shares -Recurse | Measure-Object Length -Sum")
task(t + timedelta(minutes=6), TARGET, VICTIM, lid, rf"\{BRAND}Sync", r"C:\ProgramData\fsync\sync.exe")
services(t + timedelta(minutes=7), TARGET, f"{BRAND}SyncSvc", r"C:\ProgramData\fsync\sync.exe -service", VICTIM)
cleared(t + timedelta(minutes=9), TARGET, VICTIM, lid, "Security", 1102, "Microsoft-Windows-Eventlog")
cleared(t + timedelta(minutes=9, seconds=2), TARGET, VICTIM, lid, "System", 104, "Microsoft-Windows-Eventlog")
# 3. Write the file, in time order
events.sort(key=lambda e: e[0])
records = {}
rows = []
for t, host, channel, provider, eid, kind, data in events:
records[host] = records.get(host, 1000) + 1 + rnd(3)
stamp = f"{t:%Y-%m-%dT%H:%M:%S}.{rnd(10**7):07d}Z"
if kind == "UserData":
body = "".join(f"<{k}>{escape(str(v))}</{k}>" for k, v in data.items())
ns = "http://manifests.microsoft.com/win/2004/08/windows/eventlog"
payload = f'<UserData><LogFileCleared xmlns="{ns}">{body}</LogFileCleared></UserData>'
else:
body = "".join(f'<Data Name="{k}">{escape(str(v))}</Data>' if v != "" else f'<Data Name="{k}" />' for k, v in data.items())
payload = f"<EventData>{body}</EventData>"
rows.append(f'<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"><System><Provider Name="{provider}" />'
f'<EventID>{eid}</EventID><TimeCreated SystemTime="{stamp}" /><EventRecordID>{records[host]}</EventRecordID>'
f'<Channel>{channel}</Channel><Computer>{host}.{FQDN}</Computer></System>{payload}</Event>')
out.mkdir(parents=True, exist_ok=True)
text = "<Events>\n" + "\n".join(rows) + "\n</Events>\n"
(out / "export.xml").write_text(text)
print(f"export.xml {len(rows):5d} events sha256 {hashlib.sha256(text.encode()).hexdigest()[:12]}")python3 gen_winevents.pyexport.xml 124 events sha256 bb8aea4b82b02. Read one raw event
xml.etree.ElementTree is the standard module for XML: ET.parse reads a file, ET.indent lays the tags out in lines, ET.tostring writes an element as text. Below is the first 4625 of the file, shortened to six of its 18 fields.
python3 - <<'EOF'
import xml.etree.ElementTree as ET
NS = "{http://schemas.microsoft.com/win/2004/08/events/event}"
ET.register_namespace("", NS[1:-1])
for ev in ET.parse("data/win/export.xml").getroot():
if ev.findtext(NS + "System/" + NS + "EventID") == "4625":
ET.indent(ev)
print(ET.tostring(ev, encoding="unicode"))
break
EOF<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-Security-Auditing" />
<EventID>4625</EventID>
<TimeCreated SystemTime="2026-11-24T08:31:05.0676311Z" />
<EventRecordID>1009</EventRecordID>
<Channel>Security</Channel>
<Computer>WS-ALICE.fernwood.example.com</Computer>
</System>
<EventData>
<Data Name="TargetUserName">alice</Data>
<Data Name="Status">0xc000006d</Data>
<Data Name="SubStatus">0xc000006a</Data>
<Data Name="LogonType">2</Data>
<Data Name="WorkstationName">WS-ALICE</Data>
<Data Name="IpAddress">127.0.0.1</Data>
</EventData>
</Event>Read it as a story: at 08:31 UTC somebody at the keyboard of WS-ALICE typed a bad password. (127.0.0.1 in IpAddress means local.)
A pitfall: every tag lives in a namespace, a prefix that is glued to the tag: {http://schemas.microsoft.com/win/2004/08/events/event}EventID. A search for plain EventID finds nothing, so the program keeps the namespace in NS.
3. Parse every event into a dictionary
winevents.py makes one dictionary for each event: id, ts (UTC, as in lesson 2), computer, channel, record and data (field name to text). An empty Data element has no text, so the code uses d.text or "".
for part in ev:
if local(part.tag) == "EventData": # most events: <Data Name="...">text</Data>
data = {d.get("Name"): d.text or "" for d in part}
elif local(part.tag) == "UserData": # 1102 and 104: the fields are the tags of one child
data = {local(d.tag): d.text or "" for d in part[0]}The whole of both programs is in step 8, and the steps from here on run them. Save winevents.py and win_hunt.py from step 8 in this folder now. Then run winevents.py: it counts the events of each kind.
python3 winevents.py124 events, 7 computers
1 104 log cleared
1 1102 Security log cleared
2 4104 PowerShell script block
27 4624 logon success
39 4625 logon failure
5 4672 special privileges
20 4688 process created
2 4698 scheduled task created
1 4720 account created
1 4722 account enabled
1 4726 account deleted
1 4732 added to local group
5 4768 Kerberos TGT
15 4769 Kerberos service ticket
1 4776 NTLM check
2 7045 service installedThe 4768, 4769 and 4776 lines are Kerberos and NTLM checks on the domain controller, two ways that Windows proves who you are on a network. You only count them here. 39 failures against 27 successes: look there first.
4. Count the failures by reason
win_hunt.py holds the questions of this lesson as functions. reasons counts the 4625 events by their SubStatus code. (The ipaddress module, used later, tests whether an address is in a network.)
python3 - <<'EOF'
from collections import Counter
from winevents import parse
from win_hunt import reasons
events = parse("data/win/export.xml")
print(reasons(events))
print(Counter(e["data"]["IpAddress"] for e in events if e["id"] == 4625).most_common(1))
EOFCounter({'no such user': 28, 'bad password': 11})
[('203.0.113.66', 36)]36 of 39 failures come from one outside address, and most name an account that does not exist: the guesser does not know who works here.
5. Find the brute force and what came after
brute_force finds each outside address with 10 failures inside 300 seconds (the idea of lesson 3). Then it asks the question that matters: did a logon succeed from that address after the last failure? The helper when uses datetime.fromisoformat to turn our time text into a time that you can subtract (.total_seconds() gives the seconds), and outside is true for an address that is not local and not in the office network.
def brute_force(events, count=10, window=300):
"""Addresses with `count` failures inside `window` seconds, and the logon that came after the last failure."""
found = []
for ip in sorted({e["data"]["IpAddress"] for e in events if e["id"] == 4625 and outside(e["data"]["IpAddress"])}):
bad = [e for e in events if e["id"] == 4625 and e["data"]["IpAddress"] == ip]
if any((when(bad[i + count - 1]) - when(bad[i])).total_seconds() <= window for i in range(len(bad) - count + 1)):
good = next((e for e in events if e["id"] == 4624 and e["data"]["IpAddress"] == ip and e["ts"] > bad[-1]["ts"]), None)
found.append({"ip": ip, "failures": len(bad), "first": bad[0]["ts"], "success": good})
return foundpython3 win_hunt.py | sed -n 2pbrute force from 203.0.113.66: 36 failures from 2026-11-24T13:20:04Z; then logon type 10 for svc-backup at 2026-11-24T13:22:41ZAfter 36 failures, svc-backup logged on. "Many 4625, then a 4624" is a true positive until proven otherwise. In ATT&CK it is Brute Force (T1110), then Valid Accounts (T1078).
6. Find the odd logon type and follow it
Type 10 is Remote Desktop. It is normal from the administrator's PC 192.0.2.50 (a logon at 09:40, not flagged). It is not normal from outside the office, and a service account such as svc-backup should run as a batch job (type 4), as it does at 01:00. odd_logons finds successful remote logons (types 3, 10 and 8, network with a cleartext password) from outside 192.0.2.0/24. timeline lists everything on that machine from the time of that logon.
python3 win_hunt.py | sed -n 3,15podd logon: FILE01 svc-backup type 10 from 203.0.113.66
2026-11-24T13:22:41Z 4624 logon success: svc-backup
2026-11-24T13:22:41Z 4672 special privileges: svc-backup
2026-11-24T13:23:41Z 4688 process created: whoami /all
2026-11-24T13:24:41Z 4688 process created: net user svc-helpdesk * /add
2026-11-24T13:24:42Z 4720 account created: svc-helpdesk
2026-11-24T13:25:41Z 4688 process created: net localgroup Administrators svc-helpdesk /add
2026-11-24T13:25:42Z 4732 added to local group: Administrators
2026-11-24T13:27:41Z 4104 PowerShell script block: Get-ChildItem D:\Shares -Recurse | Measure-Object Length -Sum
2026-11-24T13:28:41Z 4698 scheduled task created: \FernSync
2026-11-24T13:29:41Z 7045 service installed: FernSyncSvc
2026-11-24T13:31:41Z 1102 Security log cleared: svc-backup
2026-11-24T13:31:43Z 104 log cleared: SystemATT&CK names these Create Account: Local Account (T1136.001), Scheduled Task (T1053.005) and Windows Service (T1543.003). The administrator's own service and task at 09:44 and 09:47 look the same. What differs is who made them, from where, and what they start.
7. Find the cleared log
At 13:31 the same logon cleared the Security log (1102) and, two seconds later, the System log (104). clears finds both. Microsoft says that each 1102 deserves an investigation. ATT&CK lists it as Clear Windows Event Logs (T1685.005 in the version that was current on 2026-11-21; older text calls it T1070.001).
tail -n 2 prints the last two lines.
python3 win_hunt.py | tail -n 2log cleared: 2026-11-24T13:31:41Z FILE01 id 1102 by svc-backup
log cleared: 2026-11-24T13:31:43Z FILE01 id 104 by svc-backupYou can read the earlier events only because a copy was kept elsewhere (lesson 1).
8. The finished files
The finished files: winevents.py and win_hunt.py
winevents.py
"""winevents.py: read Windows events in XML form (Event Viewer, wevtutil qe /f:xml /e:Events) into dictionaries.
python3 winevents.py [export.xml] prints how many events there are of each kind
"""
import sys
import xml.etree.ElementTree as ET
from collections import Counter
NS = "{http://schemas.microsoft.com/win/2004/08/events/event}"
NAMES = {4624: "logon success", 4625: "logon failure", 4672: "special privileges", 4688: "process created",
4698: "scheduled task created", 4720: "account created", 4722: "account enabled", 4726: "account deleted",
4732: "added to local group", 4768: "Kerberos TGT", 4769: "Kerberos service ticket", 4776: "NTLM check",
1102: "Security log cleared", 104: "log cleared", 7045: "service installed", 4104: "PowerShell script block"}
def local(tag):
"""The tag without its namespace: {http://...}Data becomes Data."""
return tag.rsplit("}", 1)[-1]
def parse(path):
"""One dictionary for each event: id, ts (UTC), computer, channel, record and data (name to text)."""
events = []
for ev in ET.parse(path).getroot():
system, data = ev.find(NS + "System"), {}
for part in ev:
if local(part.tag) == "EventData": # most events: <Data Name="...">text</Data>
data = {d.get("Name"): d.text or "" for d in part}
elif local(part.tag) == "UserData": # 1102 and 104: the fields are the tags of one child
data = {local(d.tag): d.text or "" for d in part[0]}
events.append({"id": int(system.findtext(NS + "EventID")),
"ts": system.find(NS + "TimeCreated").get("SystemTime")[:19] + "Z",
"computer": system.findtext(NS + "Computer").split(".")[0],
"channel": system.findtext(NS + "Channel"),
"record": int(system.findtext(NS + "EventRecordID")), "data": data})
return events
if __name__ == "__main__":
events = parse(sys.argv[1] if len(sys.argv) > 1 else "data/win/export.xml")
print(len(events), "events,", len({e["computer"] for e in events}), "computers")
for number, n in sorted(Counter(e["id"] for e in events).items()):
print(f"{n:5d} {number} {NAMES.get(number, '')}")win_hunt.py
"""win_hunt.py: find a brute force, an odd logon and a log clear in the events of winevents.py.
python3 win_hunt.py [export.xml]
"""
import ipaddress
import sys
from collections import Counter
from datetime import datetime
from winevents import NAMES, parse
OFFICE = ipaddress.ip_network("192.0.2.0/24") # the invented office network
REMOTE = {"3", "8", "10"} # logon types that come over the network: network, network cleartext, remote desktop
SHOW = {4624: "TargetUserName", 4672: "SubjectUserName", 4688: "CommandLine", 4698: "TaskName", 4720: "TargetUserName", 4722: "TargetUserName", 4726: "TargetUserName", 4732: "TargetUserName", 7045: "ServiceName",
4104: "ScriptBlockText", 1102: "SubjectUserName", 104: "Channel"} # the field that tells most about each event
REASON = {"0xc0000064": "no such user", "0xc000006a": "bad password", "0xc000006d": "logon failure"}
def when(e):
return datetime.fromisoformat(e["ts"])
def outside(address):
"""True for an address that is not in the office network, and not local."""
if address in ("-", "127.0.0.1", "::1"):
return False
ip = ipaddress.ip_address(address)
return (getattr(ip, "ipv4_mapped", None) or ip) not in OFFICE # ::ffff:192.0.2.101 is the IPv4 address 192.0.2.101
def reasons(events):
"""Count failed logons by the reason that Status and SubStatus give: the specific code is in SubStatus."""
return Counter(REASON.get(e["data"]["SubStatus"], e["data"]["SubStatus"]) for e in events if e["id"] == 4625)
def brute_force(events, count=10, window=300):
"""Addresses with `count` failures inside `window` seconds, and the logon that came after the last failure."""
found = []
for ip in sorted({e["data"]["IpAddress"] for e in events if e["id"] == 4625 and outside(e["data"]["IpAddress"])}):
bad = [e for e in events if e["id"] == 4625 and e["data"]["IpAddress"] == ip]
if any((when(bad[i + count - 1]) - when(bad[i])).total_seconds() <= window for i in range(len(bad) - count + 1)):
good = next((e for e in events if e["id"] == 4624 and e["data"]["IpAddress"] == ip and e["ts"] > bad[-1]["ts"]), None)
found.append({"ip": ip, "failures": len(bad), "first": bad[0]["ts"], "success": good})
return found
def odd_logons(events):
"""Successful remote logons from outside the office."""
return [e for e in events if e["id"] == 4624 and e["data"]["LogonType"] in REMOTE and outside(e["data"]["IpAddress"])]
def clears(events):
"""Events that say a log was cleared: 1102 (Security) and 104 (another log)."""
return [e for e in events if e["id"] in (1102, 104)]
def timeline(events, logon):
"""Everything on the same computer from the time of the logon on, one line for each event."""
return [f"{e['ts']} {e['id']} {NAMES.get(e['id'], '')}: {e['data'].get(SHOW.get(e['id']), '')}"
for e in events if e["computer"] == logon["computer"] and e["ts"] >= logon["ts"]]
if __name__ == "__main__":
events = parse(sys.argv[1] if len(sys.argv) > 1 else "data/win/export.xml")
print("failures by reason:", dict(reasons(events)))
for b in brute_force(events):
s = b["success"]
print(f"brute force from {b['ip']}: {b['failures']} failures from {b['first']}; then "
+ (f"logon type {s['data']['LogonType']} for {s['data']['TargetUserName']} at {s['ts']}" if s else "no logon"))
for e in odd_logons(events):
print(f"odd logon: {e['computer']} {e['data']['TargetUserName']} type {e['data']['LogonType']} from {e['data']['IpAddress']}")
print("\n".join(" " + line for line in timeline(events, e)))
for e in clears(events):
print(f"log cleared: {e['ts']} {e['computer']} id {e['id']} by {e['data']['SubjectUserName']}")Your turn
A second day is another export with another address, account, machine and new account. Make it with python3 gen_winevents.py 2 day2 (it writes day2/export.xml) and run your tools on it. For the last two questions, read the timeline of the odd logon.
Check yourself
You search the XML for `EventID` and find nothing. Why?
Every tag is in a namespace, so its full name is {namespace}EventID. Put the namespace before the tag name.
Why is a type 10 logon from 192.0.2.50 not an alert, and one from 203.0.113.66 is?
Type 10 is Remote Desktop, which administrators use. The source decides: the first is the office, the second is outside and came after 36 failures.
Why can the intruder's service installation (7045) not be tied to a logon id?
7045 comes from the System log and has no subject fields. To tie it to an account, use the time, the machine and the Security events around it.
Field notes
- The Security log holds only what the audit policy turned on. When a 4688 or 4624 is missing, check the policy before you suspect the attacker. Command lines in 4688 and script text in 4104 each need a setting that someone must choose (script block logging: Group Policy or a registry setting).
- Python's standard XML reader is not safe against a hostile file (it can be made to use huge amounts of memory). For XML that you do not control, use the
defusedxmlpackage. - Microsoft's pages document 4624, 4625, 4672, 4688, 4720, 4722, 4726, 4732, 4698, 1102, 4768, 4769 and 4776, and the ID and channel of 4104. A Microsoft blog names 7045 as the System event for service creation, and public detection guides name 104. The field names of 7045, 104 and 4104 here follow common exports, not a Microsoft page: check them on a real export before you write a rule.
- A logon session ties events together: the 4624 holds the id as
TargetLogonId, and later events carry it asSubjectLogonId. In this export 9 of the 11 later events carry it. 4104 and 7045 have no subject, so tie them by time and machine. - Windows can write an IPv4 address as
::ffff:a.b.c.d(4768 and 4769 do it here; Microsoft names the form for 4625 too).outside()maps it back before it compares. - A cleared log is a strong sign, but not proof: some people clear logs for routine reasons. Ask who cleared it and what happened in the minutes before.