As a DevSecOps expert, create a python 3.12 script that converts a YAML config file to a Windows Subscription Query only that you paste in the GUI. Here is an output reference XML that you can based on to create a YAML config, your python script and test your script:
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
<QueryList>
<Query Id="0" Path="Security">
<!-- Network logon events-->
<Select Path="Security">*[System[(EventID=4624)]] and (*[EventData[Data[@Name="LogonType"]="3"]])</Select>
</Query>
<Query Id="1" Path="System">
<!-- RADIUS authentication events User Assigned IP address (20274), User successfully authenticated (20250), User Disconnected (20275) -->
<Select Path="System">*[System[Provider[@Name='RemoteAccess'] and (EventID=20274 or EventID=20250 or EventID=20275)]]</Select>
</Query>
<Query Id="2" Path="Microsoft-Windows-CAPI2/Operational">
<!-- CAPI events Build Chain (11), Private Key accessed (70), X509 object (90)-->
<Select Path="Microsoft-Windows-CAPI2/Operational">*[System[(EventID=11 or EventID=70 or EventID=90)]]</Select>
</Query>
<Query Id="3" Path="Security">
<!-- CA stop/Start events CA Service Stopped (4880), CA Service Started (4881), CA DB row(s) deleted (4896), CA Template loaded (4898) -->
<Select Path="Security">*[System[(EventID=4880 or EventID = 4881 or EventID = 4896 or EventID = 4898)]]</Select>
</Query>
<Query Id="4" Path="Microsoft-Windows-LSA/Operational">
<!-- Groups assigned to new login (except for well known, built-in accounts)-->
<Select Path="Microsoft-Windows-LSA/Operational">*[System[(EventID=300)]] and (*[EventData[Data[@Name="TargetUserSid"] != "S-1-5-20"]]) and (*[EventData[Data[@Name="TargetUserSid"] != "S-1-5-18"]]) and (*[EventData[Data[@Name="TargetUserSid"] != "S-1-5-19"]])</Select>
</Query>
<Query Id="5" Path="Security">
<!-- Logoff events - for Network Logon events-->
<Select Path="Security">*[System[(EventID=4634)]] and (*[EventData[Data[@Name="LogonType"] = "3"]])</Select>
</Query>
<Query Id="6" Path="Security">
<!-- RRAS events - only generated on Microsoft IAS server -->
<Select Path="Security">*[System[( (EventID >= 6272 and EventID <= 6280) )]]</Select>
</Query>
<Query Id="7" Path="Microsoft-Windows-DNS-Client/Operational">
<!-- DNS Client events Query Completed (3008) -->
<Select Path="Microsoft-Windows-DNS-Client/Operational">*[System[(EventID=3008)]]</Select>
<!-- suppresses local machine name resolution events -->
<Suppress Path="Microsoft-Windows-DNS-Client/Operational">*[EventData[Data[@Name="QueryOptions"]="140737488355328"]]</Suppress>
<!-- suppresses empty name resolution events -->
<Suppress Path="Microsoft-Windows-DNS-Client/Operational">*[EventData[Data[@Name="QueryResults"]=""]]</Suppress>
</Query>
<Query Id="8" Path="Security">
<!-- Process Terminate (4689) -->
<Select Path="Security">*[System[(EventID = 4689)]]</Select>
</Query>
<Query Id="9" Path="Security">
<!-- Local credential authentication events (4776), Logon with explicit credentials (4648) -->
<Select Path="Security">*[System[(EventID=4776 or EventID=4648)]]</Select>
</Query>
<Query Id="10" Path="Security">
<!-- Registry modified events for Operations: New Registry Value created (%%1904), Existing Registry Value modified (%%1905), Registry Value Deleted (%%1906) -->
<Select Path="Security">*[System[(EventID=4657)]] and ((*[EventData[Data[@Name="OperationType"] = "%%1904"]]) or (*[EventData[Data[@Name="OperationType"] = "%%1905"]]) or (*[EventData[Data[@Name="OperationType"] = "%%1906"]]))</Select>
</Query>
<Query Id="11" Path="Security">
<!-- Request made to authenticate to Wireless network (including Peer MAC (5632) -->
<Select Path="Security">*[System[(EventID=5632)]]</Select>
</Query>
<Query Id="12" Path="Microsoft-Windows-PowerShell/Operational">
<!-- PowerShell execute block activity (4103), Remote Command(4104), Start Command(4105), Stop Command(4106) -->
<Select Path="Microsoft-Windows-PowerShell/Operational">*[System[(EventID=4103 or EventID=4104 or EventID=4105 or EventID=4106)]]</Select>
</Query>
<Query Id="13" Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">
<!-- Detect User-Mode drivers loaded - for potential BadUSB detection. -->
<Select Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">*[System[(EventID=2004)]]</Select>
</Query>
<Query Id="14" Path="Windows PowerShell">
<!-- Legacy PowerShell pipeline execution details (800) -->
<Select Path="Windows PowerShell">*[System[(EventID=800)]]</Select>
</Query>
</QueryList>
Output me the script and the relevant yaml config file
Here's a Python 3.12 script that converts a YAML configuration file into a Windows Event Log Subscription Query XML, as per your example. The script supports:
Multiple <Query> entries with different IDs and paths
<Select> and <Suppress> elements
Conditions (e.g., event IDs, logon types, data field comparisons)
Comments for each query
✅ Python Script: yaml_to_subscription_query.py
python
import yaml
import xml.etree.ElementTree as ET
def escape_xml(text):
"""Escape special XML characters."""
return text.replace("&", "&").replace("<", "<").replace(">", ">")
def build_condition(data):
"""Convert condition dict to XPath expression."""
conditions = []
if 'EventID' in data:
eid = data['EventID']
if isinstance(eid, list):
eid_conditions = [f"EventID={e}" for e in eid]
conditions.append(f"({ ' or '.join(eid_conditions) })")
else:
conditions.append(f"EventID={eid}")
if 'LogonType' in data:
lt = data['LogonType']
if isinstance(lt, list):
lt_conditions = [f'Data[@Name="LogonType"]="{l}"' for l in lt]
conditions.append(f'(*[EventData[{ " or ".join(lt_conditions) }]])')
else:
conditions.append(f'(*[EventData[Data[@Name="LogonType"]="{lt}"]])')
if 'ProviderName' in data:
conditions.append(f'Provider[@Name="{data["ProviderName"]}"]')
if 'OperationType' in data:
ot = data['OperationType']
if isinstance(ot, list):
ot_conditions = [f'Data[@Name="OperationType"] = "{o}"' for o in ot]
conditions.append(f'({ " or ".join([f"*[EventData[{c}]]" for c in ot_conditions]) })')
else:
conditions.append(f'(*[EventData[Data[@Name="OperationType"] = "{ot}"]])')
if 'TargetUserSid' in data:
sid = data['TargetUserSid']
if isinstance(sid, list):
sid_conditions = [f'Data[@Name="TargetUserSid"] != "{s}"' for s in sid]
conditions.extend([f'(*[EventData[{c}]])' for c in sid_conditions])
else:
conditions.append(f'(*[EventData[Data[@Name="TargetUserSid"] != "{sid}"]])')
if 'QueryOptions' in data:
conditions.append(f'(*[EventData[Data[@Name="QueryOptions"]]="{data["QueryOptions"]}"])')
if 'QueryResults' in data:
conditions.append(f'(*[EventData[Data[@Name="QueryResults"]]="{data["QueryResults"]}"])')
return " and ".join(conditions)
def build_select(select_data):
"""Build <Select> element."""
path = select_data.get("Path", "Security")
condition = build_condition(select_data)
return f'*[System[{condition}]]'
def build_suppress(suppress_data):
"""Build <Suppress> element."""
path = suppress_data.get("Path", "Security")
condition = build_condition(suppress_data)
return f'*[System[{condition}]]'
def generate_xml(yaml_data):
"""Generate full XML from YAML data."""
root = ET.Element("QueryList")
for idx, item in enumerate(yaml_data):
query = ET.SubElement(root, "Query", Id=str(idx), Path=item.get("Path", "Security"))
comment = item.get("Comment")
if comment:
query.append(ET.Comment(f" {comment} "))
select_text = build_select(item["Select"])
ET.SubElement(query, "Select", Path=item["Select"]["Path"]).text = escape_xml(select_text)
if "Suppress" in item:
for suppress in item["Suppress"]:
suppress_text = build_suppress(suppress)
ET.SubElement(query, "Suppress", Path=suppress["Path"]).text = escape_xml(suppress_text)
return ET.tostring(root, encoding="unicode", xml_declaration=False)
def main():
with open("subscription_config.yaml", "r") as f:
yaml_data = yaml.safe_load(f)
xml_output = generate_xml(yaml_data)
print(xml_output)
if __name__ == "__main__":
main()