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
I'll create a Python script that converts a YAML configuration file to a Windows Subscription Query XML format. Here's the solution:
Python Script (yaml_to_subscription_query.py)
python
#!/usr/bin/env python3
"""
Windows Event Subscription Query Generator
Converts YAML configuration to Windows Subscription Query XML format
"""
import yaml
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import argparse
import sys
from pathlib import Path
from typing import Dict, List, Any
class SubscriptionQueryGenerator:
"""Generates Windows Subscription Query XML from YAML configuration"""
def __init__(self):
self.root = ET.Element("QueryList")
def escape_xml_content(self, content: str) -> str:
"""Escape special XML characters in content"""
# Note: ElementTree handles most escaping automatically,
# but we need to ensure consistency
return content
def add_query(self, query_config: Dict[str, Any]) -> None:
"""Add a query element to the XML"""
query_elem = ET.SubElement(
self.root,
"Query",
Id=str(query_config["id"]),
Path=query_config["path"]
)
# Add description as comment if provided
if "description" in query_config:
comment = ET.Comment(f" {query_config['description']} ")
query_elem.append(comment)
# Add Select elements
if "select" in query_config:
for select_item in query_config["select"]:
select_elem = ET.SubElement(
query_elem,
"Select",
Path=select_item["path"]
)
select_elem.text = select_item["filter"]
# Add Suppress elements
if "suppress" in query_config:
for suppress_item in query_config["suppress"]:
suppress_elem = ET.SubElement(
query_elem,
"Suppress",
Path=suppress_item["path"]
)
suppress_elem.text = suppress_item["filter"]
def generate_xml(self, config: Dict[str, Any]) -> str:
"""Generate the complete XML from configuration"""
# Clear any existing queries
self.root.clear()
self.root.tag = "QueryList"
self.root.attrib.clear()
# Add all queries
for query in config.get("queries", []):
self.add_query(query)
# Convert to string with proper formatting
xml_str = ET.tostring(self.root, encoding="unicode", method="xml")
# Pretty print the XML
dom = minidom.parseString(xml_str)
pretty_xml = dom.toprettyxml(indent=" ", encoding=None)
# Remove extra blank lines and fix formatting
lines = [line for line in pretty_xml.split('\n') if line.strip()]
# Skip the XML declaration line
if lines[0].startswith('<?xml'):
lines = lines[1:]
return '\n'.join(lines)
def load_yaml_config(file_path: Path) -> Dict[str, Any]:
"""Load and parse YAML configuration file"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
return yaml.safe_load(f)
except yaml.YAMLError as e:
print(f"Error parsing YAML file: {e}", file=sys.stderr)
sys.exit(1)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading file: {e}", file=sys.stderr)
sys.exit(1)
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Convert YAML config to Windows Subscription Query XML"
)
parser.add_argument(
"yaml_file",
type=Path,
help="Path to YAML configuration file"
)
parser.add_argument(
"-o", "--output",
type=Path,
help="Output XML file (default: print to stdout)"
)
args = parser.parse_args()
# Load YAML configuration
config = load_yaml_config(args.yaml_file)
# Generate XML
generator = SubscriptionQueryGenerator()
xml_output = generator.generate_xml(config)
# Output the result
if args.output:
try:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(xml_output)
print(f"XML successfully written to '{args.output}'")
except Exception as e:
print(f"Error writing output file: {e}", file=sys.stderr)
sys.exit(1)
else:
print(xml_output)
if __name__ == "__main__":
main()
YAML Configuration File (event_subscription.yaml)
yaml
Usage Instructions
Save the files:
Save the Python script as yaml_to_subscription_query.py
Save the YAML configuration as event_subscription.yaml
Install required dependencies:
bash
pip install pyyaml
Run the script:
bash
# Output to console
python yaml_to_subscription_query.py event_subscription.yaml
# Output to file
python yaml_to_subscription_query.py event_subscription.yaml -o output.xml
Copy the generated XML and paste it into the Windows Event Viewer subscription query GUI
Key Features
Clean YAML structure: Easy to read and maintain configuration
Supports comments: Descriptions are converted to XML comments
Multiple select/suppress filters: Can define multiple filters per query
Proper XML escaping: Handles special characters correctly