detect_sysmon_ldap.py
Independent portfolio example using fictional events. Not an employer detection.
1 """Original offline lab heuristic for Sysmon Event 3 XML. No log configuration changes."""
2 import argparse
3 import ipaddress
4 import json
5 import ntpath
6 import sys
7 import xml.etree.ElementTree as ET
8
9 NS = {'e': 'http://schemas.microsoft.com/win/2004/08/events/event'}
10 WATCH = {'powershell.exe', 'pwsh.exe', 'cmd.exe', 'python.exe', 'python3.exe',
11 'sharphound.exe', 'bloodhound.exe'}
12 PORTS = {'389', '636', '3268', '3269'}
13
14
15 def detect(xml_text, dc_ips):
16 targets = {str(ipaddress.ip_address(ip)) for ip in dc_ips}
17 if not targets:
18 raise ValueError('Supply at least one domain-controller IP')
19 # Parse exported XML only; ElementTree does not fetch external resources.
20 if '<!DOCTYPE' in xml_text.upper() or '<!ENTITY' in xml_text.upper():
21 raise ValueError('DTD/entity declarations are not supported')
22 root = ET.fromstring(xml_text)
23 event_tag = '{' + NS['e'] + '}Event'
24 events = [root] if root.tag == event_tag else list(root.findall('e:Event', NS))
25 if root.tag != event_tag and root.tag not in ('Events', '{' + NS['e'] + '}Events'):
26 raise ValueError('Expected an Event or Events XML export')
27 alerts, seen = [], {}
28 for event in events:
29 provider = event.find('e:System/e:Provider', NS)
30 if provider is None or provider.get('Name') != 'Microsoft-Windows-Sysmon':
31 continue
32 if event.findtext('e:System/e:EventID', namespaces=NS) != '3':
33 continue
34 data = {item.get('Name'): item.text or '' for item in event.findall('e:EventData/e:Data', NS)}
35 required = ('Image', 'DestinationIp', 'DestinationPort', 'Initiated', 'Protocol', 'ProcessGuid')
36 if any(not data.get(name) for name in required):
37 raise ValueError('Sysmon Event 3 is missing required named fields')
38 try:
39 destination = str(ipaddress.ip_address(data['DestinationIp']))
40 except ValueError as exc:
41 raise ValueError('Invalid DestinationIp in Sysmon Event 3') from exc
42 if data['Initiated'].lower() != 'true' or data['Protocol'].lower() != 'tcp':
43 continue
44 if destination not in targets or data['DestinationPort'] not in PORTS:
45 continue
46 process = ntpath.basename(data['Image']).lower()
47 if process not in WATCH:
48 continue
49 computer = event.findtext('e:System/e:Computer', namespaces=NS)
50 record = event.findtext('e:System/e:EventRecordID', namespaces=NS)
51 time = event.find('e:System/e:TimeCreated', NS)
52 if not computer or not record or time is None or not time.get('SystemTime'):
53 raise ValueError('Matching event lacks source computer, record ID, or timestamp')
54 result = {'rule': 'review_process_ldap_connection', 'computer': computer,
55 'timestamp': time.get('SystemTime'), 'record_id': record,
56 'process': data['Image'], 'process_guid': data['ProcessGuid'],
57 'destination_ip': destination, 'destination_port': int(data['DestinationPort']),
58 'assessment': 'Connection metadata only; investigate process purpose and host role.'}
59 identity = (computer, record)
60 if identity in seen:
61 if seen[identity] != result:
62 raise ValueError('Conflicting duplicate Sysmon record ID')
63 continue
64 seen[identity] = result
65 alerts.append(result)
66 return alerts
67
68
69 def main():
70 parser = argparse.ArgumentParser(description=__doc__)
71 parser.add_argument('xml_file', help='Event Viewer XML export, not binary EVTX')
72 parser.add_argument('--dc-ip', action='append', required=True, help='Repeat for additional DC IPs')
73 args = parser.parse_args()
74 try:
75 with open(args.xml_file, encoding='utf-8-sig') as stream:
76 alerts = detect(stream.read(), args.dc_ip)
77 print(json.dumps({'alerts': alerts}, indent=2))
78 except (OSError, ValueError, ET.ParseError) as exc:
79 print(f'Error: {exc}', file=sys.stderr)
80 return 2
81 return 0
82
83
84 if __name__ == '__main__':
85 sys.exit(main())