<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Usman on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Usman on Medium]]></description>
        <link>https://medium.com/@usmannazir5503?source=rss-b2b1ff46958f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eBJIMB8Tnt1x3Gqj</url>
            <title>Stories by Muhammad Usman on Medium</title>
            <link>https://medium.com/@usmannazir5503?source=rss-b2b1ff46958f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:24:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usmannazir5503/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Wazuh-TimeCapsule: Automated Chain-of-Custody Volatile Forensics Before Host Isolation on Wazuh]]></title>
            <link>https://medium.com/@usmannazir5503/wazuh-timecapsule-automated-chain-of-custody-volatile-forensics-before-host-isolation-on-wazuh-69540f7ff275?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/69540f7ff275</guid>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[digital-forensics]]></category>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[soc]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 17:21:48 GMT</pubDate>
            <atom:updated>2026-11-24T11:58:19.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wazuh-TimeCapsule: Automated Endpoint Isolation and Chain-of-Custody Forensics</h3><h3>Executive Summary</h3><p>When a canary file breach or unauthorized exfiltration attempt occurs on a Windows endpoint, Security Operations Center (SOC) responders face a critical race condition: isolating the host immediately severs active attacker sessions and prevents data loss, yet abrupt network quarantine or host shutdown destroys transient socket state before an analyst can inspect it. Conversely, running slow, full-host forensic collection scripts <em>before</em> isolating the machine leaves an active adversary connected and free to tamper with evidence or pivot laterally.</p><p><strong>Wazuh-TimeCapsule</strong> resolves this trade-off through an automated, low-latency Active Response pipeline built on <strong>Wazuh 4.14.9</strong> that enforces a strict <strong>Snapshot → Isolate → Seal</strong> containment sequence:</p><ul><li><strong>Phase 1 — Pre-Isolation Fast Network Snapshot (~200 ms):</strong> Upon detecting a high-severity canary breach via Windows kernel whodata File Integrity Monitoring (Rule 102501), the collector immediately snapshots the raw triggering alert (00_trigger_alert.json), active TCP/UDP sockets, ARP neighbor tables, and DNS client cache before network connections drop.</li><li><strong>Phase 2 — Immediate Host Isolation:</strong> Milliseconds after capturing network state, the script exports a baseline firewall backup, disables permissive Windows Defender Firewall rules to sever established attacker connections (such as active SMB or command-and-control sessions) mid-stream, and enforces a strict blockinbound,blockoutbound quarantine policy—keeping only TCP ports 1514 and 1515 open for encrypted Wazuh Agent-to-Manager telemetry.</li><li><strong>Phase 3 – Post-Isolation Forensics, Targeted User-Mode Memory &amp; SHA-256 Sealing: With the endpoint quarantined from external interference, the collector enumerates running process trees, active user sessions, services, and scheduled tasks. Using the exact process ID (PID) reported by Wazuh’s syscheck.audit.process telemetry, it runs Sysinternals procdump64.exe to acquire targeted user-mode process memory – preserving the suspect process’s private virtual address space, in-memory command arguments, loaded modules, and active heap/stack allocations while recording explicit audit decisions when alerts originate from kernel space (such as PID 4 / System).</strong></li></ul><p>Every artifact is hashed with SHA-256, audited for step-level collection errors inside CHAIN_OF_CUSTODY_MANIFEST.json, and compressed into a tamper-evident .zip evidence capsule. Once sealed, the endpoint emits a structured custody log back to the Wazuh Manager, firing a Level 12 attestation alert (Rule 102502) with the capsule&#39;s cryptographic digest so incident responders have verified, court-ready volatile evidence within seconds of detection.</p><h3>Architecture &amp; Lab Topology</h3><p>This implementation runs across a three-node virtualization lab on a shared host-only/bridged subnet:</p><p>The Wazuh-TimeCapsule lab environment consists of three interconnected systems operating across a shared virtualized network: a <strong>Wazuh Manager</strong> running the official Wazuh 4.14.9 OVA (Amazon Linux 2023) at 192.168.xx.xx, a <strong>Monitored Endpoint</strong> running on the <strong>Windows 11</strong> host (MIAN-USMAN) at 10.150.xx.xx with Wazuh Agent 4.14.9 installed, and an <strong>Attacker Machine</strong> running <strong>Kali Linux </strong>inside VirtualBox on the 10.150.74.x subnet.</p><p>Under normal operating conditions before an intrusion occurs, the Kali Linux virtual machine has direct network reachability to the Windows 11 endpoint over ICMP and TCP port 445 (SMB), while the Windows 11 Wazuh Agent maintains a persistent encrypted channel to the Wazuh Manager over TCP port 1514 for log ingestion and Active Response execution, alongside TCP port 1515 for agent registration. Internally on the Windows 11 host, kernel-level whodata File Integrity Monitoring continuously watches the C:\Company_Secrets canary directory and pairs with Microsoft Sysinternals procdump64.exe and the custom PowerShell Active Response engine.</p><p>When the Kali Linux attacker authenticates over SMB and writes a staging file into C:\Company_Secrets, the Windows 11 agent streams the whodata telemetry to wazuh-analysisd on the Wazuh Manager, firing Level-15 Rule 102501. The Wazuh Manager immediately dispatches an Active Response execution command back down TCP port 1514 to the Windows 11 endpoint, where Phase 1 captures volatile network and process state, dumps target process memory, seals the SHA-256-attested ZIP capsule inside C:\Forensics-Vault\, and ships the Chain-of-Custody JSON event to trigger Level-12 Rule 102502. Immediately afterward, Phase 2 locks down Windows Defender Firewall across all profiles to drop 100% of inbound and outbound traffic—cutting off the Kali Linux attacker completely—while leaving a surgical firewall exception open on TCP ports 1514 and 1515 exclusively for the Wazuh Manager IP so telemetry and remote quarantine release remain intact.</p><h3><strong>Lab Safety Note (Dedicated Endpoint VM):</strong></h3><p>Deploy the monitored Windows 11 endpoint as a dedicated VirtualBox VM rather than installing the agent directly on your physical host workstation. Running the endpoint in its own VM prevents quarantine tests from cutting off your primary workstation’s internet access and lets you use VirtualBox Snapshots for instant pre-attack rollback.</p><h3>End-to-End Execution Pipeline</h3><ol><li><strong>Canary Tripwire (</strong><strong>C:\Company_Secrets\):</strong> A decoy directory containing realistic fake cloud and database credentials is monitored via Wazuh&#39;s kernel-level whodata=&quot;yes&quot; File Integrity Monitoring (FIM).</li><li><strong>Level-15 Detection (</strong><strong>Rule 102501):</strong> When an attacker accesses or writes a staging file into the canary directory over SMB, Wazuh fires Rule 102501 and dispatches an add Active Response command to the Windows 11 agent.</li></ol><ul><li><strong>Phase 1 (Pre-Isolation — ~200 ms):</strong> Capture 00_trigger_alert.json, active TCP/UDP sockets, ARP cache, and DNS cache before sockets drop.</li><li><strong>Phase 2 (Immediate Containment):</strong> Export baseline Windows Firewall rules (pre_isolation_firewall.wfw), disable existing allow rules to sever live attacker sessions, allow only TCP 1514/1515 to the Wazuh Manager, and enforce blockinbound,blockoutbound.</li><li><strong>Phase 3 (Post-Isolation Forensics &amp; Sealing):</strong> Collect running processes, local user session (Win32_ComputerSystem), services, and scheduled tasks; dump <strong>only the specific user-mode PID</strong> reported by Wazuh whodata (syscheck.audit.process); audit all step errors into CHAIN_OF_CUSTODY_MANIFEST.json; and seal the capsule into a SHA-256-hashed .zip.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkfKePZttHU1L_eMzjRweg.png" /><figcaption>Architecture Demonstration</figcaption></figure><h3>Step 1: Preparing the Windows 11 Endpoint &amp; Canary Trap</h3><p>All commands in this section are executed in <strong>PowerShell as Administrator</strong> on the <strong>Windows 11 Host</strong>.</p><h3>1.1 Verify the Wazuh Agent Service</h3><p>Confirm that the Wazuh Agent service is installed and actively communicating with your Wazuh OVA:</p><pre>Get-Service -Name WazuhSvc</pre><h3>1.2 Create the Forensic Vault &amp; Install Sysinternals ProcDump</h3><p>Create C:\Forensics-Vault to store sealed evidence archives and C:\Program Files\Sysinternals to host Microsoft&#39;s official memory-dumping utility (procdump64.exe):</p><p>Powershell:</p><pre>New-Item -ItemType Directory -Force -Path &quot;C:\Forensics-Vault&quot;<br>New-Item -ItemType Directory -Force -Path &quot;C:\Program Files\Sysinternals&quot;<br><br>Invoke-WebRequest -Uri &quot;https://live.sysinternals.com/procdump64.exe&quot; -OutFile &quot;C:\Program Files\Sysinternals\procdump64.exe&quot;<br>Test-Path &quot;C:\Program Files\Sysinternals\procdump64.exe&quot;</pre><h3>1.3 Deploy the Decoy Canary Directory (C:\Company_Secrets)</h3><p>Create a high-value decoy directory populated with realistic fake environment secrets that no legitimate user or background service ever touches:</p><p>Powershell Command:</p><pre>New-Item -ItemType Directory -Force -Path &quot;C:\Company_Secrets&quot;<br><br>@&quot;<br>AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE<br>AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY<br>DATABASE_ADMIN_PASSWORD=ProdSqlMaster2026!<br>VPN_GATEWAY=vpn.corp.internal<br>&quot;@ | Out-File -FilePath &quot;C:\Company_Secrets\prod_aws_keys.env&quot; -Encoding UTF8</pre><h3>1.4 Configure Windows whodata FIM &amp; JSON Log Forwarding</h3><p>Back up ossec.conf and open it for editing:</p><p>PowerShell Command:</p><pre>Copy-Item &quot;C:\Program Files (x86)\ossec-agent\ossec.conf&quot; &quot;C:\Program Files (x86)\ossec-agent\ossec.conf.bak&quot;<br>notepad &quot;C:\Program Files (x86)\ossec-agent\ossec.conf&quot;</pre><p>Inside the &lt;syscheck&gt; section (directly beneath the Startup directory entry), add the whodata=&quot;yes&quot; monitor for C:\Company_Secrets:</p><pre>&lt;directories realtime=&quot;yes&quot;&gt;%PROGRAMDATA%\Microsoft\Windows\Start Menu\Programs\Startup&lt;/directories&gt;<br>  &lt;directories check_all=&quot;yes&quot; whodata=&quot;yes&quot; report_changes=&quot;no&quot;&gt;C:\Company_Secrets&lt;/directories&gt;</pre><p>Scroll to the bottom of ossec.conf (right above &lt;/ossec_config&gt;) and add a &lt;localfile&gt; block so the agent ingests our script&#39;s Chain-of-Custody JSON log:</p><pre>&lt;localfile&gt;<br>    &lt;log_format&gt;json&lt;/log_format&gt;<br>    &lt;location&gt;C:\Program Files (x86)\ossec-agent\logs\timecapsule-custody.json&lt;/location&gt;<br>  &lt;/localfile&gt;</pre><p>Save and close ossec.conf, pre-create the logs directory and JSON file, and restart WazuhSvc:</p><p>Powershell Command:</p><pre>New-Item -ItemType Directory -Force -Path &quot;C:\Program Files (x86)\ossec-agent\logs&quot; | Out-Null<br>New-Item -ItemType File -Force -Path &quot;C:\Program Files (x86)\ossec-agent\logs\timecapsule-custody.json&quot; | Out-Null<br>Restart-Service -Name WazuhSvc</pre><p>Verify in ossec.log that Windows whodata initialized on C:\Company_Secrets:</p><p>Powershell Command:</p><pre>Select-String -Path &quot;C:\Program Files (x86)\ossec-agent\ossec.log&quot; -Pattern &quot;Company_Secrets&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOk2CQe9317BJgrXcF8JsA.png" /><figcaption>Screenshot showing the &lt;directories check_all=&quot;yes&quot; whodata=&quot;yes&quot; ...&gt;C:\Company_Secrets&lt;/directories&gt;</figcaption></figure><h3>Step 2: Building the Finalized Active Response Scripts on Windows 11</h3><p>On Windows endpoints, Wazuh’s wazuh-execd daemon natively executes .cmd or .exe binaries inside C:\Program Files (x86)\ossec-agent\active-response\bin\ and passes the triggering alert JSON over Standard Input (STDIN).</p><h3>2.1 Engineering Notes from Live Testing</h3><p>During lab validation on Windows 11, two critical edge cases were resolved in the finalized script below:</p><ul><li><strong>Preventing Hidden UTF-8 BOM Corruption:</strong> PowerShell 5.1’s Add-Content -Encoding UTF8 prepends a Byte Order Mark (\xef\xbb\xbf) to new files, which causes Wazuh&#39;s json decoder to reject the first log line. Using [System.IO.File]::AppendAllText with UTF8Encoding($false) writes clean, BOM-free UTF-8 JSON.</li><li><strong>Overriding Pre-Existing Firewall Allow Rules:</strong> Setting firewallpolicy blockinbound,blockoutbound alone does not block traffic matched by explicit Windows Allow rules (such as File and Printer Sharing (ICMPv4-In) or SMB-In). Exporting pre_isolation_firewall.wfw and running netsh advfirewall firewall set rule name=all new enable=no guarantees complete isolation while preserving exact state restoration on delete.</li></ul><h3>2.2 Create wazuh-timecapsule.ps1</h3><p>Open the PowerShell script file in Notepad:</p><pre>notepad &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule.ps1&quot;</pre><p>Paste the complete finalized script below (update $WAZUH_MANAGER_IP to match your Wazuh OVA IP address):</p><pre>&lt;#<br>.SYNOPSIS<br>    Wazuh-TimeCapsule: Low-Latency Host Isolation &amp; Chain-of-Custody Volatile Forensics (Windows 11)<br>.DESCRIPTION<br>    Author: Muhammad Usman<br>    Target: Wazuh 4.14.9+ Windows Endpoint Agent<br>    Workflow:<br>      1. Fast Network Snapshot (~200ms pre-isolation: trigger alert, TCP/UDP, ARP, DNS)<br>      2. Immediate Host Isolation (cuts active attacker sessions; preserves TCP 1514/1515)<br>      3. Post-Isolation Host State, Alert-Targeted User-Mode Process Dump, Error-Audited SHA-256 Manifest &amp; ZIP Seal<br>#&gt;<br><br>$ErrorActionPreference = &quot;Continue&quot;<br><br># ==============================================================================<br># CONFIGURATION<br># ==============================================================================<br>$WAZUH_MANAGER_IP      = &quot;10.150.74.190&quot;<br>$AUTO_ROLLBACK_SECONDS = 60<br>$VAULT_BASE_DIR        = &quot;C:\Forensics-Vault&quot;<br>$AR_LOG_FILE           = &quot;C:\Forensics-Vault\timecapsule-ar.log&quot;<br>$CUSTODY_LOG_FILE      = &quot;C:\Program Files (x86)\ossec-agent\logs\timecapsule-custody.json&quot;<br>$PROCDUMP_BIN          = &quot;C:\Program Files\Sysinternals\procdump64.exe&quot;<br>$FW_BACKUP_FILE        = &quot;C:\Forensics-Vault\pre_isolation_firewall.wfw&quot;<br><br>function Write-ArLog {<br>    param([string]$Message)<br>    $ts = (Get-Date).ToUniversalTime().ToString(&quot;yyyy-MM-dd HH:mm:ss &#39;UTC&#39;&quot;)<br>    Add-Content -Path $AR_LOG_FILE -Value &quot;$ts wazuh-timecapsule: $Message&quot; -Encoding UTF8<br>}<br><br>function Write-Utf8NoBom {<br>    param([string]$Path, [string]$Content)<br>    [System.IO.File]::WriteAllText($Path, $Content, (New-Object System.Text.UTF8Encoding($false)))<br>}<br><br>function Invoke-ForensicStep {<br>    param(<br>        [string]$StepName,<br>        [System.Collections.Generic.List[object]]$ErrorList,<br>        [scriptblock]$Action<br>    )<br>    try {<br>        $ErrorActionPreference = &quot;Stop&quot;<br>        &amp; $Action<br>    }<br>    catch {<br>        $errMsg = $_.Exception.Message<br>        Write-ArLog &quot;ERROR in [$StepName]: $errMsg&quot;<br>        $ErrorList.Add([PSCustomObject]@{<br>            step      = $StepName<br>            error     = $errMsg<br>            timestamp = (Get-Date).ToUniversalTime().ToString(&quot;o&quot;)<br>        })<br>    }<br>    finally {<br>        $ErrorActionPreference = &quot;Continue&quot;<br>    }<br>}<br><br># ==============================================================================<br># PHASE 1 (PRE-ISOLATION): Fast Volatile Network State Snapshot<br># ==============================================================================<br>function Invoke-FastNetworkSnapshot {<br>    param(<br>        [psobject]$AlertObj,<br>        [string]$WorkDir,<br>        [System.Collections.Generic.List[object]]$ErrorList<br>    )<br><br>    Invoke-ForensicStep -StepName &quot;00_trigger_alert&quot; -ErrorList $ErrorList -Action {<br>        $alertJson = $AlertObj | ConvertTo-Json -Depth 10<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;00_trigger_alert.json&quot;) -Content $alertJson<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;01_tcp_connections&quot; -ErrorList $ErrorList -Action {<br>        $tcp = Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;01_tcp_connections.txt&quot;) -Content $tcp<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;02_udp_endpoints&quot; -ErrorList $ErrorList -Action {<br>        $udp = Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;02_udp_endpoints.txt&quot;) -Content $udp<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;03_arp_cache&quot; -ErrorList $ErrorList -Action {<br>        $arp = Get-NetNeighbor | Select-Object InterfaceAlias, IPAddress, LinkLayerAddress, State |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;03_arp_cache.txt&quot;) -Content $arp<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;04_dns_client_cache&quot; -ErrorList $ErrorList -Action {<br>        $dns = Get-DnsClientCache | Select-Object Entry, Name, Data, TimeToLive |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;04_dns_client_cache.txt&quot;) -Content $dns<br>    }<br>}<br><br># ==============================================================================<br># PHASE 2 (IMMEDIATE CONTAINMENT): Isolate Host While Preserving Wazuh Ports<br># ==============================================================================<br>function Invoke-IsolateHost {<br>    Write-ArLog &quot;Isolating host immediately (allowing ONLY Wazuh Manager $WAZUH_MANAGER_IP on TCP 1514/1515)...&quot;<br><br>    if (-not (Test-Path $FW_BACKUP_FILE)) {<br>        netsh advfirewall export $FW_BACKUP_FILE | Out-Null<br>    }<br><br>    # Disable all pre-existing Allow rules to sever active SMB/RDP/reverse-shell flows<br>    netsh advfirewall firewall set rule name=all new enable=no | Out-Null<br>    netsh advfirewall firewall delete rule name=&quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot; | Out-Null<br><br>    # Keep Wazuh Agent &lt;-&gt; Manager encrypted channel open<br>    netsh advfirewall firewall add rule name=&quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot; dir=out action=allow protocol=TCP remoteip=$WAZUH_MANAGER_IP remoteport=1514,1515 | Out-Null<br>    netsh advfirewall firewall add rule name=&quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot; dir=in action=allow protocol=TCP remoteip=$WAZUH_MANAGER_IP localport=1514,1515 | Out-Null<br><br>    # Enforce strict blockinbound,blockoutbound across Domain, Private, and Public profiles<br>    netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound | Out-Null<br><br>    Write-ArLog &quot;Host network isolation ACTIVE.&quot;<br>}<br><br># ==============================================================================<br># PHASE 3 (POST-ISOLATION): Host State, Alert-Targeted Process Dump &amp; Custody Seal<br># ==============================================================================<br>function Invoke-PostIsolationForensicsAndSeal {<br>    param(<br>        [psobject]$AlertObj,<br>        [string]$CaseId,<br>        [datetime]$NowUtc,<br>        [string]$WorkDir,<br>        [System.Collections.Generic.List[object]]$ErrorList<br>    )<br><br>    Write-ArLog &quot;[$CaseId] Collecting post-isolation host state &amp; alert-targeted process memory...&quot;<br><br>    Invoke-ForensicStep -StepName &quot;05_process_tree_cmdlines&quot; -ErrorList $ErrorList -Action {<br>        $procs = Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, Name, ExecutablePath, CommandLine, CreationDate |<br>            Format-Table -AutoSize | Out-String -Width 500<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;05_process_tree_cmdlines.txt&quot;) -Content $procs<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;06_active_user_sessions&quot; -ErrorList $ErrorList -Action {<br>        $sessions = Get-CimInstance Win32_ComputerSystem | Select-Object Name, Domain, UserName | Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;06_active_user_sessions.txt&quot;) -Content $sessions<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;07_running_services&quot; -ErrorList $ErrorList -Action {<br>        $svcs = Get-Service | Where-Object { $_.Status -eq &quot;Running&quot; } | Select-Object Name, DisplayName, StartType |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;07_running_services.txt&quot;) -Content $svcs<br>    }<br><br>    Invoke-ForensicStep -StepName &quot;08_scheduled_tasks&quot; -ErrorList $ErrorList -Action {<br>        $tasks = Get-ScheduledTask | Where-Object { $_.State -ne &quot;Disabled&quot; } | Select-Object TaskName, TaskPath, State |<br>            Format-Table -AutoSize | Out-String -Width 300<br>        Write-Utf8NoBom -Path (Join-Path $WorkDir &quot;08_scheduled_tasks.txt&quot;) -Content $tasks<br>    }<br><br>    # Alert-Targeted User-Mode Process Memory Capture (from Wazuh whodata telemetry)<br>    $dumpDecisions = New-Object System.Collections.Generic.List[object]<br>    $triggerPid    = 0<br>    $triggerName   = &quot;unknown&quot;<br>    $rawPid        = $null<br><br>    if ($AlertObj.syscheck -and $AlertObj.syscheck.audit) {<br>        if ($AlertObj.syscheck.audit.process) {<br>            $rawPid = $AlertObj.syscheck.audit.process.id<br>            if ($AlertObj.syscheck.audit.process.name) { $triggerName = [string]$AlertObj.syscheck.audit.process.name }<br>        }<br>        elseif ($AlertObj.syscheck.audit.process_id) {<br>            $rawPid = $AlertObj.syscheck.audit.process_id<br>            if ($AlertObj.syscheck.audit.process_name) { $triggerName = [string]$AlertObj.syscheck.audit.process_name }<br>        }<br>    }<br>    [void][int]::TryParse([string]$rawPid, [ref]$triggerPid)<br><br>    if ($triggerPid -le 0) {<br>        $dumpDecisions.Add([PSCustomObject]@{<br>            target_pid       = $null<br>            target_process   = &quot;N/A&quot;<br>            action           = &quot;skipped&quot;<br>            selection_reason = &quot;Triggering alert lacked a numeric syscheck.audit process ID; avoided dumping unrelated user sessions.&quot;<br>        })<br>    }<br>    elseif ($triggerPid -le 4) {<br>        $dumpDecisions.Add([PSCustomObject]@{<br>            target_pid       = $triggerPid<br>            target_process   = $triggerName<br>            action           = &quot;skipped&quot;<br>            selection_reason = &quot;Alert triggered by kernel System process (PID $triggerPid, e.g., remote SMB server thread); user-mode ProcDump is not applicable.&quot;<br>        })<br>    }<br>    elseif ($triggerPid -eq $PID) {<br>        $dumpDecisions.Add([PSCustomObject]@{<br>            target_pid       = $triggerPid<br>            target_process   = $triggerName<br>            action           = &quot;skipped&quot;<br>            selection_reason = &quot;Triggering PID matches active forensic collector process; skipped self-dump.&quot;<br>        })<br>    }<br>    else {<br>        $liveProc = Get-Process -Id $triggerPid -ErrorAction SilentlyContinue<br>        if (-not $liveProc) {<br>            $dumpDecisions.Add([PSCustomObject]@{<br>                target_pid       = $triggerPid<br>                target_process   = $triggerName<br>                action           = &quot;skipped&quot;<br>                selection_reason = &quot;Triggering process (PID $triggerPid, $triggerName) already exited before dump execution.&quot;<br>            })<br>        }<br>        elseif (-not (Test-Path $PROCDUMP_BIN)) {<br>            $missingMsg = &quot;ProcDump binary not found at $PROCDUMP_BIN.&quot;<br>            Write-ArLog &quot;ERROR in [09_procdump_pid_$triggerPid]: $missingMsg&quot;<br>            $dumpDecisions.Add([PSCustomObject]@{<br>                target_pid       = $triggerPid<br>                target_process   = $triggerName<br>                action           = &quot;failed&quot;<br>                selection_reason = $missingMsg<br>            })<br>            $ErrorList.Add([PSCustomObject]@{<br>                step      = &quot;09_procdump_pid_$triggerPid&quot;<br>                error     = $missingMsg<br>                timestamp = (Get-Date).ToUniversalTime().ToString(&quot;o&quot;)<br>            })<br>        }<br>        else {<br>            Invoke-ForensicStep -StepName &quot;09_procdump_pid_$triggerPid&quot; -ErrorList $ErrorList -Action {<br>                $memDir = Join-Path $WorkDir &quot;09_process_memory_dumps&quot;<br>                New-Item -ItemType Directory -Force -Path $memDir | Out-Null<br>                $safeName = ($liveProc.ProcessName -replace &#39;[^a-zA-Z0-9_.-]&#39;, &#39;_&#39;)<br>                $dumpFile = Join-Path $memDir &quot;${safeName}_PID${triggerPid}.dmp&quot;<br><br>                &amp; $PROCDUMP_BIN -accepteula -ma $triggerPid $dumpFile | Out-Null<br>                if (-not (Test-Path $dumpFile)) {<br>                    throw &quot;ProcDump exited with code $LASTEXITCODE without producing $dumpFile&quot;<br>                }<br><br>                $dumpDecisions.Add([PSCustomObject]@{<br>                    target_pid       = $triggerPid<br>                    target_process   = $liveProc.ProcessName<br>                    action           = &quot;dumped&quot;<br>                    dump_file        = &quot;09_process_memory_dumps\${safeName}_PID${triggerPid}.dmp&quot;<br>                    selection_reason = &quot;Exact process ID ($triggerPid) and image ($triggerName) reported by Wazuh whodata FIM audit telemetry.&quot;<br>                })<br>            }<br>        }<br>    }<br><br>    $memDumpCount = @($dumpDecisions | Where-Object { $_.action -eq &quot;dumped&quot; }).Count<br><br>    # Compute SHA-256 digests for all collected evidence files<br>    $artifacts = New-Object System.Collections.Generic.List[object]<br>    $allFiles  = Get-ChildItem -Path $WorkDir -Recurse -File | Sort-Object FullName<br>    foreach ($f in $allFiles) {<br>        $hashObj = Get-FileHash -Path $f.FullName -Algorithm SHA256<br>        $relPath = $f.FullName.Substring($WorkDir.Length + 1)<br>        $artifacts.Add([PSCustomObject]@{<br>            relative_path = $relPath<br>            size_bytes    = $f.Length<br>            sha256        = $hashObj.Hash.ToLower()<br>        })<br>    }<br><br>    $ruleId   = if ($AlertObj.rule.id) { [string]$AlertObj.rule.id } else { &quot;unknown&quot; }<br>    $alertId  = if ($AlertObj.id) { [string]$AlertObj.id } else { &quot;unknown&quot; }<br>    $ruleDesc = if ($AlertObj.rule.description) { [string]$AlertObj.rule.description } else { &quot;Canary FIM breach&quot; }<br><br>    $manifest = [PSCustomObject]@{<br>        framework                = &quot;Wazuh-TimeCapsule&quot;<br>        author                   = &quot;Muhammad Usman&quot;<br>        platform                 = &quot;Windows Endpoint&quot;<br>        memory_acquisition_scope = &quot;targeted_user_mode_process_only&quot;<br>        case_id                  = $CaseId<br>        captured_at_utc          = $NowUtc.ToString(&quot;o&quot;)<br>        host                     = $env:COMPUTERNAME<br>        trigger_alert_id         = $alertId<br>        trigger_rule_id          = $ruleId<br>        trigger_rule_description = $ruleDesc<br>        process_dump_decisions   = @($dumpDecisions.ToArray())<br>        process_dumps_captured   = $memDumpCount<br>        collection_error_count   = $ErrorList.Count<br>        collection_errors        = @($ErrorList.ToArray())<br>        artifact_count           = $artifacts.Count<br>        artifacts                = @($artifacts.ToArray())<br>    }<br><br>    $manifestPath = Join-Path $WorkDir &quot;CHAIN_OF_CUSTODY_MANIFEST.json&quot;<br>    $manifestJson = $manifest | ConvertTo-Json -Depth 10<br>    Write-Utf8NoBom -Path $manifestPath -Content $manifestJson<br>    Write-ArLog &quot;[$CaseId] Manifest written ($($artifacts.Count) artifacts, $($ErrorList.Count) errors).&quot;<br><br>    # Compress evidence folder into tamper-evident ZIP (with retry for Defender AV scan locks)<br>    Add-Type -AssemblyName System.IO.Compression.FileSystem<br>    $zipPath = Join-Path $VAULT_BASE_DIR &quot;$CaseId.zip&quot;<br>    if (Test-Path $zipPath) { Remove-Item $zipPath -Force }<br>    for ($attempt = 1; $attempt -le 3; $attempt++) {<br>        try {<br>            Start-Sleep -Milliseconds 500<br>            [System.IO.Compression.ZipFile]::CreateFromDirectory($WorkDir, $zipPath)<br>            break<br>        }<br>        catch {<br>            Write-ArLog &quot;[$CaseId] ZIP attempt $attempt failed: $($_.Exception.Message)&quot;<br>            if ($attempt -eq 3) { throw }<br>        }<br>    }<br>    $zipHash = (Get-FileHash -Path $zipPath -Algorithm SHA256).Hash.ToLower()<br><br>    Remove-Item -Path $WorkDir -Recurse -Force<br><br>    # Emit single-line BOM-free JSON custody event to Wazuh Manager (Rule 102502)<br>    $custodyEvent = [PSCustomObject]@{<br>        integration       = &quot;wazuh-timecapsule&quot;<br>        action            = &quot;capsule_sealed&quot;<br>        case_id           = $CaseId<br>        host              = $env:COMPUTERNAME<br>        trigger_rule_id   = $ruleId<br>        capsule_path      = $zipPath<br>        capsule_sha256    = $zipHash<br>        artifact_count    = $artifacts.Count<br>        ram_dumps         = $memDumpCount<br>        collection_errors = $ErrorList.Count<br>        timestamp_utc     = $NowUtc.ToString(&quot;o&quot;)<br>    }<br>    $jsonLine = $custodyEvent | ConvertTo-Json -Compress<br>    New-Item -ItemType Directory -Force -Path (Split-Path $CUSTODY_LOG_FILE) | Out-Null<br>    [System.IO.File]::AppendAllText($CUSTODY_LOG_FILE, &quot;$jsonLine`r`n&quot;, (New-Object System.Text.UTF8Encoding($false)))<br><br>    Write-ArLog &quot;[$CaseId] Capsule sealed: $zipPath | SHA256=$zipHash | Errors=$($ErrorList.Count)&quot;<br>    if ($AUTO_ROLLBACK_SECONDS -gt 0) {<br>        Write-ArLog &quot;[$CaseId] Scheduling automatic isolation rollback in $AUTO_ROLLBACK_SECONDS seconds...&quot;<br>        $psCmd = &quot;Start-Sleep -Seconds $AUTO_ROLLBACK_SECONDS; (&#39;{&#39; + [char]34 + &#39;command&#39; + [char]34 + &#39;:&#39; + [char]34 + &#39;delete&#39; + [char]34 + &#39;}&#39;) | &amp; &#39;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule.cmd&#39;&quot;<br>        Start-Process -FilePath &quot;powershell.exe&quot; -ArgumentList &quot;-NoProfile&quot;, &quot;-ExecutionPolicy&quot;, &quot;Bypass&quot;, &quot;-Command&quot;, $psCmd -WindowStyle Hidden<br>    }<br>}<br><br>function Invoke-LiftIsolation {<br>    Write-ArLog &quot;Lifting endpoint network isolation...&quot;<br>    netsh advfirewall firewall delete rule name=&quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot; | Out-Null<br>    if (Test-Path $FW_BACKUP_FILE) {<br>        netsh advfirewall import $FW_BACKUP_FILE | Out-Null<br>        Remove-Item -Path $FW_BACKUP_FILE -Force<br>    }<br>    else {<br>        netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound | Out-Null<br>    }<br>    Write-ArLog &quot;Endpoint network isolation LIFTED.&quot;<br>}<br><br># ==============================================================================<br># MAIN ENTRYPOINT<br># ==============================================================================<br>$rawInput = [Console]::In.ReadLine()<br>if ([string]::IsNullOrWhiteSpace($rawInput)) { exit 0 }<br><br>try {<br>    $msg = $rawInput | ConvertFrom-Json<br>}<br>catch {<br>    Write-ArLog &quot;Failed to parse JSON from STDIN: $_&quot;<br>    exit 1<br>}<br><br>$command  = [string]$msg.command<br>$alertObj = $msg.parameters.alert<br><br>if ($command -eq &quot;add&quot;) {<br>    try {<br>        $existingRule = netsh advfirewall firewall show rule name=&quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot; 2&gt;&amp;1<br>        if ($existingRule -match &quot;WAZUH_TIMECAPSULE_ALLOW_MANAGER&quot;) {<br>            Write-ArLog &quot;Host already isolated; skipping duplicate execution.&quot;<br>            exit 0<br>        }<br><br>        $nowUtc    = (Get-Date).ToUniversalTime()<br>        $tsSlug    = $nowUtc.ToString(&quot;yyyyMMddTHHmmssZ&quot;)<br>        $ruleId    = if ($alertObj.rule.id) { [string]$alertObj.rule.id } else { &quot;unknown&quot; }<br>        $caseId    = &quot;TC-$($env:COMPUTERNAME)-$tsSlug-R$ruleId&quot;<br>        $workDir   = Join-Path $VAULT_BASE_DIR $caseId<br>        $errorList = New-Object System.Collections.Generic.List[object]<br><br>        New-Item -ItemType Directory -Force -Path $workDir | Out-Null<br><br>        # 1. Millisecond network snapshot BEFORE cutting connections<br>        Invoke-FastNetworkSnapshot -AlertObj $alertObj -WorkDir $workDir -ErrorList $errorList<br><br>        # 2. Immediate firewall isolation (RAM stays intact; TCP 1514/1515 stays open)<br>        Invoke-IsolateHost<br><br>        # 3. Slow host forensics, alert-targeted RAM dump, SHA-256 manifest &amp; custody alert<br>        Invoke-PostIsolationForensicsAndSeal -AlertObj $alertObj -CaseId $caseId -NowUtc $nowUtc -WorkDir $workDir -ErrorList $errorList<br>    }<br>    catch {<br>        Write-ArLog &quot;FATAL ERROR at line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)&quot;<br>        exit 1<br>    }<br>}<br>elseif ($command -eq &quot;delete&quot;) {<br>    Invoke-LiftIsolation<br>}</pre><h3><strong>2.3 Create the Batch Wrapper (wazuh-timecapsule.cmd)</strong></h3><p>Create the .cmd launcher and verify that neither file has a hidden .txt extension:</p><p>Powershell Command:</p><pre>@&#39;<br>@echo off<br>powershell.exe -NoProfile -ExecutionPolicy Bypass -File &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule.ps1&quot;<br>&#39;@ | Out-File -FilePath &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule.cmd&quot; -Encoding ASCII<br><br>Get-ChildItem &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule*&quot; | Select-Object Name</pre><h3>Step 3: Configuring Detection Rules &amp; Active Response on Wazuh OVA 4.14.9</h3><p>Log into your <strong>Wazuh 4.14.9 OVA</strong> console or SSH session and escalate to root:</p><pre>sudo -i</pre><h3>3.1 Create Conflict-Free Detection Rules (102501 &amp; 102502)</h3><p>When authoring custom Wazuh rules, three schema constraints must be respected:</p><ol><li><strong>Unique Custom IDs (</strong><strong>100000–</strong><strong>120000):</strong> Using 102501 and 102502 prevents WARNING: (7612) rule ID collisions.</li><li><strong>Valid FIM Parent SIDs (</strong><strong>550,553,554):</strong> Modern Wazuh 4.14.10 uses 550 (modified), 553 (deleted), and 554 (added) for FIM events.</li><li><strong>No Reserved Static Field Names (</strong><strong>action):</strong> In Wazuh&#39;s rule parser, &lt;field name=&quot;action&quot;&gt; is a reserved static field that triggers ERROR: Failure to read rule 102502. Field &#39;action&#39; is static. Matching &lt;field name=&quot;integration&quot;&gt;^wazuh-timecapsule$&lt;/field&gt; uniquely identifies the custody event without touching reserved keywords.</li></ol><p>Create /var/ossec/etc/rules/timecapsule_rules.xml:</p><pre>nano /var/ossec/etc/rules/timecapsule_rules.xml</pre><pre>&lt;group name=&quot;wazuh_timecapsule,dfir,deception,&quot;&gt;<br><br>  &lt;!-- Rule 102501: Windows Canary File Modified/Created/Deleted (Level 15) --&gt;<br>  &lt;rule id=&quot;102501&quot; level=&quot;15&quot;&gt;<br>    &lt;if_sid&gt;550,553,554&lt;/if_sid&gt;<br>    &lt;field name=&quot;file&quot; type=&quot;pcre2&quot;&gt;(?i)^c:\\company_secrets\\&lt;/field&gt;<br>    &lt;description&gt;Wazuh-TimeCapsule Canary Triggered: Unauthorized activity on $(file)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1552.001&lt;/id&gt;<br>      &lt;id&gt;T1005&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br><br>  &lt;!-- Rule 102502: Chain-of-Custody Forensic Capsule Sealed Alert (Level 12) --&gt;<br>  &lt;rule id=&quot;102502&quot; level=&quot;12&quot;&gt;<br>    &lt;decoded_as&gt;json&lt;/decoded_as&gt;<br>    &lt;field name=&quot;integration&quot;&gt;^wazuh-timecapsule$&lt;/field&gt;<br>    &lt;description&gt;Wazuh-TimeCapsule Evidence Sealed [$(case_id)] | SHA-256: $(capsule_sha256) | Files: $(artifact_count)&lt;/description&gt;<br>    &lt;group&gt;chain_of_custody,forensics,&lt;/group&gt;<br>  &lt;/rule&gt;<br><br>&lt;/group&gt;</pre><p>After pasting these rules in the file to save the file pres ctrl + O then enter after that press ctrl + X.</p><p>To give proper permissions to this file run these commands in wazuh manager terminal:</p><pre>chown wazuh:wazuh /var/ossec/etc/rules/timecapsule_rules.xml<br>chmod 660 /var/ossec/etc/rules/timecapsule_rules.xml</pre><h3>3.2 Register the Active Response Command in ossec.conf</h3><p>Back up /var/ossec/etc/ossec.conf and add the &lt;command&gt; and &lt;active-response&gt; definitions inside &lt;ossec_config&gt;:</p><pre>nano /var/ossec/etc/ossec.conf</pre><p>Add these blocks alongside your existing &lt;command&gt; and &lt;active-response&gt; entries (use &lt;timeout&gt;0&lt;/timeout&gt; for permanent quarantine until analyst release, or &lt;timeout&gt;60&lt;/timeout&gt; for automatic 60-second recovery during single-host testing):</p><pre>&lt;command&gt;<br>  &lt;name&gt;wazuh-timecapsule&lt;/name&gt;<br>  &lt;executable&gt;wazuh-timecapsule.cmd&lt;/executable&gt;<br>  &lt;timeout_allowed&gt;yes&lt;/timeout_allowed&gt;<br>&lt;/command&gt;<br><br>&lt;active-response&gt;<br>  &lt;disabled&gt;no&lt;/disabled&gt;<br>  &lt;command&gt;wazuh-timecapsule&lt;/command&gt;<br>  &lt;location&gt;local&lt;/location&gt;<br>  &lt;rules_id&gt;102501&lt;/rules_id&gt;<br>  &lt;timeout&gt;0&lt;/timeout&gt;<br>&lt;/active-response&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLp3EVd6MKSf3C4CrbClIg.png" /><figcaption>ossec.conf sections that need to be added</figcaption></figure><h3>3.3 Validate Ruleset Syntax &amp; Restart Wazuh Manager</h3><p>Run Wazuh’s configuration validator and restart the manager:</p><pre>/var/ossec/bin/wazuh-analysisd -t &amp;&amp; systemctl restart wazuh-manager</pre><p>On Windows 11, verify that ar.conf synced the new command automatically:</p><p>Powershell Command:</p><pre>Get-Content &quot;C:\Program Files (x86)\ossec-agent\etc\shared\ar.conf&quot;</pre><h3>Step 4: Validating Detections with wazuh-logtest &amp; alerts.json</h3><h3>4.1 Testing Rule 102502 (Chain-of-Custody JSON) in wazuh-logtest</h3><p>Launch /var/ossec/bin/wazuh-logtest on your <strong>Wazuh OVA</strong>:</p><pre>sudo /var/ossec/bin/wazuh-logtest</pre><p>Paste the single-line JSON custody log sample and press <strong>Enter</strong>:</p><pre>{&quot;integration&quot;:&quot;wazuh-timecapsule&quot;,&quot;action&quot;:&quot;capsule_sealed&quot;,&quot;case_id&quot;:&quot;TC-MIAN-USMAN-20261123T144537Z-R102501&quot;,&quot;host&quot;:&quot;MIAN-USMAN&quot;,&quot;trigger_rule_id&quot;:&quot;102501&quot;,&quot;capsule_path&quot;:&quot;C:\\Forensics-Vault\\TC-MIAN-USMAN-20261123T144537Z-R102501.zip&quot;,&quot;capsule_sha256&quot;:&quot;8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4&quot;,&quot;artifact_count&quot;:10,&quot;ram_dumps&quot;:1,&quot;timestamp_utc&quot;:&quot;2026-11-23T14:45:37.0000000Z&quot;}</pre><p>wazuh-logtest decodes the event via name: &#39;json&#39; in Phase 2 and outputs <strong>id: &#39;102502&#39;</strong>, <strong>level: &#39;12&#39;</strong>, and <strong>**Alert to be generated.</strong> in Phase 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RiB05B6o-uua75GjvQAKQ.png" /><figcaption>Logtest of rule 102502</figcaption></figure><h3>4.2 Understanding Why FIM Rule 102501 Uses Queue 8: Instead of wazuh-logtest</h3><p>While wazuh-logtest validates Rule 102502 cleanly in Phase 3, pasting a File Integrity Monitoring (FIM) payload into /var/ossec/bin/wazuh-logtest will never trigger Rule 102501 because of how wazuh-analysisd routes internal message queues:</p><p>Bullet wazuh-logtest routes to Queue 1: (Syslog): Every line pasted into wazuh-logtest is tagged with 1: and sent through standard text/JSON decoders, matching generic json in Phase 2 and stopping before Phase 3.</p><p>Bullet FIM events require Queue 8: (syscheck): On Windows endpoints, wazuh-syscheckd transmits file telemetry with an 8: prefix, routing it to Wazuh’s internal C decoder (DecodeSyscheck) to populate syscheck.* fields and evaluate parent rules 550, 553, and 554.</p><p><strong>Raw Wazuh 4.14.9 Queue 8: FIM Event Format:</strong></p><pre>8:[001] (MIAN-USMAN) any-&gt;syscheck:{&quot;type&quot;:&quot;event&quot;,&quot;data&quot;:{&quot;path&quot;:&quot;c:\\company_secrets\\test_canary.txt&quot;,&quot;version&quot;:2,&quot;mode&quot;:&quot;whodata&quot;,&quot;type&quot;:&quot;added&quot;,&quot;timestamp&quot;:1795445135,&quot;attributes&quot;:{&quot;type&quot;:&quot;file&quot;,&quot;size&quot;:16,&quot;mtime&quot;:1795445135,&quot;hash_md5&quot;:&quot;d41d8cd98f00b204e9800998ecf8427e&quot;,&quot;hash_sha1&quot;:&quot;da39a3ee5e6b4b0d3255bfef95601890afd80709&quot;,&quot;hash_sha256&quot;:&quot;9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08&quot;},&quot;audit&quot;:{&quot;user_name&quot;:&quot;Usman&quot;,&quot;process_id&quot;:4,&quot;process_name&quot;:&quot;System&quot;}}}<br></pre><h3>How to Verify Rule 102501 Instead:</h3><p>After touching a file in C:\Company_Secrets\, inspect the decoded DecodeSyscheck alert directly in alerts.json on the <strong>Wazuh Manager</strong>:</p><pre>grep &#39;&quot;id&quot;:&quot;102501&quot;&#39; /var/ossec/logs/alerts/alerts.json | tail -n 1 | python3 -m json.tool<br></pre><h3>Step 5: Live Attack Simulation from Kali Linux</h3><p>Now we simulate an attacker on <strong>Kali Linux</strong> who has compromised valid user credentials and connects remotely over SMB to stage files inside C:\Company_Secrets\.</p><h3>5.1 Identify the Windows 11 IP, Local Username &amp; Prepare the SMB Lab Share</h3><p>When signing into Windows 11 with a Microsoft Account, Windows maps your login to a local profile username (typically the first five characters of your email). On <strong>Windows 11 (Administrator PowerShell)</strong>, retrieve your IPv4 address (ipconfig) and local administrator username:</p><p>Powershell Command:</p><pre>ipconfig<br>$env:USERNAME<br>net localgroup Administrators</pre><p>Because Windows UAC Remote Restrictions block non-built-in local admins from connecting to C$ (NT_STATUS_ACCESS_DENIED) unless LocalAccountTokenFilterPolicy is modified, expose C:\Company_Secrets directly as a temporary SMB share for the attack simulation:</p><p>Powershell Command:</p><pre>New-SmbShare -Name &quot;Company_Secrets&quot; -Path &quot;C:\Company_Secrets&quot; -FullAccess &quot;Usman&quot;<br>Get-SmbShare -Name &quot;Company_Secrets&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cumAB8ms2b_6DcbSgRpgug.png" /><figcaption>Exposing directory as a temporary SMB</figcaption></figure><h3>5.2 Execute the Attack Commands from Kali Linux</h3><p>Open a terminal on <strong>Kali Linux</strong> and run every step of the reconnaissance and file-staging sequence against the Windows 11 host (10.15.xxx.xxx):</p><pre># 1. Verify network reachability to the Windows 11 target before attack<br>ping -c 2 &lt;Windows IP&gt;<br><br># 2. Authenticate to the Company_Secrets SMB share using compromised credentials<br>smbclient //&lt;WindowsIP&gt;/Company_Secrets -U &quot;Administrator&quot;</pre><p>Once inside the smb: \&gt; interactive prompt, stage a file inside the canary directory:</p><pre>put /etc/hostname exfil_stage.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK_IT7rea_uKiNZKbINCWQ.png" /><figcaption>Attack View on kali</figcaption></figure><h3>5.3 Verify Immediate Network Containment</h3><p>Exit smbclient (exit or Ctrl + C) on <strong>Kali Linux</strong> and re-test connectivity to Windows 11:</p><pre>ping -c 2 &lt;Windows IP&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igqrE_gce6EGm9tSN65z7A.png" /><figcaption>kali ip not reachable after the attack</figcaption></figure><p>Within 3 to 5 seconds of put /etc/hostname exfil_stage.txt, ping fails with <strong>100% packet loss</strong>, and any browser session on the Windows 11 host immediately displays <strong>ERR_NETWORK_ACCESS_DENIED</strong>—proving Phase 2 firewall containment executed automatically.</p><p>Inside the smb: \&gt; prompt, stage a brand-new file, wait 3 seconds for firewall isolation to trigger, and immediately run ls inside the <strong>same open session</strong>:</p><pre>ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtirisCk_DvqZ6ym6TN0uA.png" /><figcaption>Isolation of victim machine</figcaption></figure><h3>Step 6: Inspecting the Sealed Capsule, Dashboard Alerts &amp; Recovery</h3><h3>6.1 Verify the Sealed Forensic Archive on Windows 11</h3><p>In <strong>Administrator PowerShell</strong> on <strong>Windows 11</strong>, list C:\Forensics-Vault\ and extract the captured capsule (TC-MIAN-USMAN-20261123T144537Z-R102501.zip, ~113 MB including full process memory dumps):</p><p>Powershell Command:</p><pre>Get-ChildItem &quot;C:\Forensics-Vault\TC-*.zip&quot;<br><br>$capsule = Get-ChildItem &quot;C:\Forensics-Vault\TC-*.zip&quot; | Sort-Object LastWriteTime -Descending | Select-Object -First 1<br>Expand-Archive -Path $capsule.FullName -DestinationPath &quot;C:\Forensics-Vault\Extracted&quot; -Force<br>Get-ChildItem &quot;C:\Forensics-Vault\Extracted\*&quot; -Recurse</pre><p>Inspect the cryptographic Chain-of-Custody manifest and captured volatile network/process artifacts:</p><p>Powershell Command :</p><pre>Get-Content &quot;C:\Forensics-Vault\Extracted\*\CHAIN_OF_CUSTODY_MANIFEST.json&quot;<br>Get-Content &quot;C:\Forensics-Vault\Extracted\*\01_tcp_connections.txt&quot;<br>Get-Content &quot;C:\Forensics-Vault\Extracted\*\05_process_tree_cmdlines.txt&quot; | Select-Object -First 30</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyaV4wzq_qxmQWN0scvpZg.png" /><figcaption>Extracting the captured capsule</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY4OzFINN36SFzBLR5MHew.png" /><figcaption>CHAIN_OF_CUSTODY_MANIFEST.json</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qsqp6crzuZpkbf9zzDVFDw.png" /><figcaption>tcp_connections view</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKbLbevbJY7AGwSbaBS1RA.png" /><figcaption>process_tree_cmdlines view in powershell terminal</figcaption></figure><h3>6.2 Verify Both Alerts on the Wazuh 4.14.9 Dashboard</h3><p>On the <strong>Wazuh OVA</strong>, inspect the live JSON alert for Rule 102501:</p><p>Open the <strong>Wazuh Dashboard</strong> (https://&lt;WAZUH-OVA-IP&gt;) → <strong>Threat Hunting</strong> and filter for rule.id: 102501 and rule.id: 102502 to view both the Level-15 canary breach alert and the Level-12 cryptographic evidence attestation alert side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sO2AgYiMnbRQgoVhuUTNwg.png" /><figcaption>Rules Triggering in Wazuh Dashboard</figcaption></figure><h3>6.3 Lift Host Isolation &amp; Clean Up Lab Artifacts</h3><p>Once forensic review is complete, restore Windows 11 networking by passing the &quot;delete&quot; command into wazuh-timecapsule.cmd and remove the temporary SMB share:</p><p>Powershell Command:</p><pre>&#39;{&quot;command&quot;:&quot;delete&quot;}&#39; | &amp; &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\wazuh-timecapsule.cmd&quot;<br>Remove-SmbShare -Name &quot;Company_Secrets&quot; -Force<br><br># Confirm external connectivity is restored (returns True)<br>Test-NetConnection -ComputerName 8.8.8.8 -Port 53 -InformationLevel Quiet</pre><h3>Operational Impact</h3><p>By coupling Wazuh 4.14.9’s kernel-level whodata File Integrity Monitoring with a two-phase Active Response pipeline, Wazuh-TimeCapsule bridges the gap between automated endpoint containment and court-defensible DFIR collection. Instead of forcing SOC responders to choose between preserving volatile RAM state and stopping an active intrusion, every high-severity breach automatically generates a SHA-256-attested forensic snapshot before severing attacker communications.</p><h3>References:</h3><p><strong>Wazuh documentation, version 4.14.:</strong> <a href="https://documentation.wazuh.com/4.14/7">https://documentation.wazuh.com/4.14/</a></p><p><strong>Wazuh — Monitoring log files: </strong><a href="https://documentation.wazuh.com/4.14/user-manual/capabilities/log-data-collection/monitoring-log-files.html">https://documentation.wazuh.com/4.14/user-manual/capabilities/log-data-collection/monitoring-log-files.html</a></p><p><strong>Wazuh — localfile configuration reference:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/reference/ossec-conf/localfile.html">https://documentation.wazuh.com/4.14/user-manual/reference/ossec-conf/localfile.html</a></p><p><strong>Wazuh — Custom rules:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/rules/custom.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/rules/custom.html</a></p><p><strong>Wazuh — Rules XML syntax:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/rules.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/rules.html</a></p><p><strong>Wazuh — Decoders XML syntax:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/decoders.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/decoders.html</a></p><h3>About the Authors</h3><p><strong>Muhammad Usman</strong></p><p><strong><em>Wazuh Ambassador at Wazuh</em></strong></p><p>Student at Riphah International University, Faisalabad</p><p><strong>For the Wazuh website reference:</strong></p><p>You can explore more about the platform’s core capabilities on the official <a href="https://wazuh.com/">Wazuh Website</a>.</p><p><strong>For the Wazuh Ambassador program reference:</strong></p><p>This project was developed and published as part of my contributions to the <a href="https://wazuh.com/ambassadors-program/">Wazuh Ambassador Program.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69540f7ff275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End LLM Security Monitoring and Denial-of-Wallet Detection Pipeline with Wazuh SIEM]]></title>
            <link>https://medium.com/@usmannazir5503/end-to-end-llm-security-monitoring-and-denial-of-wallet-detection-pipeline-with-wazuh-siem-76c081db5453?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c081db5453</guid>
            <category><![CDATA[llm-security]]></category>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 18:58:03 GMT</pubDate>
            <atom:updated>2026-10-16T13:40:20.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End LLM Security Monitoring and Denial-of-Wallet Detection Pipeline with Wazuh SIEM:</h3><h3><strong>Introduction:</strong></h3><p>LLM services are often metered by request volume or token usage. An application that lacks visibility into token consumption may fail to distinguish normal use from repeated requests, unusually large prompts, or other suspicious activity. Infrastructure monitoring remains important, but application-level telemetry provides context such as the event type, model label, user identifier, token counts, and estimated cost.</p><p>This lab extends monitoring to an LLM gateway using structured JSON logs and Wazuh custom rules. The purpose is to demonstrate an end-to-end detection workflow: generate telemetry, collect it, analyze it, and verify alerts. The implementation is a proof of concept for a controlled lab; it is not a production-ready gateway or a complete DoW prevention system.</p><h3><strong>Executive Summary &amp; Production Utility:</strong></h3><p>In modern enterprise production environments, Large Language Model (LLM) applications expose organizations to critical financial, operational, and security vulnerabilities that traditional Web Application Firewalls (WAFs) fail to address – most notably Denial-of-Wallet (DoW) attacks, unbounded token consumption, and automated script flooding. This pipeline solves these pressing challenges by acting as an intelligent security monitoring layer that intercepts API requests in real time, parses granular token consumption telemetry, and correlates user behavior directly within Wazuh SIEM. By deploying custom PCRE2 detection rules and frequency-based behavioral analytics, the system instantly identifies malicious bot activity, runaway prompt execution loops, and massive resource-drain anomalies before they can incur catastrophic cloud infrastructure costs. For security operations teams, this automated telemetry pipeline transforms opaque LLM token expenditure into visible, actionable security telemetry, ensuring strict financial protection, runtime resilience, and comprehensive compliance auditing across enterprise AI deployments.</p><h3><strong>Where Can This Pipeline Be Integrated in future Productions?</strong></h3><p>To maximize visibility and threat coverage, this monitoring and detection pipeline can be integrated at several critical architectural control points across an organization’s infrastructure:</p><p><strong>Enterprise AI API Gateways &amp; Reverse Proxies:</strong></p><p>Placed directly in front of internal or customer-facing LLM microservices (such as Kong, Apigee, or custom Flask/FastAPI middleware) to inspect all incoming prompts and log usage before requests reach commercial providers (OpenAI, Azure OpenAI, ) or on-premise model endpoints (vLLM, Ollama).</p><p><strong>Security Operations Center (SOC) Workflows:</strong></p><p>Integrated directly into existing SIEM dashboards where security analysts monitor traditional infrastructure logs. By feeding LLM token analytics into Wazuh, SOC teams can correlate AI-specific abuse patterns (like rapid-fire bot flooding) alongside traditional network intrusions and endpoint telemetry under a single pane of glass.</p><p><strong>Cloud FinOps &amp; Cost Governance Systems:</strong></p><p>Positioned as an early-warning telemetry feeder for financial operations teams. Because Denial-of-Wallet attacks manifest as sudden spikes in token consumption, the high-volume rules (⁠100501⁠ and ⁠100504⁠) can trigger automated alerts to cloud cost-management systems or initiate automated rate-limiting scripts via SOAR platforms.</p><p><strong>AI-Assisted Developer Workstations &amp; CI/CD Pipelines:</strong></p><p>Deployed alongside internal development environments and internal tool usage to monitor shadow AI usage, track experimental agentic tool calls, and detect unauthorized API key reuse or token exfiltration attempts originating from compromised developer sessions.</p><h3>Section 1: End-to-End Architecture &amp; Workflow Diagram</h3><p>The pipeline operates across a hybrid environment consisting of a Windows 11 workstation hosting the LLM gateway and Wazuh endpoint agent, a Wazuh Manager for log analysis and correlation, and a Kali Linux system used for security testing and attack simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSkE3kCNR1wujJ-4dh8w5w.png" /><figcaption>Architecture Diagram</figcaption></figure><h3>Section 2: Environment Setup &amp; Python Dependency Installation</h3><p>Before deploying the gateway application, prepare your Windows 11 workstation environment to handle Python packages and secure API credentials.</p><h3>Lab Environment &amp; Specifications</h3><ul><li><strong>SIEM Platform:</strong> Wazuh OVA (v4.14.7)</li><li><strong>Endpoint / Agent:</strong> Windows 11 host running the Wazuh Agent (v4.14.7), actively monitoring the local AI gateway telemetry directory (C:\LLM_Gateway\).</li><li><strong>AI Security Gateway:</strong> Custom Python Flask reverse proxy application managing OpenAI API interactions, cost tracking, and structured JSON logging.</li><li><strong>Attacker / Testing Machine:</strong> Kali Linux virtual machine utilized for simulating high-token prompt stuffing, rapid-fire request flooding, and bot telemetry evasion.</li></ul><h3>2.1 Workspace Initialization</h3><p>Open PowerShell or Command Prompt with administrative privileges to establish your project directory:</p><pre>mkdir C:\LLM_Gateway<br>cd /d C:\LLM_Gateway</pre><h3>2.2 Installing Required Dependencies</h3><p>Install Flask for routing HTTP API requests, the OpenAI SDK for LLM interactions, and supporting networking libraries:</p><pre>pip install flask openai requests</pre><h3>2.3 Setting Up Secure OpenAI API Credentials</h3><p>To prevent hardcoding sensitive API keys into your source code, configure your OpenAI API key as a persistent Windows user environment variable:</p><pre>setx OPENAI_API_KEY &quot;sk-proj-your-actual-api-key-here&quot;</pre><p>Note: Close and reopen your terminal session after executing setx so the environment variable is loaded into memory).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tafokTbMPx2j5tK1NrJV2A.jpeg" /><figcaption>Flask Installation Completed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlQ-32YBChCCtQOHxXUvng.jpeg" /><figcaption>Openai Installed in Agent Machine.</figcaption></figure><h3>Section 3: Implementing the Flask LLM Gateway (app.py)</h3><p>The Flask application serves as an intermediary proxy between API clients and the OpenAI backend. For every processed prompt, it extracts precise usage statistics from the API response (prompt_tokens, completion_tokens, total_tokens), calculates estimated monetary costs based on model pricing tiers, and writes a structured JSON log entry to C:\LLM_Gateway\token_usage.log.</p><h3>Verify the Gateway Application:</h3><p>First, inspect the app.py and verify the request route, accepted JSON fields, and logging path. The implementation described here uses the variable names data for parsed request data, prompt_text for extracted prompt content, and log_entry for the structured telemetry record. Keep these names aligned with the actual source code when reproducing or publishing the guide.</p><p>The current telemetry schema uses llm_event_type as the event-type field. It must be spelled the same way in the gateway output, Wazuh rules, test events, and article examples.</p><p>Representative telemetry schema (illustrative values):</p><pre>{<br> &quot;timestamp&quot;: &quot;2026–10–16T03:15:57+05:00&quot;,<br> &quot;llm_event_type&quot;: &quot;llm_token_usage&quot;,<br> &quot;user_id&quot;: &quot;attacker_bot_99&quot;,<br> &quot;model&quot;: &quot;gpt-4o-mini&quot;,<br> &quot;prompt_tokens&quot;: 12608,<br> &quot;completion_tokens&quot;: 61,<br> &quot;total_tokens&quot;: 12669,<br> &quot;cost_usd&quot;: 0.001928<br>}</pre><p>The gateway sends prompts to the OpenAI API and receives model responses. Check the final app.py before describing token counts: if prompt_tokens, completion_tokens, and total_tokens are taken from the response usage metadata, identify them as provider-reported usage; if they are calculated locally, label them as estimates. Similarly, cost_usd is a gateway-calculated estimate unless verified against provider billing. Do not describe an estimated cost as an official OpenAI charge.</p><p>Create a file named app.py in your working directory and populate it with the complete source code below:</p><pre>from flask import Flask, request, jsonify<br>import os<br>import json<br>from datetime import datetime, timezone<br><br>app = Flask(__name__)<br><br>LOG_DIR = r&quot;C:\LLM_Gateway&quot;<br>LOG_FILE = os.path.join(LOG_DIR, &quot;token_usage.log&quot;)<br>os.makedirs(LOG_DIR, exist_ok=True)<br><br>@app.route(&#39;/v1/chat&#39;, methods=[&#39;POST&#39;])<br>def chat_gateway():<br>    data = request.json<br>    user_id = data.get(&quot;user_id&quot;, &quot;anonymous&quot;)<br>    model = data.get(&quot;model&quot;, &quot;gpt-4o&quot;)<br>    prompt_text = data.get(&quot;prompt&quot;, &quot;&quot;)<br>    <br>    # Calculate tokens based on prompt length (lab approximation)<br>    prompt_tokens = len(prompt_text.split()) * 2  <br>    completion_tokens = 100 <br>    total_tokens = prompt_tokens + completion_tokens<br>    <br>    # Cost calculation ($0.002 per 1,000 tokens)<br>    cost_usd = round((total_tokens / 1000) * 0.002, 5)<br>    <br>    # Structured JSON log entry<br>    log_entry = {<br>        &quot;timestamp&quot;: datetime.now(timezone.utc).isoformat(),<br>        &quot;llm_event_type&quot;: &quot;llm_token_usage&quot;,<br>        &quot;user_id&quot;: user_id,<br>        &quot;model&quot;: model,<br>        &quot;prompt_tokens&quot;: prompt_tokens,<br>        &quot;completion_tokens&quot;: completion_tokens,<br>        &quot;total_tokens&quot;: total_tokens,<br>        &quot;cost_usd&quot;: cost_usd<br>    }<br>    <br>    # Automatically append to log file watched by Wazuh Agent<br>    with open(LOG_FILE, &quot;a&quot;) as f:<br>        f.write(json.dumps(log_entry) + &quot;\n&quot;)<br>        <br>    print(f&quot;[AUTOMATED LOG] User: {user_id} | Tokens: {total_tokens}&quot;)<br>    <br>    return jsonify({<br>        &quot;status&quot;: &quot;success&quot;,<br>        &quot;user&quot;: user_id,<br>        &quot;total_tokens_consumed&quot;: total_tokens,<br>        &quot;estimated_cost_usd&quot;: cost_usd<br>    })<br><br>if __name__ == &#39;__main__&#39;:<br>    print(&quot;--- LLM Gateway Server is Live on Port 5000 ---&quot;)<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s26_UxhV_ZUK2kFSq0tXLw.jpeg" /><figcaption>app running in lab enviornment</figcaption></figure><h3>Section 4: Wazuh Agent Telemetry Configuration (ossec.conf)</h3><p>To instruct the Wazuh endpoint agent to monitor and stream the gateway log file, update the agent configuration file on the Windows 11 machine.</p><ol><li>Open C:\Program Files (x86)\ossec-agent\ossec.conf using an elevated text editor (Notepad run as Administrator).</li><li>Locate the logging blocks and append the following &lt;localfile&gt; configuration:</li></ol><pre>&lt;localfile&gt;<br>  &lt;location&gt;C:/LLM_Gateway/token_usage.log&lt;/location&gt;<br>  &lt;log_format&gt;json&lt;/log_format&gt;<br>&lt;/localfile&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulZWW9tN_s4lo2SaY1KTRg.jpeg" /><figcaption>ossec.conf file with the highlighted &lt;localfile&gt; JSON log monitoring block</figcaption></figure><p>Restart the Wazuh Agent Windows service via PowerShell to apply changes:</p><pre>Restart-Service WazuhSvc</pre><h3>Section 5: Custom Wazuh SIEM Detection Rules and decoder(local_rules.xml &amp;local_decoder.xml)</h3><p>On the Wazuh Manager, custom rules govern how incoming JSON logs are decoded, filtered, and escalated into security alerts. Edit /var/ossec/etc/rules/local_rules.xml and add the complete rule set:</p><pre><br><br> &lt;group name=&quot;local,llm,token_monitoring&quot;&gt;<br><br>  &lt;!-- =================================================== --&gt;<br>  &lt;!-- 1. STANDALONE RUNTIME TOKEN TELEMETRY RULES         --&gt;<br>  &lt;!-- =================================================== --&gt;<br><br>  &lt;rule id=&quot;100500&quot; level=&quot;3&quot;&gt;<br>    &lt;decoded_as&gt;json&lt;/decoded_as&gt;<br>    &lt;field name=&quot;llm_event_type&quot;&gt;^llm_token_usage$&lt;/field&gt;<br>    &lt;description&gt;LLM Token Activity: User $(user_id) consumed $(total_tokens) tokens on $(model) (Cost: $$(cost_usd)).&lt;/description&gt;<br>    &lt;options&gt;no_full_log&lt;/options&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Alert: High token consumption (4,000–9,999 tokens) --&gt;<br>  &lt;rule id=&quot;100501&quot; level=&quot;10&quot;&gt;<br>    &lt;if_sid&gt;100500&lt;/if_sid&gt;<br>    &lt;field name=&quot;total_tokens&quot; type=&quot;pcre2&quot;&gt;^[4-9][0-9]{3}$&lt;/field&gt;<br>    &lt;description&gt;SECURITY ALERT: High token consumption by user $(user_id). Tokens: $(total_tokens). Possible Denial of Wallet.&lt;/description&gt;<br>    &lt;group&gt;resource_abuse,attack&lt;/group&gt;<br>  &lt;/rule&gt;<br><br>  &lt;!-- Alert: Extreme token consumption (10,000+ tokens) --&gt;<br>  &lt;rule id=&quot;100504&quot; level=&quot;12&quot;&gt;<br>    &lt;if_sid&gt;100500&lt;/if_sid&gt;<br>    &lt;field name=&quot;total_tokens&quot; type=&quot;pcre2&quot;&gt;^[1-9][0-9]{4,}$&lt;/field&gt;<br>    &lt;description&gt;CRITICAL ALERT: Extreme token consumption by user $(user_id). Tokens: $(total_tokens). Possible Denial of Wallet.&lt;/description&gt;<br>    &lt;group&gt;resource_abuse,attack,critical&lt;/group&gt;<br>  &lt;/rule&gt;<br><br>  &lt;!-- Alert: Known simulation or malicious bot --&gt;<br>  &lt;rule id=&quot;100502&quot; level=&quot;8&quot;&gt;<br>    &lt;if_sid&gt;100500&lt;/if_sid&gt;<br>    &lt;field name=&quot;user_id&quot; type=&quot;pcre2&quot;&gt;^attacker_bot_99$&lt;/field&gt;<br>    &lt;description&gt;SECURITY RISK: Known simulation or malicious bot $(user_id) executed an LLM query.&lt;/description&gt;<br>    &lt;group&gt;financial_risk,anomaly&lt;/group&gt;<br>  &lt;/rule&gt; <br><br><br>  &lt;!-- Alert: Repeated LLM activity --&gt;<br>  &lt;rule id=&quot;100503&quot; level=&quot;12&quot; frequency=&quot;5&quot; timeframe=&quot;60&quot;&gt;<br>    &lt;if_matched_sid&gt;100500&lt;/if_matched_sid&gt;<br>    &lt;same_field&gt;user_id&lt;/same_field&gt;<br>    &lt;description&gt;CRITICAL THREAT: Repeated LLM requests from user $(user_id). Possible automated abuse.&lt;/description&gt;<br>    &lt;group&gt;flooding,denial_of_service,attack&lt;/group&gt;<br>  &lt;/rule&gt;<br><br>&lt;/group&gt;</pre><p>These rules matches JSON telemetry whose llm_event_type is exactly llm_token_usage. The field name is based on the actual schema observed in this lab.</p><h3>Configuring a Custom JSON Decoder in Wazuh SIEM</h3><p>To monitor security events generated by the LLM gateway, I configured Wazuh to parse structured JSON telemetry from the gateway’s log file. The Python Flask application records token usage, user identifiers, model information, token counts, and estimated API costs in C:\LLM_Gateway\token_usage.log.</p><h3>Why JSON Decoding Matters</h3><p>Each log entry contains structured fields that Wazuh can extract and use for rule-based detection. For example, the gateway generates events containing fields such as:</p><ul><li>llm_event_type: Identifies the event as LLM token-usage telemetry.</li><li>user_id: Identifies the user or simulated test actor.</li><li>model: Specifies the LLM model used.</li><li>total_tokens: Records the combined prompt and completion token count.</li><li>cost_usd: Records the estimated API cost.</li></ul><p>By extracting these fields, Wazuh can evaluate individual events against custom detection rules instead of relying only on unstructured log text.</p><h3>Custom Decoder Configuration</h3><p>I initially created a custom decoder in the Wazuh decoder configuration:</p><p>Bash Command for editing the <strong>local_decodert.xml</strong> file in wazuh manager:</p><pre> sudo nano /var/ossec/etc/decoders/local_decoder.xml</pre><p>Decoder to add in the file:</p><pre>&lt;decoder name=&quot;llm-custom-json&quot;&gt;<br>  &lt;prematch&gt;llm_event_type&lt;/prematch&gt;<br>  &lt;plugin_decoder&gt;JSON_Decoder&lt;/plugin_decoder&gt;<br>&lt;/decoder&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwFFdCuSyZusNW0WCByNqA.jpeg" /><figcaption>decoder added in the local_decoder file</figcaption></figure><p>This was intended to identify LLM-related events and use JSON decoding to extract their fields. During testing, however, Wazuh selected its built-in JSON decoder, reported as json, and successfully extracted the telemetry fields. This confirmed that a separate custom decoder was not necessary for the JSON structure used in this implementation.</p><h3>Testing the Decoder</h3><p>I validated the incoming telemetry using Wazuh’s log testing utility:</p><pre>sudo /var/ossec/bin/wazuh-logtest</pre><p>I then supplied a sample event:</p><pre>{&quot;timestamp&quot;: &quot;2026-10-16T02:42:15.561209+05:00&quot;, &quot;llm_event_type&quot;: &quot;llm_token_usage&quot;, &quot;user_id&quot;: &quot;attacker_bot_99&quot;, &quot;model&quot;: &quot;gpt-5.5&quot;, &quot;prompt_tokens&quot;: 12607, &quot;completion_tokens&quot;: 59, &quot;total_tokens&quot;: 12666, &quot;cost_usd&quot;: 0.038706}</pre><p>Screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykAobbzfX2p7bECQHK-TXA.jpeg" /><figcaption>Live log test of rule 100504</figcaption></figure><p>The attacker_bot_99 value is a controlled test marker, not reliable attacker attribution. Because the gateway accepts user_id from the request, a client may change it. Production-oriented correlation should use authenticated identity or API-key metadata and request IDs, with source information as an additional signal rather than sole proof of identity.</p><p>Restart the Wazuh Manager to compile and load the rules:</p><pre>sudo systemctl restart wazuh-manager</pre><h3>Section 6: Verification &amp; Attack Simulation Plan</h3><p>Validate rule logic and alerting pipelines by executing test requests from a <strong>Kali Linux</strong> workstation targeting the Windows 11 gateway IP (&lt;WINDOWS_11_IP&gt;).</p><p><strong>Send Test Requests from Kali Linux:</strong></p><p>The following commands assume the gateway listens on port 5000 and accepts POST /v1/chat with a JSON body containing user_id, model, and messages. Confirm this against your final app.py. Replace the example IP address with the actual Windows gateway IP.</p><pre>export GATEWAY_IP=&quot;192.168.1.50&quot; # Replace with your Windows gateway IP<br>export GATEWAY=&quot;http://${GATEWAY_IP}:5000&quot;</pre><p><strong>Connectivity check:</strong></p><pre>curl -i - max-time 5 &quot;${GATEWAY}/&quot;</pre><p>A 404 response may mean the application has no root route; it does not automatically mean the host is unreachable. A timeout or refused connection should prompt checks of the IP address, Flask listener, Windows firewall, and network path.</p><p><strong>Normal request:</strong></p><pre>curl -i - max-time 60 -X POST &quot;${GATEWAY}/v1/chat&quot; \<br> -H &quot;Content-Type: application/json&quot; \<br> -d &#39;{<br> &quot;user_id&quot;: &quot;kali_normal_test&quot;,<br> &quot;model&quot;: &quot;gpt-4o-mini&quot;,<br> &quot;messages&quot;: [<br> {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Reply with a short greeting.&quot;}<br> ]<br> }&#39;</pre><p>Expected: the gateway accepts the request and appends a baseline telemetry event. Rule 100500 should be eligible to match. Record the actual HTTP response and confirm the corresponding log event.</p><p><strong>Known identifier test:</strong></p><pre>curl -i - max-time 60 -X POST &quot;${GATEWAY}/v1/chat&quot; \<br> -H &quot;Content-Type: application/json&quot; \<br> -d &#39;{<br> &quot;user_id&quot;: &quot;attacker_bot_99&quot;,<br> &quot;model&quot;: &quot;gpt-4o-mini&quot;,<br> &quot;messages&quot;: [<br> {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Controlled identifier detection test.&quot;}<br> ]<br> }&#39;</pre><p>Expected: the resulting event should include user_id attacker_bot_99 and may match rule 100502. Another rule may also match if its conditions are satisfied; report the actual output rather than assuming only one rule fires.</p><p><strong>8.4 Repeated activity test</strong></p><pre>for i in 1 2 3 4 5; do<br> curl -sS - max-time 60 -X POST &quot;${GATEWAY}/v1/chat&quot; \<br> -H &quot;Content-Type: application/json&quot; \<br> -d &quot;{<br> \&quot;user_id\&quot;: \&quot;repeat_test_user\&quot;,<br> \&quot;model\&quot;: \&quot;gpt-4o-mini\&quot;,<br> \&quot;messages\&quot;: [<br> {\&quot;role\&quot;: \&quot;user\&quot;, \&quot;content\&quot;: \&quot;Controlled repeated activity test ${i}\&quot;}<br> ]<br> }&quot;<br> echo<br>done</pre><p>Expected: five events from the same user_id within the configured time window exercise rule 100503. Verify whether the rule actually fires in alerts.json. If it does not, inspect frequency/timeframe, same-field correlation, parent rule, event timing, and rule hierarchy. Run this only against your own lab.</p><p>Because the current gateway simulates or estimates usage, these examples test telemetry and detection behavior. If the gateway has since been changed to call a paid provider, requests may incur charges; keep tests controlled and avoid flood traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbSMZkz8tSO4BQpxLaMA2g.jpeg" /><figcaption>Custom Rules triggered after doing test requests from kali machine.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qky-o0QXyHBCiUJfyhc2zw.jpeg" /><figcaption>Full Log view of rule_id 100504 showing cost and number of tokens consumed</figcaption></figure><h3>Section 7: Persistent Gateway Automation via Windows Startup Folder</h3><p>To ensure the Flask LLM gateway runs automatically upon system login without manual terminal intervention, implement the Windows Startup folder method.</p><h3>Step-by-Step Implementation</h3><ol><li><strong>Create a Batch Script:</strong> Navigate to C:\LLM_Gateway and create a batch file named run_gateway.bat using Notepad:</li></ol><pre>@echo off<br>cd /d C:\LLM_Gateway<br>python app.py<br>pause</pre><ol><li><strong>Access the Windows Startup Directory:</strong> Press Win + R on your keyboard, type <strong>shell:startup</strong>, and hit Enter. This opens the current user&#39;s startup folder.</li><li><strong>Create a Shortcut:</strong> Right-click inside the open Startup folder -&gt; <strong>New</strong> -&gt; <strong>Shortcut</strong>, browse to select C:\LLM_Gateway\run_gateway.bat, name the shortcut LLM_Gateway, and click <strong>Finish</strong>.</li></ol><p>Upon the next system reboot and user login, the batch script executes automatically, launching the Flask gateway in a dedicated command window and streaming live telemetry to Wazuh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMrFUiej2OsS0JqjtJA21w.jpeg" /><figcaption>LLM_Gateway shortcut, alongside the active command prompt running app.py</figcaption></figure><h3>Section 8: Changing OpenAI Models</h3><p>To switch between OpenAI models (e.g., changing from gpt-4o-mini to gpt-4o, gpt-4.5, or o3-mini), you can pass the model name dynamically in your JSON request payload, or set a different default model inside app.py:</p><pre>model = data.get(&quot;model&quot;, &quot;gpt-4o&quot;) # Change default model here</pre><p><strong>Important Note on Cost Calculation:</strong> If you switch models, update the cost multipliers in app.py to match OpenAI&#39;s current pricing for input and output tokens for that specific model tier:</p><pre># Example adjustment for a higher-tier model<br>cost_usd = round((prompt_tokens * 0.00000250) + (completion_tokens * 0.00001000), 6)</pre><h3>Section 9: Common Pitfalls &amp; Troubleshooting When Switching Models of OpenAi</h3><p>Although the foundational architecture was initially built and verified using OpenAI gpt-4o-mini.</p><p><strong>SDK Attribute Mismatches (</strong><strong>AttributeError):</strong></p><ul><li><strong><em>The Mistake:</em></strong> Assuming every provider uses OpenAI’s exact attribute names (prompt_tokens, completion_tokens).</li></ul><p><strong>Incorrect Cost Multipliers:</strong></p><ul><li><strong><em>The Mistake:</em> </strong>Leaving the cheap gpt-4o-mini pricing calculation formula intact when switching to a heavy flagship model like gpt-4o or latest models</li><li><strong><em>The Fix:</em></strong> Always recalculate the financial cost multiplier in app.py based on the active model&#39;s exact per-token pricing to prevent inaccurate cost_usd logging in Wazuh.</li></ul><p><strong>Missing Environment Variables:</strong></p><ul><li><strong><em>The Mistake:</em> </strong>Forgetting that switching SDKs requires a corresponding provider API key set via setx.</li><li><strong><em>The Fix:</em></strong> Ensure the correct environment variable is configured and restart your terminal session or Windows service so the new key is detected in memory.</li></ul><h3><strong>Troubleshooting Common Issues:</strong></h3><p><strong>No event in token_usage.log</strong></p><p>Confirm the request route and JSON schema; inspect the Flask console/logs; verify the gateway’s configured file path and write permissions.</p><p><strong>Agent does not collect the file</strong></p><p>Confirm the exact localfile path, JSON log format, XML validity, agent status, and service restart. Check the agent logs for configuration errors.</p><p><strong>wazuh-logtest matches generic rule 1002 instead of a custom rule</strong></p><p>Check that the custom rules are loaded, that the JSON decoder is selected, that llm_event_type matches the event exactly, and that rule IDs/conditions are valid.</p><p><strong>Rule 100504 does not fire</strong></p><p>Check total_tokens threshold, field extraction, rule order, parent/child conditions, and the exact rule definition. Test with a synthetic event above the threshold.</p><p><strong>Rule 100503 does not fire</strong></p><p>Send the required number of events within the configured timeframe and confirm the rule’s frequency and same-user correlation fields. Validate with live alert records.</p><p><strong>Alert exists in alerts.json but not the dashboard</strong></p><p>Troubleshoot indexer and dashboard ingestion separately. Check service health and indexing configuration; do not infer dashboard success from alerts.json alone.</p><h3><strong>Section 10: Results and Discussion</strong></h3><p>The recorded lab evidence shows that the Wazuh JSON decoder extracted the fields from a structured telemetry event and that the extreme-token test matched rule 100504. A live manager alert was also observed for an event containing 12,669 total tokens. These results demonstrate the end-to-end detection path for that tested event.</p><p>For a reproducible report, present evidence in separate categories:</p><p>(1) rule parsing/matching with wazuh-logtest, (2) live collection and alert generation, and (3) dashboard indexing if independently verified. State the actual result for each test rule. Do not say that every rule passed unless you have captured evidence for each one.</p><p>Token thresholds are indicators, not proof of malicious intent. Legitimate long-context tasks can use many tokens, and simulated token counts do not validate actual provider billing. Rule thresholds should be tuned against normal workloads to balance false positives and missed detections.</p><h3><strong>12. Limitations and Security Considerations</strong></h3><p><strong>Simulated or estimated usage</strong></p><p>The current lab estimates or simulates token counts and cost. For provider-accurate telemetry, integrate the actual provider API and use its response usage metadata where available; distinguish calculated costs from official billing.</p><p><strong>Client-controlled user_id</strong></p><p>A client may change user_id. Prefer authenticated identity or API-key metadata, request IDs, and additional context. Source IP is useful but may be obscured by proxies or NAT.</p><p><strong>Predefined bot marker</strong></p><p>attacker_bot_99 is a controlled test value, not generalized bot detection.</p><p><strong>Detection versus prevention</strong></p><p>The current pipeline alerts. It does not automatically block requests, revoke keys, or enforce quotas/rate limits. These require separate gateway controls or a carefully designed and tested active-response integration.</p><p><strong>Laboratory server</strong></p><p>A Flask development server and hard-coded test marker are suitable for a controlled lab, not production. Production use requires a production-grade server, TLS, authentication, secure secret management, input validation, access control, and protected logs.</p><h3><strong>Section 11: Future Improvements</strong></h3><p>Integrate a real model provider and collect response usage metadata.</p><p>Add authenticated identity and safe API-key metadata correlation without logging secret key values.</p><p>Implement API-key lifecycle audit events for creation, rotation, expiry, revocation, and suspected exposure.</p><p>Add gateway-side request quotas, token budgets, and rate limiting.</p><p>Create dashboard visualizations for token usage, estimated cost, repeated requests, and alert severity.</p><p>Tune rules against representative normal workloads and test each rule with a documented test matrix.</p><p>Evaluate automated response only with clear safeguards, testing, and rollback procedures.</p><h3><strong>Section 12: Conclusion</strong></h3><p>This guide documented a practical LLM telemetry monitoring pipeline using a Flask gateway, a Windows Wazuh agent, and Wazuh SIEM. Structured JSON records are collected and evaluated with custom rules for baseline telemetry, high and extreme token consumption, a predefined test identifier, and repeated activity. The recorded extreme-token event matched rule 100504 and generated a live alert. The implementation remains a lab proof of concept: token and cost values are estimated/simulated, user_id is client-controlled, and alerts do not themselves prevent abuse. These boundaries make the reported result accurate and provide a clear path for future work, including provider-backed usage telemetry, stronger identity correlation, API-key lifecycle monitoring, and carefully tested enforcement controls.</p><h3><strong>References:</strong></h3><p><strong>Wazuh documentation, version 4.14.:</strong> <a href="https://documentation.wazuh.com/4.14/7">https://documentation.wazuh.com/4.14/</a></p><p><strong>Wazuh — Monitoring log files: </strong><a href="https://documentation.wazuh.com/4.14/user-manual/capabilities/log-data-collection/monitoring-log-files.html">https://documentation.wazuh.com/4.14/user-manual/capabilities/log-data-collection/monitoring-log-files.html</a></p><p><strong>Wazuh — localfile configuration reference:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/reference/ossec-conf/localfile.html">https://documentation.wazuh.com/4.14/user-manual/reference/ossec-conf/localfile.html</a></p><p><strong>Wazuh — Custom rules:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/rules/custom.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/rules/custom.html</a></p><p><strong>Wazuh — Rules XML syntax:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/rules.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/rules.html</a></p><p><strong>Wazuh — Decoders XML syntax:</strong> <a href="https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/decoders.html">https://documentation.wazuh.com/4.14/user-manual/ruleset/ruleset-xml-syntax/decoders.html</a></p><h3>About the Authors</h3><p><strong>Muhammad Usman</strong></p><p><strong><em>Wazuh Ambassador at Wazuh</em></strong></p><p>Student at Riphah International University, Faisalabad</p><p><strong>Muhammad Shahbaz</strong></p><p>Student at Riphah International University, Faisalabad</p><p><strong>For the Wazuh website reference:</strong></p><p>You can explore more about the platform’s core capabilities on the official <a href="https://wazuh.com/">Wazuh Website</a>.</p><p><strong>For the Wazuh Ambassador program reference:</strong></p><p>This project was developed and published as part of my contributions to the <a href="https://wazuh.com/ambassadors-program/">Wazuh Ambassador Program.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c081db5453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Wazuh-AFD (Anti-Forensics Detection & Automated Active Response Framework)]]></title>
            <link>https://medium.com/@usmannazir5503/building-wazuh-afd-anti-forensics-detection-automated-active-response-framework-2b6c59a0bfa9?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b6c59a0bfa9</guid>
            <category><![CDATA[anti-forensics]]></category>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[wazuh]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 16:35:35 GMT</pubDate>
            <atom:updated>2026-09-28T18:08:52.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>Executive Summary &amp; Problem Statement</h3><h3><strong>Executive Summary:</strong></h3><p>This engineering manual provides a comprehensive, step-by-step blueprint for building <strong>Wazuh-AFD</strong> (Anti-Forensics Detection): an enterprise-grade detection and automated active response framework. Designed for cybersecurity students, junior analysts, and security engineers, this guide bridges the gap between passive log collection and active defense by detailing every configuration file, telemetry source, custom rule, and automated mitigation script from zero to end.</p><h3>The Problem Statement:</h3><p>In modern cybersecurity operations, endpoint detection and response (EDR) solutions and Security Information and Event Management (SIEM) systems excel at capturing initial access, lateral movement, and persistence mechanisms. However, a critical blind spot persists during post-compromise stages: <strong>threat actor anti-forensics and evasion tactics</strong>.</p><p>Sophisticated attackers routinely execute clean-up operations before disconnecting from a compromised host. These tactics include:</p><ul><li><strong>Clearing Windows Security Event Logs</strong> (e.g., via wevtutil cl Security) to destroy authentication traces, privilege escalation artifacts, and credential access records (<strong>MITRE ATT&amp;CK T1070.001</strong>).</li><li><strong>Wiping staging artifacts, custom scripts, and payloads</strong> from the file system using native shell commands (Remove-Item or del) (<strong>MITRE ATT&amp;CK T1070.004</strong>).</li><li><strong>Exploiting human response latency:</strong> In traditional architectures, a SIEM acts purely as a passive observer, generating alerts that require manual triage. By the time a human analyst reviews the logs, the adversary has already wiped the evidence and blinded the defenders.</li></ul><h3>The Objective: Wazuh-AFD</h3><p>To solve this challenge, <strong>Wazuh-AFD (Anti-Forensics Detection)</strong> is engineered as a closed-loop defense framework. It combines deep endpoint telemetry streaming (Sysmon and PowerShell logs), advanced multi-event SIEM correlation rules, and automated active response scripts to detect, correlate, and contain anti-forensics campaigns instantaneously without human latency.</p><h3>Section 1: End-to-End Architecture &amp; Lab Topology</h3><p>To capture evasive attacker behavior, a robust telemetry pipeline is deployed across both the endpoint and the SIEM server.</p><h3>1. Architectural Components</h3><ul><li><strong>Victim Endpoint (Windows 11):</strong></li><li><strong>Wazuh Agent:</strong> Transmits OS telemetry and logs securely to the central server.</li><li><strong>Microsoft Sysmon (System Monitor):</strong> Captures high-fidelity process creation, command-line arguments, and image loads (Sysmon Event ID 1).</li><li><strong>PowerShell Logging:</strong> Captures script block execution and command activity.</li><li><strong>File Integrity Monitoring (FIM):</strong> Real-time monitoring of sensitive staging directories (C:\wazuh-scripts).</li><li><strong>SIEM Server (Wazuh Linux Server):</strong></li><li>Central analysis engine responsible for parsing logs, evaluating custom detection rules, executing multi-event correlation logic, and triggering active response actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr4Arq16VZR9KUrTyeuklg.jpeg" /><figcaption>Architecture Diagram</figcaption></figure><h3>2. MITRE ATT&amp;CK Framework Mapping</h3><ul><li><strong>T1070.001:</strong> Indicator Removal on Host: Clear Windows Event Logs.</li><li><strong>T1070.004:</strong> Indicator Removal on Host: File Deletion.</li></ul><h3>Section 2: Phase 1 — Windows 11 Wazuh Agent Telemetry &amp; Log Collection Configuration</h3><p>Before writing detection rules, the Windows 11 endpoint must be configured to stream Sysmon, PowerShell, and File Integrity Monitoring (FIM) telemetry to the server.</p><h3>1. Locating the Agent Configuration File</h3><p>On your Windows 11 endpoint, the agent configuration is stored at: C:\Program Files (x86)\ossec-agent\ossec.conf</p><h3>2. Adding Event Channel and FIM Block Definitions</h3><p>To track real-time activity and modifications within your designated threat staging workspace, you define your custom directory paths directly inside the ⁠&lt;syscheck&gt;⁠ section of your Windows agent configuration file (⁠C:\Program Files (x86)\ossec-agent\ossec.conf⁠):</p><pre> <br>   &lt;!-- File integrity monitoring --&gt;<br>  &lt;directories check_all=&quot;yes&quot; realtime=&quot;yes&quot;&gt;your directory path here&lt;/directories&gt;<br> <br><br> </pre><p>Open ossec.conf in an editor running as Administrator and ensure your configuration includes the following three critical telemetry blocks:</p><pre><br>&lt;!-- ========================================== --&gt;<br>  &lt;!-- 1. Security Event Channel Log Collection    --&gt;<br>  &lt;!-- ========================================== --&gt;<br><br>  &lt;localfile&gt;<br>    &lt;location&gt;Security&lt;/location&gt;<br>    &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>  &lt;/localfile&gt;<br><br>&lt;!-- ========================================== --&gt;<br>  &lt;!-- 2. Sysmon Event Channel Log Collection     --&gt;<br>  &lt;!-- ========================================== --&gt;<br>  &lt;localfile&gt;<br>    &lt;location&gt;Microsoft-Windows-Sysmon/Operational&lt;/location&gt;<br>    &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>  &lt;/localfile&gt;<br><br><br>  &lt;!-- ========================================== --&gt;<br>  &lt;!-- 3. PowerShell Operational Log Collection   --&gt;<br>  &lt;!-- ========================================== --&gt;<br>  &lt;localfile&gt;<br>    &lt;location&gt;Microsoft-Windows-PowerShell/Operational&lt;/location&gt;<br>    &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>  &lt;/localfile&gt;<br>  &lt;!-- ========================================== --&gt;<br>  &lt;!-- 4. System Log Collection   --&gt;<br>  &lt;!-- ========================================== --&gt;<br>  &lt;localfile&gt;<br>    &lt;location&gt;System&lt;/location&gt;<br>    &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>  &lt;/localfile&gt;</pre><h3>3. Restarting the Wazuh Agent Service</h3><p>Whenever changes are made to the agent’s ossec.conf, restart the Windows service to apply them:</p><ol><li>Open <strong>PowerShell as Administrator</strong>.</li><li>Run the restart command:</li></ol><pre>Restart-Service -Name WazuhSvc</pre><h3>Section 3: Phase 2 — Custom Detection Engineering (local_rules.xml)</h3><p>Detection engineering requires authoring custom XML rules on the Wazuh Server to catch specific attacker signatures and evasion patterns.</p><h3>1. Deploying Custom Rules on the Wazuh Server</h3><ol><li>Log into your <strong>Wazuh Server terminal</strong>.</li><li>Open the custom rules file using nano:</li></ol><pre>sudo nano /var/ossec/etc/rules/local_rules.xml</pre><pre>&lt;group name=&quot;windows, anti_forensics, wazuh_afd,&quot;&gt;<br>  &lt;!-- ======================================================== --&gt;<br>  &lt;!-- Wazuh-AFD: Custom Anti-Forensics Rules                    --&gt;<br>  &lt;!-- ======================================================== --&gt;<br>&lt;rule id=&quot;100001&quot; level=&quot;12&quot;&gt;<br>    &lt;if_group&gt;windows&lt;/if_group&gt;<br>    &lt;field name=&quot;win.system.eventID&quot;&gt;1102&lt;/field&gt;<br>    &lt;description&gt;Wazuh-AFD: Windows Security Audit Log Cleared (Anti-Forensics)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1070.001&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br>  &lt;rule id=&quot;100002&quot; level=&quot;10&quot;&gt;<br>    &lt;if_group&gt;windows&lt;/if_group&gt;<br>    &lt;field name=&quot;win.system.eventID&quot;&gt;1&lt;/field&gt;<br>    &lt;match&gt;Remove-Item&lt;/match&gt;<br>    &lt;description&gt;Wazuh-AFD: Command-Line File Deletion Detected (Anti-Forensics T1070.004)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1070.004&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br>&lt;rule id=&quot;100003&quot; level=&quot;14&quot; frequency=&quot;2&quot; timeframe=&quot;60&quot;&gt;<br>    &lt;if_matched_sid&gt;100001&lt;/if_matched_sid&gt;<br>    &lt;if_matched_sid&gt;100002&lt;/if_matched_sid&gt;<br>    &lt;description&gt;Wazuh-AFD: Critical Multi-Stage Anti-Forensics Campaign Detected (Log Clearing + Artifact Deletion)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1070.001&lt;/id&gt;<br>      &lt;id&gt;T1070.004&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br>&lt;/group&gt;</pre><h3>2. Validating and Restarting the Wazuh Manager</h3><p>Before applying changes live, test the configuration syntax to prevent daemon failures:</p><pre>sudo /var/ossec/bin/wazuh-analysisd -t<br>sudo systemctl restart wazuh-manager</pre><h3>Section 4: Phase 3 — Automated Active Response Integration</h3><p>To transform Wazuh from a passive alerting system into an active defense platform, configure an automated response that triggers when Rule 100003 fires.</p><h3>1. Server-Side Active Response Configuration</h3><ol><li>Open the primary server configuration file:</li></ol><pre>sudo nano /var/ossec/etc/ossec.conf</pre><p>Scroll to the &lt;active-response&gt; section and add the command block and rule mapping:</p><pre>&lt;command&gt;<br>  &lt;name&gt;afd-incident-response&lt;/name&gt;<br>  &lt;executable&gt;afd-response.bat&lt;/executable&gt;<br>  &lt;expect&gt;&lt;/expect&gt;<br>  &lt;timeout_allowed&gt;no&lt;/timeout_allowed&gt;<br>&lt;/command&gt;<br><br>&lt;active-response&gt;<br>  &lt;command&gt;afd-incident-response&lt;/command&gt;<br>  &lt;location&gt;local&lt;/location&gt;<br>  &lt;rules_id&gt;100003&lt;/rules_id&gt;<br>&lt;/active-response&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzdAfVsf0mNs8eS61Vix-Q.jpeg" /><figcaption>Active response section added in ossec.conf in wazuh manager</figcaption></figure><p>Save, exit, and restart the Wazuh manager:</p><pre>sudo systemctl restart wazuh-manager</pre><h3>2. Deploying the Endpoint Response Script (afd-response.bat)</h3><p>On your Windows 11 endpoint, create the local script that executes automatically upon a critical alert.</p><ol><li>Open <strong>PowerShell as Administrator</strong> on <strong>Windows 11</strong>.</li><li>Run the following deployment block:</li></ol><pre>$ScriptPath = &quot;C:\Program Files (x86)\ossec-agent\active-response\bin\afd-response.bat&quot;<br>$ScriptContent = @&quot;<br>@echo off<br>echo [%DATE% %TIME%] WAZUH-AFD: Critical Anti-Forensics Campaign Detected. Initiating Local Safeguards. &gt;&gt; C:\wazuh-scripts\containment_log.txt<br>echo Emergency containment triggered by Rule 100003. &gt;&gt; C:\&lt;your directory path here&gt;\containment_log.txt<br>&quot;@<br>Set-Content -Path $ScriptPath -Value $ScriptContent</pre><p>Restart the Wazuh agent service:</p><pre>Restart-Service -Name WazuhSvc</pre><h3>3. Operational Benefits of Active Response</h3><ul><li><strong>Eliminates Human Latency:</strong> Automatically executes endpoint mitigation near real-time a multi-stage attack is correlated.</li><li><strong>Maintains Audit Trails:</strong> Appends secure, timestamped logs to C:\monitored directory added in FIM\containment_log.txt for incident response reporting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJDnc0bMKsKywSu5QcOyVg.jpeg" /><figcaption>active response text file created in the FIM directory getting monitored</figcaption></figure><ul><li><strong>Closes the Loop:</strong> Converts the SIEM into a self-defending architecture capable of automated containment.</li></ul><h3>Section 5: Phase 4 — Live Attack Simulation &amp; Verification Testing</h3><p>Test the complete pipeline by simulating an attacker clearing audit tracks and deleting staging artifacts.</p><h3>Step 1: Execute the Attack Chain on Windows 11</h3><p>Open <strong>PowerShell (Administrator)</strong> and run the commands back-to-back:</p><pre># Stage 1: Clear the Windows Security Event Log<br>wevtutil cl Security<br><br># Stage 2: Delete staging artifact via fresh process execution<br>powershell.exe -Command &quot;Remove-Item &#39;C:\wazuh-scripts\test-artifact.txt&#39; -Force -ErrorAction SilentlyContinue&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UNmBMHo0xFav3KzesFPiw.jpeg" /><figcaption>test from agent machine</figcaption></figure><h3>Step 2: Verify Server Alerts</h3><ol><li>Switch to the <strong>Wazuh Server terminal</strong>.</li><li>Check for individual rule firing (100002) and correlation rule firing (100003):</li></ol><pre>sudo grep &quot;100002&quot; /var/ossec/logs/alerts/alerts.log<br>sudo grep &quot;100003&quot; /var/ossec/logs/alerts/alerts.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOGSS2TJgjWusRCZwOinxw.jpeg" /><figcaption>rules triggered in wazuh manager</figcaption></figure><h3>Step 3: Verify Active Response Containment</h3><ol><li>Return to the <strong>Windows 11 endpoint</strong>.</li><li>Inspect the generated containment log by running this command in powershell:</li></ol><pre>Get-Content &quot;C:\wazuh-scripts\containment_log.txt&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54VB7AdLxOBK60k7jemsdw.jpeg" /><figcaption>containtment logs in the file created by active response</figcaption></figure><h3>Section 6: Phase 5 — Enterprise Scaling &amp; Production Best Practices</h3><p>Deploying this architecture in a live enterprise environment requires adapting lab practices for production scale:</p><ol><li><strong>Broadening Coverage with Wildcards:</strong> Instead of static paths like C:\wazuh-scripts, enterprise FIM configurations leverage wildcards (*) and environment variables (%UserProfile%, %SystemRoot%) to monitor high-risk staging directories across every user profile simultaneously (e.g., C:\Users\*\AppData\Local\Temp\*).</li><li><strong>Out-of-Band Log Streaming:</strong> While attackers can execute local log wipes (wevtutil cl), enterprise architecture mitigates this by streaming telemetry in real-time to an immutable, centralized SIEM or WORM (Write Once, Read Many) storage tier where threat actors hold no administrative privileges.</li><li><strong>Centralized Policy Orchestration:</strong> Rather than configuring endpoints manually, enterprise rules and FIM policies are deployed at scale using Wazuh Agent Groups, Active Directory Group Policy Objects (GPO), or automation tools like Ansible and Microsoft Intune.</li></ol><h3>Conclusion</h3><p>You have successfully engineered, configured, and tested <strong>Wazuh-AFD</strong> from zero to end. By establishing deep endpoint telemetry, writing custom detection rules, configuring multi-event SIEM correlation, and deploying automated active response scripts, you have built a professional, portfolio-grade detection project ready for demonstration on technical blogs or resume highlights!</p><h3>About the Author</h3><p><strong>Muhammad Usman</strong></p><p><strong><em>Wazuh Ambassador at Wazuh</em></strong></p><p>Student at Riphah International University, Faisalabad</p><p><strong>For the Wazuh website reference:</strong></p><p>You can explore more about the platform’s core capabilities on the official <a href="https://wazuh.com/">Wazuh Website</a>.</p><p><strong>For the Wazuh Ambassador program reference:</strong></p><p>This project was developed and published as part of my contributions to the <a href="https://wazuh.com/ambassadors-program/">Wazuh Ambassador Program.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b6c59a0bfa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Centralized SOC Lab: Integrating Wazuh SIEM Telemetry with Graylog via Filebeat & Docker]]></title>
            <link>https://medium.com/@usmannazir5503/building-a-centralized-soc-lab-integrating-wazuh-siem-telemetry-with-graylog-via-filebeat-docker-af6dfb1f89f0?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6dfb1f89f0</guid>
            <category><![CDATA[cyber-security-analyst]]></category>
            <category><![CDATA[graylog]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[wazuh]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 19:33:54 GMT</pubDate>
            <atom:updated>2026-09-06T19:33:54.661Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step operational guide to forwarding endpoint security events from a Wazuh Manager VM to Graylog running on Windows using WSL2, Docker Compose, and Filebeat.</p><h3>1. Executive Summary &amp; Core Use Cases</h3><p>In modern Security Operations Center (SOC) environments, combining host-level security detection with centralized log aggregation is standard practice. <strong>Wazuh</strong> functions as an Endpoint Detection and Response (EDR) and Security Information and Event Management (SIEM) solution — handling file integrity monitoring, vulnerability scans, and endpoint threat detection. <strong>Graylog</strong>, powered by OpenSearch, acts as a centralized log management platform built for lightning-fast queries, custom data extraction, and stream-based filtering.</p><p>By forwarding Wazuh telemetry directly into Graylog using Filebeat, security analysts achieve several core operational capabilities:</p><ul><li><strong>Centralized Security Management:</strong> Aggregate endpoint alerts from Linux and Windows hosts alongside network device logs in a single operational view.</li><li><strong>Rapid Incident Response &amp; Forensics:</strong> Leverage Graylog’s high-performance search engine to query security logs across historical timeframes during threat-hunting exercises.</li><li><strong>Custom Stream Processing &amp; Alerting:</strong> Route specific threat categories (e.g., <em>Failed Authentication</em>, <em>Privilege Escalation</em>) into targeted Graylog streams to fire automated webhooks to external ticketing or notification tools.</li></ul><h3>2. Nework Topology &amp; Lab Architecture</h3><p>The lab is configured inside VirtualBox using a private <strong>Host-Only Network</strong> (192.x.x.x/24) to isolate security traffic while allowing inter-system communication.</p><ul><li><strong>Windows Host (</strong><strong>192.xxx.xx.x)</strong>: Runs Docker Desktop via WSL2 (orchestrating Graylog, OpenSearch, and MongoDB) and acts as a monitored Wazuh Agent endpoint.</li><li><strong>Wazuh Manager VM (</strong><strong>192.x.x.x)</strong>: Executes the core detection engine, ruleset matching, and Filebeat log shipping.</li><li><strong>Kali Linux VM (</strong><strong>192.x.x.x)</strong>: Serves as an attack platform and monitored Linux endpoint running a Wazuh Agent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6P2c32GzsyHCuyxARz_XgA.png" /><figcaption>Diagram Of Workflow</figcaption></figure><h3>3. WSL2 &amp; Docker Compose Setup on Windows</h3><p>Graylog requires a backend search engine (OpenSearch) and a metadata database (MongoDB). Deploying this stack on Windows is handled using <strong>WSL2</strong> and <strong>Docker Desktop</strong>.</p><h3>Step A: Enable WSL2</h3><p>Open PowerShell as Administrator:</p><pre>wsl --install<br>wsl --set-default-version 2</pre><h3>Step B: Deploy the Graylog Container Stack</h3><p>Install Docker Desktop on Windows, ensuring <strong>Use the WSL 2 based engine</strong> is checked in Settings -&gt; General.</p><p>Create a folder named graylog-soc and save the following docker-compose.yml:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  mongodb:<br>    image: mongo:5.0<br>    container_name: graylog_mongodb<br>    volumes:<br>      - mongo_data:/data/db<br>    restart: always<br><br>  opensearch:<br>    image: opensearchproject/opensearch:2.11.0<br>    container_name: graylog_opensearch<br>    environment:<br>      - OPENSEARCH_JAVA_OPTS=-Xms1g -Xmx1g<br>      - bootstrap.memory_lock=true<br>      - discovery.type=single-node<br>      - action.auto_create_index=false<br>      - DISABLE_INSTALL_DEMO_CONFIG=true<br>      - DISABLE_SECURITY_PLUGIN=true<br>    ulimits:<br>      memlock:<br>        soft: -1<br>        hard: -1<br>    volumes:<br>      - opensearch_data:/usr/share/opensearch/data<br>    restart: always<br><br>  graylog:<br>    image: graylog/graylog:5.2<br>    container_name: graylog_server<br>    depends_on:<br>      - mongodb<br>      - opensearch<br>    ports:<br>      - &quot;9000:9000&quot;     # Web Interface<br>      - &quot;5044:5044&quot;     # Beats Input Receiver<br>    environment:<br>      GRAYLOG_PASSWORD_SECRET: &quot;8a12f38d4e56719abc02d4eef1102931a&quot;<br>      GRAYLOG_ROOT_PASSWORD_SHA2: &quot;8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918&quot; # SHA-256 for &#39;admin&#39;<br>      GRAYLOG_HTTP_BIND_ADDRESS: &quot;0.0.0.0:9000&quot;<br>      GRAYLOG_ELASTICSEARCH_HOSTS: &quot;http://opensearch:9200&quot;<br>    volumes:<br>      - graylog_data:/usr/share/graylog/data<br>    restart: always<br><br>volumes:<br>  mongo_data:<br>  opensearch_data:<br>  graylog_data:</pre><p>Launch the stack:</p><pre>docker compose up -d</pre><p>Verify that all three containers are active:</p><pre>docker ps</pre><h3>4. Configuring Graylog Beats Input &amp; Windows Firewall</h3><p>For Graylog to receive incoming log batches from Filebeat, an active Beats input port must be opened and allowed through the host firewall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnpFaDqOoYtJLbV_RXVXZA.jpeg" /><figcaption>graylog active in docker</figcaption></figure><h3>Step A: Configure Beats Input in Graylog UI</h3><ol><li>Navigate to http://localhost:9000 in your browser and log in (admin / admin).</li><li>Go to <strong>System</strong> -&gt; <strong>Inputs</strong>.</li><li>Select <strong>Beats</strong> from the dropdown menu and click <strong>Launch new input</strong>.</li><li>Set <strong>Title</strong> to Wazuh-Alerts Beats and <strong>Port</strong> to 5044.</li><li>Click <strong>Save</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saxOkTx2tcUN73p_OdbyrQ.jpeg" /><figcaption>wazuh manager node configured in graylog and running status shown</figcaption></figure><h3>Step B: Configure Windows Defender Firewall</h3><p>Open <strong>PowerShell as Administrator</strong> on your Windows host to allow incoming traffic on TCP port 5044:</p><pre>New-NetFirewallRule -DisplayName &quot;Graylog Beats 5044&quot; -Direction Inbound -LocalPort 5044 -Protocol TCP -Action Allow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw5Vy07lhO2vCt4QEa23Xw.jpeg" /><figcaption>Allowing traffic on port 5044 as windows was blocking it by default</figcaption></figure><h3>5. Configuring Filebeat on Wazuh Manager</h3><p>Filebeat monitors the core alert file (/var/ossec/logs/alerts/alerts.json) on the Wazuh Manager and forwards formatted JSON records to Graylog.</p><p>On the Wazuh Manager VM, edit /etc/filebeat/filebeat.yml:</p><pre>filebeat.modules:<br>  - module: wazuh<br>    alerts:<br>      enabled: true<br>    archives:<br>      enabled: false<br><br>logging.level: info<br>logging.to_files: true<br>logging.files:<br>  path: /var/log/filebeat<br>  name: filebeat<br>  keepfiles: 7<br>  permissions: 0644<br><br>output.logstash:<br>  hosts: [&quot;&lt;windows host ip&gt;:5044&quot;]</pre><p><strong>Critical Configuration Rule:</strong> YAML parser syntax requires literal spaces instead of tabs. The hosts: definition under output.logstash: must be indented by <strong>exactly two spaces</strong>. Incorrect indentation or tab characters will throw errors such as yaml: line XX: did not find expected key or No outputs are defined.</p><p>Validate the configuration file and restart the service:</p><pre>sudo filebeat test config<br>sudo systemctl restart filebeat<br>sudo systemctl status filebeat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*RZWUDiLjn1TPd6xt-NrwtQ.jpeg" /><figcaption>filebeat configuration</figcaption></figure><h3>6. Troubleshooting Real-World Pipeline Bottlenecks</h3><p>Setting up multi-node security pipelines often uncovers networking and configuration hurdles. Here are the main troubleshooting solutions applied during this integration:</p><h3>A. Testing Sockets Without nc (Netcat)</h3><p>Minimal Linux installations (like the Wazuh OVA appliance) often omit diagnostic utilities like nc or telnet. You can test network port connectivity directly using Bash&#39;s built-in TCP features:</p><pre>timeout 3 bash -c &quot;&lt;/dev/tcp/192.168.56.1/5044&quot; &amp;&amp; echo &quot;PORT OPEN&quot; || echo &quot;PORT CLOSED&quot;</pre><h3>Resolving Clock Skew &amp; Timezone Search Filters</h3><p>If Graylog’s <strong>System / Inputs</strong> tab displays active network throughput on port 5044, but queries return zero results, check for VM clock drift:</p><p>Bash</p><pre>date</pre><p>When system clocks differ across host and guest VMs, events are indexed under shifted timestamps. Expanding Graylog’s time range dropdown from “Search in last 5 minutes” to <strong>Search in all messages</strong> resolves search visibility while system clocks resynchronize.</p><h3>7. Generating Security Events &amp; Verifying Log Delivery</h3><p>To confirm end-to-end ingestion, generate synthetic authentication failures on your connected endpoints.</p><h3>From Windows Host (PowerShell):</h3><p>Trigger a failed authentication event (Windows Event ID 4625):</p><pre>net use \\127.0.0.1\IPC$ /user:fakeuser wrongpassword</pre><h3>From attacker machine(Terminal):</h3><p>Trigger a local authentication failure:</p><p>In my case i was using a windows endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PF83HIBn1F-C_cYw6h5owQ.jpeg" /><figcaption>Powershell view while generating test alerts</figcaption></figure><h3>Verify Log Delivery in Graylog:</h3><ol><li>Open <a href="http://localhost:9000/search.">http://localhost:9000/search.</a></li><li>Type fakeuser into the search bar.</li><li>Set the time range filter to <strong>Search in all messages</strong> and press Enter.</li></ol><p>Expanding any event record displays structured key-value maps (such as agent_name, rule_id, and full_log), confirming that Filebeat and Graylog are successfully ingesting, parsing, and centralizing security telemetry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAVxtZSCNr3SaU7YnquRVQ.jpeg" /><figcaption>fakeuser logs in graylog</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6dfb1f89f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autonomous SOC Alert Triage Pipeline: Wazuh & n8n Agentic AI Automation]]></title>
            <link>https://medium.com/@usmannazir5503/autonomous-soc-alert-triage-pipeline-wazuh-n8n-agentic-ai-automation-07a1fd240c9c?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/07a1fd240c9c</guid>
            <category><![CDATA[alert-triage]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 04:12:02 GMT</pubDate>
            <atom:updated>2026-09-06T04:12:02.912Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Executive Summary</h3><p>Modern Security Operations Centers (SOCs) struggle with alert fatigue and high operational overhead generated by continuous streams of unverified SIEM alerts. This implementation provides an automated, event-driven Agentic AI SOC triage pipeline connecting <strong>Wazuh SIEM</strong>, <strong>n8n Automation Engine</strong>, and <strong>Large Language Models (LLMs)</strong>.</p><p>The pipeline intercepts high-severity alerts (Level 10+) directly on the Wazuh server, conducts real-time Tier-1/Tier-2 context correlation, assigns True/False Positive verdicts, calculates analytical confidence scores, extracts Indicators of Compromise (IOCs), maps threat actions to the MITRE ATT&amp;CK enterprise matrix, and dispatches structured HTML incident triage reports directly to SOC analysts’ email inboxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*BgcEuitEO3MbhpF1kRvqYA.png" /><figcaption>n8n Workflow</figcaption></figure><h3>Flow Lifecycle</h3><ol><li><strong>Detection &amp; Filtering:</strong> Wazuh captures events, matches rules, and invokes a custom Python integration for alerts configured at level &gt;= 10.</li><li><strong>Ingestion:</strong> An n8n Webhook trigger listens over HTTPS and issues an immediate HTTP 200 OK acknowledgment to Wazuh.</li><li><strong>Agentic Reasoning:</strong> An n8n AI Agent (backed by gpt-5-mini at temperature 0.1) processes raw telemetry and enforces structured schema generation via a Structured Output Parser.</li><li><strong>Dashboard Generation:</strong> A JavaScript code node transforms the validated JSON triage object into an HTML incident dashboard.</li><li><strong>Notification:</strong> The SMTP node packages the executive HTML summary and dispatches it immediately to security staff.</li></ol><h3>3. Step-by-Step Implementation Manual</h3><h3>Phase 1: Wazuh Server Webhook &amp; Script Integration</h3><p><strong>Step 1: Deployment of Custom Forwarder Script:</strong></p><p>Created /var/ossec/integrations/custom-n8n.py on the Wazuh Manager to extract raw alert event streams and forward them over HTTPS:</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>Wazuh Production Integration Forwarder for n8n SOC Automation Pipeline.<br>Author: Muhammad Usman<br>Location: /var/ossec/integrations/custom-n8n.py<br>&quot;&quot;&quot;<br><br>import sys<br>import json<br>import os<br>import requests<br>from requests.adapters import HTTPAdapter<br>from urllib3.util.retry import Retry<br><br>LOG_FILE = &quot;/var/ossec/logs/integrations.log&quot;<br><br>def write_log(msg: str):<br>    try:<br>        with open(LOG_FILE, &quot;a&quot;) as f:<br>            f.write(f&quot;[custom-n8n.py] {msg}\n&quot;)<br>    except Exception:<br>        pass<br><br>def create_session() -&gt; requests.Session:<br>    session = requests.Session()<br>    # Retry policy: 3 attempts on intermittent 502, 503, 504 status codes<br>    retries = Retry(<br>        total=3,<br>        backoff_factor=0.5,<br>        status_forcelist=[502, 503, 504],<br>        raise_on_status=False<br>    )<br>    session.mount(&#39;https://&#39;, HTTPAdapter(max_retries=retries))<br>    session.mount(&#39;http://&#39;, HTTPAdapter(max_retries=retries))<br>    return session<br><br>def main():<br>    if len(sys.argv) &lt; 4:<br>        write_log(&quot;[FATAL] Missing required arguments from Wazuh engine.&quot;)<br>        sys.exit(1)<br><br>    alert_file_path = sys.argv[1]<br>    user_api_key = sys.argv[2]   # Passed via &lt;api_key&gt; in ossec.conf<br>    hook_url = sys.argv[3]       # Passed via &lt;hook_url&gt; in ossec.conf<br><br>    if not os.path.exists(alert_file_path):<br>        write_log(f&quot;[ERROR] Alert file path not accessible: {alert_file_path}&quot;)<br>        sys.exit(1)<br><br>    try:<br>        with open(alert_file_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as alert_file:<br>            alert_payload = json.load(alert_file)<br>    except Exception as err:<br>        write_log(f&quot;[ERROR] Failed to parse JSON alert: {str(err)}&quot;)<br>        sys.exit(1)<br><br>    headers = {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;User-Agent&quot;: &quot;Wazuh-SOC-Triage-Engine/2.0&quot;,<br>        &quot;X-Wazuh-Key&quot;: user_api_key<br>    }<br><br>    session = create_session()<br>    try:<br>        response = session.post(<br>            hook_url,<br>            json=alert_payload,<br>            headers=headers,<br>            timeout=(3.05, 10.0) # (connect timeout, read timeout)<br>        )<br>        if response.status_code not in [200, 201, 202]:<br>            write_log(f&quot;[WARN] Non-2xx response from n8n webhook: HTTP {response.status_code} - {response.text}&quot;)<br>            sys.exit(1)<br>            <br>    except requests.exceptions.RequestException as err:<br>        write_log(f&quot;[CRITICAL] Webhook dispatch failed: {str(err)}&quot;)<br>        sys.exit(1)<br><br>    sys.exit(0)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Step 2: Set Script Permissions and Ownership</h4><p>Harden the integration file permissions so the wazuh system user can execute it securely:</p><pre>sudo chmod 750 /var/ossec/integrations/custom-n8n.py<br>sudo chown root:wazuh /var/ossec/integrations/custom-n8n.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nQuRI4xKq1DbE2DEeeGE0g.png" /><figcaption>Terminal View of Commands</figcaption></figure><h4>Step 3: Configure Alert Forwarding Filters in Wazuh</h4><p>Open the primary Wazuh Manager configuration file:</p><pre>sudo nano /var/ossec/etc/ossec.conf</pre><p>Add the production &lt;integration&gt; declaration inside &lt;ossec_config&gt;. Use your live production webhook URL (do <strong>not</strong> use the -test path) and configure a shared secret under &lt;api_key&gt;:</p><pre>&lt;!-- Production Automated SOC Triage Integration --&gt;<br>  &lt;integration&gt;<br>    &lt;name&gt;custom-n8n.py&lt;/name&gt;<br>    &lt;hook_url&gt;https://n8n.your-soc-domain.internal/webhook/wazuh-alerts&lt;/hook_url&gt;<br>    &lt;api_key&gt;c0a80150-prod-sec-key-83f1-482a-a829-token991&lt;/api_key&gt;<br>    &lt;level&gt;10&lt;/level&gt;<br>    &lt;alert_format&gt;json&lt;/alert_format&gt;<br>  &lt;/integration&gt;<br>&lt;/ossec_config&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*I8WLQewWp6ZYMLlPo2qnig.png" /><figcaption>ossec.conf Configuration</figcaption></figure><p>Restart the Wazuh Manager to apply the configuration:</p><pre><br>sudo systemctl restart wazuh-manager<br>sudo tail -n 20 /var/ossec/logs/ossec.log | grep -i integration</pre><h3>Phase 2: n8n Workflow Construction</h3><h4>Step 4: Configure Node 1 — Webhook Trigger</h4><ol><li>Add a <strong>Webhook</strong> node to your n8n workflow canvas.</li><li>Set <strong>HTTP Method</strong> to POST.</li><li><strong>Authentication:</strong> Header Auth</li></ol><ul><li><strong>Header Name:</strong> X-Wazuh-Key</li><li><strong>Value:</strong> c0a80150-prod-sec-key-83f1-482a-a829-token991</li></ul><ol><li>Set <strong>Respond</strong> to Immediately (or onReceived) to return a 200 OK response right away, avoiding timeouts on the Wazuh integration runner.</li><li>Click <strong>Listen for test event</strong> when debugging.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*dLb-jjtvv3Py7wRu-FSgQA.png" /><figcaption>Node 1 of n8n Workflow</figcaption></figure><h4>Step 5: Configure Node 2 — AI Agent &amp; Chat Model</h4><ol><li>Add an <strong>AI Agent</strong> node and wire it to the Webhook node.</li><li>Set <strong>Agent Type</strong> to Tools Agent.</li><li>Set <strong>Source for Prompt (User Message)</strong> to:</li></ol><pre>Analyze the following raw Wazuh security alert JSON:<br>{{ JSON.stringify($json.body) }}<br><br>Execute an automated Tier-2 SOC evaluation. Validate whether this is an active attack, scanning reconnaissance, operational false positive, or normal administrative action. Extract all observable Indicators of Compromise (IOCs), map techniques to the MITRE ATT&amp;CK enterprise matrix, assess true confidence, and generate deterministic immediate containment steps.</pre><p>4. In the <strong>Settings</strong> tab, configure the <strong>System Prompt</strong>:</p><pre>You are an Autonomous Tier-2 SOC Incident Responder Agent embedded in a high-security Enterprise SOC.<br>Your operational objectives:<br>1. Ingest raw Wazuh JSON alerts directly from internal endpoints and network collectors.<br>2. Cross-correlate rule severity, process command lines, source/destination network artifacts, and actor context.<br>3. Classify alerts strictly as &quot;True Positive&quot;, &quot;False Positive&quot;, or &quot;Suspicious&quot;.<br>4. Assign an integer confidence score from 0 to 100 based strictly on technical evidence.<br>5. Extract exact IOCs (IPs, users, process paths, hash values) present in the payload.<br>6. Map the behavioral pattern to exact MITRE ATT&amp;CK Techniques and Tactics.<br>7. Return actionable, non-generic operational remediation commands for SOC engineers.<br>Never hallucinate non-existent IPs or usernames. If an attribute does not exist in the raw log, output &quot;N/A&quot;.</pre><p>5. Add an <strong>OpenAI Chat Model</strong> sub-node and connect it to the <strong>Chat Model</strong> input of the AI Agent:</p><ul><li><strong>Model:</strong> gpt-5-mini</li><li><strong>Temperature:</strong> 0.1 (low temperature ensures deterministic, objective risk evaluations)</li><li><strong>Max Tokens:</strong> 1500</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wCYSXHUsg8uzsqwzzD8W2Q.png" /><figcaption>Node 2 of n8n Workflow</figcaption></figure><h4>Node 3: Structured Output Parser (Sub-Node)</h4><p>Connected directly to the AI Agent to enforce strict JSON structure output:</p><pre>{<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;alert_summary&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;description&quot;: &quot;Concise summary detailing the suspicious event, affected host, and rule violated.&quot;<br>    },<br>    &quot;classification&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;enum&quot;: [&quot;True Positive&quot;, &quot;False Positive&quot;, &quot;Suspicious&quot;],<br>      &quot;description&quot;: &quot;Final analytical triage verdict.&quot;<br>    },<br>    &quot;confidence_score&quot;: {<br>      &quot;type&quot;: &quot;number&quot;,<br>      &quot;description&quot;: &quot;Integer percentage (0-100) denoting certainty of the verdict.&quot;<br>    },<br>    &quot;iocs&quot;: {<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;properties&quot;: {<br>        &quot;source_ip&quot;: { &quot;type&quot;: &quot;string&quot; },<br>        &quot;target_user&quot;: { &quot;type&quot;: &quot;string&quot; },<br>        &quot;process_name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>        &quot;destination_port&quot;: { &quot;type&quot;: &quot;string&quot; }<br>      },<br>      &quot;required&quot;: [&quot;source_ip&quot;, &quot;target_user&quot;]<br>    },<br>    &quot;mitre_mapping&quot;: {<br>      &quot;type&quot;: &quot;array&quot;,<br>      &quot;items&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;technique_id&quot;: { &quot;type&quot;: &quot;string&quot; },<br>          &quot;technique_name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>          &quot;tactic&quot;: { &quot;type&quot;: &quot;string&quot; }<br>        },<br>        &quot;required&quot;: [&quot;technique_id&quot;, &quot;technique_name&quot;, &quot;tactic&quot;]<br>      }<br>    },<br>    &quot;immediate_actions&quot;: {<br>      &quot;type&quot;: &quot;array&quot;,<br>      &quot;items&quot;: { &quot;type&quot;: &quot;string&quot; },<br>      &quot;description&quot;: &quot;Prioritized containment and isolation steps.&quot;<br>    },<br>    &quot;security_recommendations&quot;: {<br>      &quot;type&quot;: &quot;array&quot;,<br>      &quot;items&quot;: { &quot;type&quot;: &quot;string&quot; },<br>      &quot;description&quot;: &quot;Hardening, detection rules tuning, or firewall policy updates.&quot;<br>    }<br>  },<br>  &quot;required&quot;: [<br>    &quot;alert_summary&quot;,<br>    &quot;classification&quot;,<br>    &quot;confidence_score&quot;,<br>    &quot;iocs&quot;,<br>    &quot;mitre_mapping&quot;,<br>    &quot;immediate_actions&quot;,<br>    &quot;security_recommendations&quot;<br>  ]<br>}</pre><h3>4. Phase 3: Production HTML Dashboard Generator (JavaScript Node)</h3><p>This production version includes defensive handling for null fields, dynamic CSS variables based on threat levels, and clean HTML escaping:</p><pre>// Retrieve parsed triage object from upstream agent<br>const triage = $json.output || $json;<br><br>// Sanitize inputs<br>const escapeHtml = (unsafe) =&gt; {<br>  if (typeof unsafe !== &#39;string&#39;) return unsafe ?? &#39;N/A&#39;;<br>  return unsafe<br>    .replace(/&amp;/g, &quot;&amp;amp;&quot;)<br>    .replace(/&lt;/g, &quot;&amp;lt;&quot;)<br>    .replace(/&gt;/g, &quot;&amp;gt;&quot;)<br>    .replace(/&quot;/g, &quot;&amp;quot;&quot;)<br>    .replace(/&#39;/g, &quot;&amp;#039;&quot;);<br>};<br><br>// Evaluate Verdict Styles<br>const classification = triage.classification || &#39;Suspicious&#39;;<br>let verdictColor = &#39;#d97706&#39;;<br>let verdictBg = &#39;#fef3c7&#39;;<br><br>if (classification === &#39;True Positive&#39;) {<br>  verdictColor = &#39;#dc2626&#39;;<br>  verdictBg = &#39;#fee2e2&#39;;<br>} else if (classification === &#39;False Positive&#39;) {<br>  verdictColor = &#39;#16a34a&#39;;<br>  verdictBg = &#39;#dcfce7&#39;;<br>}<br><br>const rawConfidence = triage.confidence_score;<br>let displayConfidence = &#39;N/A&#39;;<br>if (typeof rawConfidence === &#39;number&#39;) {<br>  displayConfidence = rawConfidence &lt;= 1 ? (rawConfidence * 100).toFixed(0) + &#39;%&#39; : rawConfidence + &#39;%&#39;;<br>}<br><br>const htmlDashboard = `&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;style&gt;<br>  body { font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif; background-color: #f1f5f9; color: #0f172a; margin: 0; padding: 24px; }<br>  .container { max-width: 800px; margin: auto; background: #ffffff; border-radius: 8px; border: 1px solid #cbd5e1; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.08); }<br>  .header { background: #0f172a; color: #ffffff; padding: 20px 24px; display: flex; justify-content: space-between; align-items: center; }<br>  .header h2 { margin: 0; font-size: 18px; letter-spacing: 0.5px; }<br>  .header .tag { font-size: 11px; background: #1e293b; padding: 4px 8px; border-radius: 4px; border: 1px solid #334155; color: #94a3b8; }<br>  .content { padding: 24px; }<br>  .grid { display: flex; gap: 16px; margin-bottom: 24px; }<br>  .card { flex: 1; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 14px 16px; }<br>  .card-label { font-size: 11px; color: #64748b; font-weight: 700; text-transform: uppercase; margin-bottom: 6px; }<br>  .badge { display: inline-block; padding: 6px 12px; border-radius: 4px; font-weight: 800; font-size: 13px; color: ${verdictColor}; background: ${verdictBg}; }<br>  .section-title { font-size: 12px; font-weight: 800; text-transform: uppercase; color: #334155; margin: 24px 0 10px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 6px; letter-spacing: 0.5px; }<br>  .box { background: #f8fafc; border-left: 4px solid #0284c7; padding: 14px; border-radius: 0 6px 6px 0; font-size: 13px; line-height: 1.6; }<br>  table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 13px; }<br>  th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid #e2e8f0; }<br>  th { background: #f8fafc; color: #475569; font-weight: 700; font-size: 12px; }<br>  code { background: #e2e8f0; color: #0f172a; padding: 2px 6px; border-radius: 4px; font-family: &#39;SFMono-Regular&#39;, Consolas, Monaco, monospace; font-size: 12px; }<br>  ul, ol { padding-left: 20px; margin: 8px 0; font-size: 13px; line-height: 1.6; }<br>  .action-item { color: #b91c1c; font-weight: 600; margin-bottom: 4px; }<br>  .footer { background: #f8fafc; padding: 12px 24px; border-top: 1px solid #e2e8f0; font-size: 11px; color: #94a3b8; text-align: center; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;header&quot;&gt;<br>    &lt;h2&gt;Autonomous SOC Incident Triage&lt;/h2&gt;<br>    &lt;span class=&quot;tag&quot;&gt;Wazuh SIEM • Production Engine&lt;/span&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;content&quot;&gt;<br>    &lt;div class=&quot;grid&quot;&gt;<br>      &lt;div class=&quot;card&quot;&gt;<br>        &lt;div class=&quot;card-label&quot;&gt;Verdict&lt;/div&gt;<br>        &lt;span class=&quot;badge&quot;&gt;${escapeHtml(classification)}&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;card&quot;&gt;<br>        &lt;div class=&quot;card-label&quot;&gt;Confidence Assessment&lt;/div&gt;<br>        &lt;div style=&quot;font-size: 18px; font-weight: 800; color: #0f766e;&quot;&gt;${escapeHtml(displayConfidence)}&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>        <br>    &lt;div class=&quot;section-title&quot;&gt;Alert Summary&lt;/div&gt;<br>    &lt;div class=&quot;box&quot;&gt;${escapeHtml(triage.alert_summary || &#39;No summary available.&#39;)}&lt;/div&gt;<br>        <br>    &lt;div class=&quot;section-title&quot;&gt;Identified Indicators of Compromise&lt;/div&gt;<br>    &lt;table&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;&lt;th&gt;Indicator Type&lt;/th&gt;&lt;th&gt;Observed Value&lt;/th&gt;&lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody&gt;<br>        &lt;tr&gt;&lt;td&gt;Attacker Source IP&lt;/td&gt;&lt;td&gt;&lt;code&gt;${escapeHtml(triage.iocs?.source_ip)}&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;<br>        &lt;tr&gt;&lt;td&gt;Targeted System User&lt;/td&gt;&lt;td&gt;&lt;code&gt;${escapeHtml(triage.iocs?.target_user)}&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;<br>        &lt;tr&gt;&lt;td&gt;Process Artifact&lt;/td&gt;&lt;td&gt;&lt;code&gt;${escapeHtml(triage.iocs?.process_name || &#39;N/A&#39;)}&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br><br>    &lt;div class=&quot;section-title&quot;&gt;MITRE ATT&amp;CK Correlation&lt;/div&gt;<br>    &lt;table&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;&lt;th&gt;Technique ID&lt;/th&gt;&lt;th&gt;Technique Name&lt;/th&gt;&lt;th&gt;Tactic&lt;/th&gt;&lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody&gt;<br>        ${Array.isArray(triage.mitre_mapping) &amp;&amp; triage.mitre_mapping.length &gt; 0 ? <br>          triage.mitre_mapping.map(m =&gt; `<br>            &lt;tr&gt;<br>              &lt;td&gt;&lt;code&gt;${escapeHtml(m.technique_id)}&lt;/code&gt;&lt;/td&gt;<br>              &lt;td&gt;&lt;strong&gt;${escapeHtml(m.technique_name)}&lt;/strong&gt;&lt;/td&gt;<br>              &lt;td&gt;${escapeHtml(m.tactic)}&lt;/td&gt;<br>            &lt;/tr&gt;<br>          `).join(&#39;&#39;) : &#39;&lt;tr&gt;&lt;td colspan=&quot;3&quot;&gt;No explicit MITRE techniques mapped&lt;/td&gt;&lt;/tr&gt;&#39;}<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br><br>    &lt;div class=&quot;section-title&quot;&gt;Immediate Containment Actions&lt;/div&gt;<br>    &lt;ol&gt;<br>      ${Array.isArray(triage.immediate_actions) &amp;&amp; triage.immediate_actions.length &gt; 0 ? <br>        triage.immediate_actions.map(act =&gt; `&lt;li class=&quot;action-item&quot;&gt;${escapeHtml(act)}&lt;/li&gt;`).join(&#39;&#39;) : &#39;&lt;li&gt;No containment required.&lt;/li&gt;&#39;}<br>    &lt;/ol&gt;<br><br>    &lt;div class=&quot;section-title&quot;&gt;Security Recommendations&lt;/div&gt;<br>    &lt;ul&gt;<br>      ${Array.isArray(triage.security_recommendations) &amp;&amp; triage.security_recommendations.length &gt; 0 ? <br>        triage.security_recommendations.map(r =&gt; `&lt;li&gt;${escapeHtml(r)}&lt;/li&gt;`).join(&#39;&#39;) : &#39;&lt;li&gt;No recommendations provided.&lt;/li&gt;&#39;}<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;footer&quot;&gt;Generated by Autonomous AI SOC Agent Pipeline • High-Severity Incident Notification&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;`;<br><br>return {<br>  htmlReport: htmlDashboard,<br>  raw_triage: triage<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7LYE4lSvmg3S_m2nYtHcHA.png" /><figcaption>javacript node</figcaption></figure><h3>5. Phase 4: Production SMTP Dispatch Configuration</h3><h3>Node 4: Send Email Node Setup</h3><ul><li><strong>Credential Type:</strong> SMTP</li><li><strong>Host:</strong> smtp.enterprise-mail.com (or smtp.gmail.com with App Password)</li><li><strong>Port:</strong> 465 (SSL/TLS Enabled)</li><li><strong>From Email:</strong> soc-automation@yourdomain.com</li><li><strong>To Email:</strong> soc-tier2@yourdomain.com, oncall-incident@yourdomain.com</li><li><strong>Subject Line:</strong></li></ul><pre>🚨 [SEV-HIGH] SOC Alert: {{ $json.raw_triage.classification }} - MITRE {{ $json.raw_triage.mitre_mapping[0]?.technique_id || &#39;T1110&#39; }}</pre><ul><li><strong>Email Format:</strong> HTML</li><li><strong>HTML Body:</strong> {{ $json.htmlReport }}</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*CCAXMjLAxlJnn8v_PimLvg.png" /><figcaption>email recieved after testing</figcaption></figure><h3>6. End-to-End Production Verification &amp; Attack Simulation</h3><p>To confirm the automated pipeline operates cleanly under production load, trigger a real security event using an SSH brute-force attempt against a managed Linux endpoint (or execute a controlled payload through curl targeting the production webhook with strict authentication).</p><h3>Method: Production Webhook Validation via cURL</h3><p>Execute this command directly from the Wazuh Manager to test the live network path, mutual authentication, and JSON parsing:</p><pre>curl -X POST https://n8n.your-soc-domain.internal/webhook/wazuh-alerts \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;X-Wazuh-Key: c0a80150-prod-sec-key-83f1-482a-a829-token991&quot; \<br>  -d &#39;{<br>    &quot;timestamp&quot;: &quot;2026-09-06T08:45:00.000+0000&quot;,<br>    &quot;rule&quot;: {<br>      &quot;level&quot;: 10,<br>      &quot;id&quot;: &quot;5712&quot;,<br>      &quot;description&quot;: &quot;sshd: brute force trying to get access to the system.&quot;,<br>      &quot;mitre&quot;: {<br>        &quot;id&quot;: [&quot;T1110&quot;],<br>        &quot;tactic&quot;: [&quot;Credential Access&quot;],<br>        &quot;technique&quot;: [&quot;Brute Force&quot;]<br>      }<br>    },<br>    &quot;agent&quot;: {<br>      &quot;id&quot;: &quot;001&quot;,<br>      &quot;name&quot;: &quot;production-core-srv&quot;,<br>      &quot;ip&quot;: &quot;10.0.1.50&quot;<br>    },<br>    &quot;data&quot;: {<br>      &quot;srcip&quot;: &quot;198.51.100.23&quot;,<br>      &quot;dstuser&quot;: &quot;root&quot;<br>    },<br>    &quot;full_log&quot;: &quot;Sep 06 08:45:00 production-core-srv sshd[44012]: Failed password for root from 198.51.100.23 port 49152 ssh2&quot;<br>  }&#39;</pre><p><strong>7. Operational Benchmark &amp; Performance Metrics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgYHRlmz6enR2ESLds117Q.jpeg" /></figure><h3>Operational Takeaway</h3><p>This production setup isolates network calls with a resilient Python daemon, verifies ingress webhook credentials, enforces schema integrity using strict JSON definitions, and sends formatted HTML dashboards to SOC analysts’ inboxes. The result is a consistent, low-latency triage pipeline that reduces MTTR from minutes to seconds without dropping alerts or requiring manual data collection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07a1fd240c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Automated SOC Pipeline: Ingesting Wazuh SIEM Alerts into DFIR-IRIS with Docker & n8n]]></title>
            <link>https://medium.com/@usmannazir5503/building-an-automated-soc-pipeline-ingesting-wazuh-siem-alerts-into-dfir-iris-with-docker-n8n-780bc32baeb4?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/780bc32baeb4</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[siri]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[wazuh]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 21:13:52 GMT</pubDate>
            <atom:updated>2026-08-17T21:13:52.671Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to eliminate alert fatigue, bypass network constraints, and build a production-grade automated incident response workflow.</em></p><p>In a modern Security Operations Center (SOC), speed and accuracy dictate the outcome of an investigation. When high-severity security events trigger across production endpoints, relying on human analysts to manually copy log payloads, format metadata, and file ticket records creates unnecessary response latency.</p><p>During my cybersecurity internship at <strong>ITSOLERA Pvt. Ltd.</strong>, I set out to solve this operational bottleneck by building a fully automated Security Orchestration, Automation, and Response (SOAR) pipeline.</p><p>This guide walks through how to link the <strong>Wazuh SIEM Platform</strong>, a containerized <strong>n8n Workflow Engine</strong>, and <strong>DFIR-IRIS Case Management</strong> into a unified, enterprise-style architecture — running entirely in a secure internal environment without unstable public tunnels.</p><h3>1. High-Level Architecture Overview</h3><p>The system operates across four discrete stages:</p><ol><li><strong>Telemetry Ingestion &amp; Detection:</strong> A monitored endpoint streams authentication events to the Wazuh Manager.</li><li><strong>Alert Forwarding:</strong> Wazuh evaluates custom rules and fires a webhook POST request for any event with <strong>Rule Level $\ge 10$</strong>.</li><li><strong>Orchestration &amp; Data Normalization:</strong> An internal n8n instance ingests the JSON payload, applies logic filtering, and maps the fields to match the DFIR-IRIS case schema.</li><li><strong>Automated Ticket Creation:</strong> An authenticated HTTPS REST API call provisions a structured incident case in DFIR-IRIS instantly.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eECD9XOoSL7h2ViLTonSyA.jpeg" /><figcaption>Figure 1: Complete High-Level Architecture Diagram showing log flow from Wazuh through Dockerized n8n to DFIR-IRIS.</figcaption></figure><h3>2. Infrastructure Setup &amp; Environment Details</h3><ul><li><strong>Host Platform:</strong> Kali Linux (x86_64) running on Oracle VM VirtualBox</li><li><strong>Detection Engine:</strong> Wazuh SIEM Manager (v4.x)</li><li><strong>Workflow Engine:</strong> n8n Workflow Automation (Docker Container)</li><li><strong>Incident Management:</strong> DFIR-IRIS v2 (Docker Compose over HTTPS on 172.0.0.0)</li></ul><h3>3. Deploying DFIR-IRIS via Docker Compose</h3><p>To establish the case management repository, DFIR-IRIS was deployed locally using its official container stack.</p><h3>Step 1: Clone and Launch the Service</h3><p>Bash</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install -y git docker.io docker-compose<br>git clone https://github.com/dfir-iris/iris-web.git<br>cd iris-web<br>cp .env.model .env<br>docker-compose up -d --build</pre><h3>Step 2: Extract API Authentication Token</h3><ul><li>Access the web console over secure HTTPS: [https://172.17.0.1](https://172.0.0.0).</li><li>Navigate to <strong>User Profile / Settings</strong> $\rightarrow$ <strong>API Key</strong>.</li><li>Generate and copy the API key:</li><li>Plaintext</li></ul><pre>Bearer &lt;APIKEY&gt;</pre><ul><li>Note the default customer context: IrisInitialClient (<strong>Customer ID:</strong> 1).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVukFcEkms91NI_ugOqhHQ.jpeg" /><figcaption>Figure 2: DFIR-IRIS Dashboard and API Key configuration interface under secure HTTPS.</figcaption></figure><h3>4. Deploying n8n Locally in Docker</h3><p>Cloud-hosted automation services enforce strict Server-Side Request Forgery (SSRF) protections, preventing outbound requests to private IP ranges like 172.17.x.x or 192.168.x.x.</p><p>To maintain security and eliminate the need for third-party exposure tunnels, n8n was deployed directly onto the local Docker bridge network:</p><p>Bash</p><pre>docker run -d \<br>  --name n8n-prod \<br>  --restart always \<br>  -p 5678:5678 \<br>  -v n8n_data:/home/node/.n8n \<br>  docker.n8n.io/n8nio/n8n</pre><p>Once running, access the local canvas via plain HTTP:</p><p>Plaintext</p><pre>http://localhost:5678</pre><h3>5. Building the SOAR Automation Workflow</h3><p>Inside the n8n canvas, create a workflow named Wazuh-to-IRIS-Pipeline utilizing four modular nodes:</p><h3>1. Webhook Trigger Node</h3><ul><li><strong>HTTP Method:</strong> POST</li><li><strong>Path:</strong> wazuh-alerts</li><li><strong>Response Mode:</strong> Immediately (returns HTTP 200 OK to prevent the Wazuh manager from timing out).</li></ul><h3>2. If / Severity Filter Node</h3><p>To prevent low-priority events from cluttering the incident queue, configure an evaluation condition:</p><ul><li><strong>Value 1:</strong> {{ $json.body.rule.level }}</li><li><strong>Operation:</strong> Number $\rightarrow$ Larger or equal to (&gt;=)</li><li><strong>Value 2:</strong> 10</li><li>Route downstream execution strictly from the true output port.</li></ul><h3>3. Edit Fields (Set) Node</h3><p>Map raw telemetry into DFIR-IRIS schema attributes:</p><ul><li><strong>case_name:</strong> ={{ &quot;Wazuh Alert [&quot; + $(&#39;Webhook&#39;).item.json.body.rule.id + &quot;] - &quot; + $(&#39;Webhook&#39;).item.json.body.rule.description }}</li><li><strong>case_description:</strong> ={{ &quot;Agent: &quot; + $(&#39;Webhook&#39;).item.json.body.agent.name + &quot; (&quot; + $(&#39;Webhook&#39;).item.json.body.agent.ip + &quot;)\nRule ID: &quot; + $(&#39;Webhook&#39;).item.json.body.rule.id + &quot;\nRule Level: &quot; + $(&#39;Webhook&#39;).item.json.body.rule.level + &quot;\nLog: &quot; + ($(&#39;Webhook&#39;).item.json.body.full_log || &quot;N/A&quot;) }}</li><li><strong>case_soc_id: </strong>={{ $(&#39;Webhook&#39;).item.json.body.id }}</li><li><strong>case_customer:</strong> 1</li></ul><h3>4. HTTP Request Node (Ticket Dispatcher)</h3><ul><li><strong>Method:</strong> POST</li><li><strong>URL:</strong> [https://172.0.0.0/manage/cases/add](https://172.0.0.0/manage/cases/add)</li><li><strong>Authentication:</strong> Generic Credential Type $\rightarrow$ Header Auth</li><li><strong>Header Name:</strong> Authorization</li><li><strong>Header Value:</strong> Bearer &lt;YOUR_IRIS_API_KEY&gt;</li><li><strong>Send Headers:</strong> Content-Type: application/json</li><li><strong>Send Body:</strong> Using JSON</li><li><strong>JSON Body Expression:</strong></li><li>JSON</li></ul><pre>{{   JSON.stringify({     &quot;case_name&quot;: $json.case_name,     &quot;case_description&quot;: $json.case_description,     &quot;case_customer&quot;: 1,     &quot;case_soc_id&quot;: $json.case_soc_id   }) }}</pre><ul><li><strong>Options:</strong> Toggle Ignore SSL Issues to true to allow the local self-signed certificate over HTTPS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHAKDubw2jptfe8aCOEloA.jpeg" /><figcaption>Figure 3: Complete n8n workflow canvas showing the active execution line.</figcaption></figure><h3>6. Configuring Wazuh Manager Integration</h3><p>To forward alerts directly from Wazuh to the local n8n webhook listener, modify the main configuration file:</p><ul><li>Open /var/ossec/etc/ossec.conf:</li><li>Bash</li></ul><pre>sudo nano /var/ossec/etc/ossec.conf</pre><ul><li>Append the custom integration block directly inside &lt;ossec_config&gt;:</li><li>XML</li></ul><pre>&lt;integration&gt;  <br> &lt;name&gt;custom-webhook&lt;/name&gt;  <br> &lt;hook_url&gt;http://127.0.0.1:5678/webhook/wazuh-alerts&lt;/hook_url&gt;  <br> &lt;level&gt;10&lt;/level&gt;  <br> &lt;alert_format&gt;json&lt;/alert_format&gt;<br> &lt;/integration&gt;</pre><ul><li>Test the XML syntax and restart the daemon:</li><li>Bash</li></ul><pre>sudo /var/ossec/bin/wazuh-analysisd -t<br>sudo systemctl restart wazuh-manager</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*y5l59c2JkiN-YYUT6Oofyg.jpeg" /><figcaption>Figure 4: Wazuh Manager configuration file displaying the <em>&lt;integration&gt;</em> block.</figcaption></figure><h3>7. Verification &amp; End-to-End Testing</h3><h3>Simulating a High-Severity Incident</h3><p>To test the pipeline end-to-end, simulate a brute-force SSH authentication alert (Rule 5710, Severity Level 12):</p><p>Bash</p><pre>curl -X POST http://localhost:5678/webhook-test/wazuh-alerts \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;id&quot;: &quot;1718000001.12345&quot;,<br>    &quot;rule&quot;: {<br>      &quot;id&quot;: &quot;5710&quot;,<br>      &quot;level&quot;: 12,<br>      &quot;description&quot;: &quot;SSHD authentication failed multiple times&quot;<br>    },<br>    &quot;agent&quot;: {<br>      &quot;id&quot;: &quot;001&quot;,<br>      &quot;name&quot;: &quot;prod-ubuntu-server&quot;,<br>      &quot;ip&quot;: &quot;192.168.1.50&quot;<br>    },<br>    &quot;full_log&quot;: &quot;Jun 16 02:15:01 prod-ubuntu sshd[1024]: Failed password for root from 203.0.113.5 port 42123 ssh2&quot;<br>  }&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRAEcOoN03dFLDf-KT_B-g.jpeg" /></figure><h3>Validating Case Creation in DFIR-IRIS</h3><ul><li>Log into the DFIR-IRIS interface ([https://172.0.0.0](https://172.0.0.0)).</li><li>Navigate to <strong>Investigation</strong> $\rightarrow$ <strong>Cases</strong>.</li><li>Confirm the new incident record appears:</li><li><strong>Case Title:</strong> Wazuh Alert [5710] - SSHD authentication failed multiple times</li><li><strong>Customer:</strong> IrisInitialClient (#1)</li><li><strong>Description:</strong> Contains the offending host IP (192.168.1.50), machine name, rule classification, and raw syslog audit stream.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fE616gur0_22YFcGE0o5w.jpeg" /><figcaption>Figure 6: n8n Execution log showing successful status 200 responses across all nodes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twoNI8620IiirCHQsrXLVA.jpeg" /></figure><blockquote>Figure 7: DFIR-IRIS Incident Case View showing the parsed Wazuh telemetry.</blockquote><h3>Conclusion &amp; Key Takeaways</h3><p>By containerizing the entire SOAR pipeline locally:</p><ul><li><strong>Zero External Dependencies:</strong> The system functions reliably without relying on third-party tunnels or external cloud routers.</li><li><strong>Noise Reduction:</strong> Applying strict severity thresholds (Level≥10$) keeps case queues clean and actionable.</li><li><strong>Faster Incident Response:</strong> Triage time drops from minutes of manual data entry to sub-second automated ticket provisioning.</li></ul><p><em>Written by </em><strong><em>Muhammad Usman</em></strong><em> — CyberSecurity Analyst</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=780bc32baeb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Automated SOC Pipeline: Wazuh Alert Processing, IoC Extraction, and Threat Intelligence…]]></title>
            <link>https://medium.com/@usmannazir5503/building-an-automated-soc-pipeline-wazuh-alert-processing-ioc-extraction-and-threat-intelligence-795732689a0c?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/795732689a0c</guid>
            <category><![CDATA[soar]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[virustotal]]></category>
            <category><![CDATA[n8n-workflow]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 09:35:33 GMT</pubDate>
            <atom:updated>2026-08-15T09:35:33.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Automated SOC Pipeline: Wazuh Alert Processing, IoC Extraction, and Threat Intelligence Enrichment with n8n</h3><p>Security Operations Centers (SOCs) face an overwhelming volume of daily alerts. Manually investigating every suspicious IP address, malicious file hash, or outbound domain drains valuable analyst time and increases Mean Time to Respond (MTTR).</p><p>To eliminate this manual triage overhead, we can build a Security Orchestration, Automation, and Response (SOAR) pipeline. In this guide, we walk through constructing an automated workflow using <strong>n8n</strong> that ingests <strong>Wazuh</strong> alerts, automatically extracts core Indicators of Compromise (IoCs), queries <strong>VirusTotal</strong> and <strong>AbuseIPDB</strong>, calculates dynamic risk severity, and delivers clean HTML incident reports directly to your SOC inbox.</p><h3>High-Level Architecture</h3><p>The pipeline processes security telemetry across six modular stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWPUZQBleZVqhPu5WCuG5g.png" /><figcaption>Workflow Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQmhaO6Q2-JSN23E7mZjxQ.jpeg" /><figcaption><strong>Complete 6-node n8n workflow canvas with successful execution paths.</strong></figcaption></figure><h3>Step 1: Ingesting Alerts via Webhook</h3><p>The pipeline starts with an <strong>n8n Webhook Node</strong> configured to receive raw JSON alerts from Wazuh via HTTP POST.</p><h3>Webhook Node Parameters:</h3><ul><li><strong>HTTP Method:</strong> POST</li><li><strong>Path:</strong> wazuh-alerts</li><li><strong>Authentication:</strong> None (or Header Auth for production hardening)</li><li><strong>Respond:</strong> When Last Node Finishes (or Immediately)</li></ul><h3>Step 2: Live Integration on Wazuh Server</h3><p>To push live alerts from a Wazuh Manager to the n8n endpoint automatically, we leverage the native wazuh-integratord daemon.</p><h3>1. Custom Integration Script</h3><p>Create /var/ossec/integrations/custom-n8n.py:</p><p>Python</p><pre>#!/usr/bin/env python3<br>import sys<br>import json<br>import requests<br>alert_file = sys.argv[1]<br>hook_url = sys.argv[3]<br>with open(alert_file) as f:<br>    alert_json = json.load(f)<br>headers = {&#39;Content-Type&#39;: &#39;application/json&#39;}<br>try:<br>    response = requests.post(hook_url, json=alert_json, headers=headers, timeout=10)<br>    response.raise_for_status()<br>except Exception as e:<br>    with open(&#39;/var/ossec/logs/integrations.log&#39;, &#39;a&#39;) as log_file:<br>        log_file.write(f&quot;Error forwarding alert to n8n: {str(e)}\n&quot;)</pre><p>Set execution permissions:</p><p>Bash</p><pre>sudo chmod 750 /var/ossec/integrations/custom-n8n.py<br>sudo chown root:wazuh /var/ossec/integrations/custom-n8n.py</pre><h3>2. Configure ossec.conf</h3><p>Append the integration block inside /var/ossec/etc/ossec.conf:</p><p>XML</p><pre>&lt;integration&gt;<br>  &lt;name&gt;custom-n8n.py&lt;/name&gt;<br>  &lt;hook_url&gt;https://&lt;YOUR-N8N-INSTANCE&gt;/webhook/wazuh-alerts&lt;/hook_url&gt;<br>  &lt;level&gt;5&lt;/level&gt;<br>  &lt;alert_format&gt;json&lt;/alert_format&gt;<br>&lt;/integration&gt;<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFKf9qWIAIJEROMWNooaIA.jpeg" /><figcaption>ossec.conf section</figcaption></figure><p>Restart the Wazuh Manager to apply:</p><p>Bash</p><pre>sudo systemctl restart wazuh-manager</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNnpoYXk8yav6oS09YDlHg.jpeg" /><figcaption>Wazuh server terminal displaying integration configuration in ossec.conf and integrator daemon logs.</figcaption></figure><h3>Step 3: Automated IoC Extraction via Regex</h3><p>Raw Wazuh events contain both structured fields and unstructured log text. We use an n8n <strong>Code Node</strong> (JavaScript, Run Once for All Items mode) to parse out public IP addresses, domains, URLs, and cryptographic hashes (MD5, SHA-1, SHA-256) while filtering private subnets.</p><p>JavaScript</p><pre>const items = $input.all();<br>const returnData = [];<br>// Regular expressions to accurately extract IoCs<br>const IP_REGEX = /\b(?!(?:10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.|127\.))\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/g;<br>const URL_REGEX = /https?:\/\/[^\s&quot;&#39;&lt;&gt;]+/gi;<br>const DOMAIN_REGEX = /\b(?!(?:localhost|internal|local)\b)(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/g;<br>const HASH_REGEX = /\b([a-fA-F0-9]{64}|[a-fA-F0-9]{32}|[a-fA-F0-9]{40})\b/g;<br>for (const item of items) {<br>  const alertData = item.json.body || item.json;<br>  const alertString = JSON.stringify(alertData);<br>  const alertId = alertData.id || alertData.rule?.id || &quot;WAZUH-ALERT&quot;;<br>  const alertDescription = alertData.rule?.description || alertData.full_log || &quot;Wazuh Security Event&quot;;<br>  <br>  const ips = Array.from(new Set(alertString.match(IP_REGEX) || []));<br>  const urls = Array.from(new Set(alertString.match(URL_REGEX) || []));<br>  const hashes = Array.from(new Set(alertString.match(HASH_REGEX) || []));<br>  <br>  let domains = Array.from(new Set(alertString.match(DOMAIN_REGEX) || []));<br>  domains = domains.filter(d =&gt; !/^\d+\.\d+\.\d+\.\d+$/.test(d));<br>  returnData.push({<br>    json: {<br>      alertId,<br>      alertDescription,<br>      extractedIps: ips,<br>      extractedUrls: urls,<br>      extractedDomains: domains,<br>      extractedHashes: hashes,<br>      primaryIp: ips.length &gt; 0 ? ips[0] : null,<br>      primaryHash: hashes.length &gt; 0 ? hashes[0] : null<br>    }<br>  });<br>}<br>return returnData;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LyYVGFQDYXlIjIGqB0NUw.jpeg" /><figcaption>Output panel of Code Node showing parsed arrays for extracted IPs, URLs, domains, and hashes.</figcaption></figure><h3>Step 4: Threat Intelligence Enrichment</h3><h3>1. AbuseIPDB Query (Node 3)</h3><p>Add an <strong>HTTP Request</strong> node to evaluate IP reputation against AbuseIPDB:</p><ul><li><strong>Method:</strong> GET</li><li><strong>URL:</strong> [https://api.abuseipdb.com/api/v2/check](https://api.abuseipdb.com/api/v2/check)</li><li><strong>Query Parameters:</strong></li><li><strong>Name:</strong>ipAddress <strong>Value:</strong>{{ $json.primaryIp || &#39;8.8.8.8&#39; }}</li><li><strong>Name:</strong>maxAgeInDays <strong>Value:</strong> 90</li><li><strong>Headers:</strong></li><li><strong>Name:</strong>Key <strong>Value:</strong> &lt;YOUR_ABUSEIPDB_API_KEY&gt;</li><li><strong>Name:</strong>Accept <strong>Value:</strong> application/json</li><li><strong>Settings Tab:</strong> Set <strong>On Error</strong> to Continue (using error output) to prevent pipeline halts on null lookups.</li></ul><h3>2. VirusTotal File Hash Query (Node 4)</h3><p>Add an <strong>HTTP Request</strong> node to query VirusTotal for file reputation:</p><ul><li><strong>Method:</strong> GET</li><li><strong>URL (Expression):</strong> [https://www.virustotal.com/api/v3/files/](https://www.virustotal.com/api/v3/files/){{ $(&#39;Code in JavaScript&#39;).item.json.primaryHash || &#39;e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855&#39; }}</li><li><strong>Headers:</strong></li><li><strong>Name:</strong>x-apikey <strong>Value:</strong> &lt;YOUR_VIRUSTOTAL_API_KEY&gt;</li><li><strong>Settings Tab:</strong> Set <strong>On Error</strong> to Continue (using error output).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mebYl1KJF6S93Efx09cu7A.jpeg" /><figcaption>Threat Intelligence API responses from AbuseIPDB and VirusTotal.</figcaption></figure><h3>Step 5: Risk Scoring Matrix</h3><p>Add a second <strong>Code Node</strong> to evaluate the reputation data and assign a normalized risk score:</p><p>JavaScript</p><pre>const alertInfo = $(&#39;Code in JavaScript&#39;).item?.json || $(&#39;Code&#39;).item?.json || {};<br>const abuseData = $(&#39;HTTP Request&#39;).item?.json?.data || {};<br>const vtData = $(&#39;HTTP Request1&#39;).item?.json?.data?.attributes?.last_analysis_stats || {};<br>const abuseScore = abuseData.abuseConfidenceScore || 0;<br>const vtMalicious = vtData.malicious || 0;<br>let severity = &quot;LOW&quot;;<br>let riskReason = [];<br>if (abuseScore &gt;= 50 || vtMalicious &gt;= 5) {<br>  severity = &quot;HIGH&quot;;<br>  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);<br>} else if (abuseScore &gt;= 20 || vtMalicious &gt;= 1) {<br>  severity = &quot;MEDIUM&quot;;<br>  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);<br>} else {<br>  severity = &quot;LOW&quot;;<br>  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);<br>}<br>return [{<br>  json: {<br>    alertId: alertInfo.alertId || &quot;WAZUH-ALERT&quot;,<br>    description: alertInfo.alertDescription || &quot;No description provided&quot;,<br>    severity: severity,<br>    iocs: {<br>      ips: alertInfo.extractedIps || [],<br>      urls: alertInfo.extractedUrls || [],<br>      domains: alertInfo.extractedDomains || [],<br>      hashes: alertInfo.extractedHashes || []<br>    },<br>    reputation: {<br>      abuseConfidenceScore: abuseScore,<br>      vtMaliciousDetections: vtMalicious,<br>      summary: riskReason.join(&quot; | &quot;)<br>    }<br>  }<br>}];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*P0CuoBdu8Kt0iRL8jq8UAw.jpeg" /><figcaption>Output pane of the Risk Scoring Node showing final assigned severity and consolidated threat summary.</figcaption></figure><h3>Step 6: Automated HTML Incident Reporting</h3><p>Add a <strong>Send Email</strong> node to generate and deliver the formatted alert report to the SOC team:</p><ul><li><strong>Subject:</strong> [SOC Incident Report] Alert: {{ $json.alertId }} - Severity: {{ $json.severity }}</li><li><strong>Email Format:</strong> HTML</li><li><strong>HTML Body:</strong></li></ul><p>HTML</p><pre>&lt;h2&gt;SOC Threat Intelligence Alert Report&lt;/h2&gt;<br>&lt;table border=&quot;1&quot; cellpadding=&quot;8&quot; style=&quot;border-collapse: collapse; width: 100%;&quot;&gt;<br>  &lt;tr style=&quot;background-color: #f4f4f4;&quot;&gt;<br>    &lt;th&gt;Attribute&lt;/th&gt;<br>    &lt;th&gt;Value&lt;/th&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Alert ID&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.alertId }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Calculated Severity&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td style=&quot;font-weight: bold; color: {{ $json.severity === &#39;HIGH&#39; ? &#39;red&#39; : ($json.severity === &#39;MEDIUM&#39; ? &#39;orange&#39; : &#39;green&#39;) }};&quot;&gt;<br>      {{ $json.severity }}<br>    &lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.description }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Extracted IPs&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.iocs.ips.join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Extracted URLs &amp; Domains&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.iocs.domains.concat($json.iocs.urls).join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Extracted Hashes&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.iocs.hashes.join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;&lt;strong&gt;Reputation Summary&lt;/strong&gt;&lt;/td&gt;<br>    &lt;td&gt;{{ $json.reputation.summary }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>&lt;/table&gt;</pre><h3>Testing &amp; Validation Results</h3><p>The workflow was verified against two test cases:</p><h3>1. Benign Event Baseline (WAZUH-1001)</h3><ul><li><strong>Payload:</strong> SSH successful login event containing IP 8.8.8.8 and standard clean hash.</li><li><strong>Outcome:</strong> Abuse score 0%, VirusTotal detections 0 $\rightarrow$ Assigned LOW severity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtEQ5KZ_6i4tPhGLYLPLCg.jpeg" /><figcaption>Email inbox notification displaying the benign alert report with LOW severity.</figcaption></figure><h3>2. Malicious Threat Event (WAZUH-9999)</h3><ul><li><strong>Payload:</strong> Mimikatz execution telemetry containing known malicious C2 IP (118.25.6.39) and binary hash.</li><li><strong>Outcome:</strong> High abuse score, multiple AV flags $\rightarrow$ Assigned HIGH severity and dispatched immediate notification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnfsZ_rq12fzS_gDqu7zsQ.jpeg" /><figcaption>Email inbox notification displaying the malicious alert report with HIGH severity in red.</figcaption></figure><h3><strong>NOTE:</strong></h3><h3><strong>If you want to copy paste the workflow only the json code is below here:</strong></h3><pre>{<br>  &quot;name&quot;: &quot;wazuh-ioc-enrichment&quot;,<br>  &quot;nodes&quot;: [<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;httpMethod&quot;: &quot;POST&quot;,<br>        &quot;path&quot;: &quot;wazuh-alerts&quot;,<br>        &quot;responseMode&quot;: &quot;lastNode&quot;,<br>        &quot;options&quot;: {}<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.webhook&quot;,<br>      &quot;typeVersion&quot;: 2.1,<br>      &quot;position&quot;: [<br>        0,<br>        0<br>      ],<br>      &quot;id&quot;: &quot;9c0ffac7-778e-4c9f-bd17-de8b2666748d&quot;,<br>      &quot;name&quot;: &quot;Webhook&quot;,<br>      &quot;webhookId&quot;: &quot;webhook-id-placeholder&quot;<br>    },<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;jsCode&quot;: &quot;const items = $input.all();\nconst returnData = [];\n\n// Regular Expressions for IoC extraction\nconst IP_REGEX = /\\b(?!(?:10\\.|192\\.168\\.|172\\.(?:1[6-9]|2[0-9]|3[01])\\.|127\\.))\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b/g;\nconst URL_REGEX = /https?:\\/\\/[^\\s\&quot;&#39;&lt;&gt;]+/gi;\nconst DOMAIN_REGEX = /\\b(?!(?:localhost|internal|local)\\b)(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}\\b/g;\nconst HASH_REGEX = /\\b([a-fA-F0-9]{64}|[a-fA-F0-9]{32}|[a-fA-F0-9]{40})\\b/g;\n\nfor (const item of items) {\n  const alertData = item.json.body || item.json;\n  const alertString = JSON.stringify(alertData);\n\n  const alertId = alertData.id || alertData.rule?.id || \&quot;N/A\&quot;;\n  const alertDescription = alertData.rule?.description || alertData.full_log || \&quot;Wazuh Alert Event\&quot;;\n  \n  // Extract matches (deduplicated)\n  const ips = Array.from(new Set(alertString.match(IP_REGEX) || []));\n  const urls = Array.from(new Set(alertString.match(URL_REGEX) || []));\n  const hashes = Array.from(new Set(alertString.match(HASH_REGEX) || []));\n  \n  // Extract domains while ignoring matches that are pure IPs\n  let domains = Array.from(new Set(alertString.match(DOMAIN_REGEX) || []));\n  domains = domains.filter(d =&gt; !/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(d));\n\n  returnData.push({\n    json: {\n      alertId,\n      alertDescription,\n      extractedIps: ips,\n      extractedUrls: urls,\n      extractedDomains: domains,\n      extractedHashes: hashes,\n      primaryIp: ips.length &gt; 0 ? ips[0] : null,\n      primaryHash: hashes.length &gt; 0 ? hashes[0] : null\n    }\n  });\n}\n\nreturn returnData;&quot;<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.code&quot;,<br>      &quot;typeVersion&quot;: 2,<br>      &quot;position&quot;: [<br>        224,<br>        0<br>      ],<br>      &quot;id&quot;: &quot;455b346e-bcd2-4e13-90b5-162f00abf6d6&quot;,<br>      &quot;name&quot;: &quot;Code in JavaScript&quot;<br>    },<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;url&quot;: &quot;https://api.abuseipdb.com/api/v2/check&quot;,<br>        &quot;sendQuery&quot;: true,<br>        &quot;queryParameters&quot;: {<br>          &quot;parameters&quot;: [<br>            {<br>              &quot;name&quot;: &quot;ipAddress&quot;,<br>              &quot;value&quot;: &quot;={{ $json.primaryIp || &#39;8.8.8.8&#39; }}&quot;<br>            },<br>            {<br>              &quot;name&quot;: &quot;maxAgeInDays&quot;,<br>              &quot;value&quot;: &quot;90&quot;<br>            }<br>          ]<br>        },<br>        &quot;sendHeaders&quot;: true,<br>        &quot;headerParameters&quot;: {<br>          &quot;parameters&quot;: [<br>            {<br>              &quot;name&quot;: &quot;Key&quot;,<br>              &quot;value&quot;: &quot;YOUR_ABUSEIPDB_API_KEY&quot;<br>            },<br>            {<br>              &quot;name&quot;: &quot;Accept&quot;,<br>              &quot;value&quot;: &quot;application/json&quot;<br>            }<br>          ]<br>        },<br>        &quot;options&quot;: {}<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.httpRequest&quot;,<br>      &quot;typeVersion&quot;: 4.5,<br>      &quot;position&quot;: [<br>        448,<br>        0<br>      ],<br>      &quot;id&quot;: &quot;dbd9ab53-3475-46ef-bba7-1b5b3bfebf69&quot;,<br>      &quot;name&quot;: &quot;HTTP Request&quot;,<br>      &quot;onError&quot;: &quot;continueErrorOutput&quot;<br>    },<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;url&quot;: &quot;=https://www.virustotal.com/api/v3/files/{{ $(&#39;Code in JavaScript&#39;).item.json.primaryHash || &#39;e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855&#39; }}&quot;,<br>        &quot;sendHeaders&quot;: true,<br>        &quot;headerParameters&quot;: {<br>          &quot;parameters&quot;: [<br>            {<br>              &quot;name&quot;: &quot;x-apikey&quot;,<br>              &quot;value&quot;: &quot;YOUR_VIRUSTOTAL_API_KEY&quot;<br>            }<br>          ]<br>        },<br>        &quot;options&quot;: {}<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.httpRequest&quot;,<br>      &quot;typeVersion&quot;: 4.5,<br>      &quot;position&quot;: [<br>        672,<br>        -96<br>      ],<br>      &quot;id&quot;: &quot;5366684e-ef0f-4645-8550-6ffcc4dc039f&quot;,<br>      &quot;name&quot;: &quot;HTTP Request1&quot;,<br>      &quot;onError&quot;: &quot;continueErrorOutput&quot;<br>    },<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;jsCode&quot;: &quot;// Safely reference previous nodes regardless of n8n default naming\nconst alertInfo = $(&#39;Code in JavaScript&#39;).item?.json || $(&#39;Code&#39;).item?.json || {};\nconst abuseData = $(&#39;HTTP Request&#39;).item?.json?.data || {};\nconst vtData = $(&#39;HTTP Request1&#39;).item?.json?.data?.attributes?.last_analysis_stats || {};\n\nconst abuseScore = abuseData.abuseConfidenceScore || 0;\nconst vtMalicious = vtData.malicious || 0;\n\nlet severity = \&quot;LOW\&quot;;\nlet riskReason = [];\n\n// Scoring matrix evaluation\nif (abuseScore &gt;= 50 || vtMalicious &gt;= 5) {\n  severity = \&quot;HIGH\&quot;;\n  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);\n} else if (abuseScore &gt;= 20 || vtMalicious &gt;= 1) {\n  severity = \&quot;MEDIUM\&quot;;\n  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);\n} else {\n  severity = \&quot;LOW\&quot;;\n  riskReason.push(`AbuseIPDB Confidence: ${abuseScore}%`, `VirusTotal Detections: ${vtMalicious}`);\n}\n\nreturn [{\n  json: {\n    alertId: alertInfo.alertId || \&quot;WAZUH-ALERT\&quot;,\n    description: alertInfo.alertDescription || \&quot;No description provided\&quot;,\n    severity: severity,\n    iocs: {\n      ips: alertInfo.extractedIps || [],\n      urls: alertInfo.extractedUrls || [],\n      domains: alertInfo.extractedDomains || [],\n      hashes: alertInfo.extractedHashes || []\n    },\n    reputation: {\n      abuseConfidenceScore: abuseScore,\n      vtMaliciousDetections: vtMalicious,\n      summary: riskReason.join(\&quot; | \&quot;)\n    }\n  }\n}];&quot;<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.code&quot;,<br>      &quot;typeVersion&quot;: 2,<br>      &quot;position&quot;: [<br>        896,<br>        -145.6907000545116<br>      ],<br>      &quot;id&quot;: &quot;dfe7eed2-44a2-49b8-a429-b473205e84f9&quot;,<br>      &quot;name&quot;: &quot;Code in JavaScript1&quot;<br>    },<br>    {<br>      &quot;parameters&quot;: {<br>        &quot;fromEmail&quot;: &quot;soc-alerts@example.com&quot;,<br>        &quot;toEmail&quot;: &quot;soc-analyst@example.com&quot;,<br>        &quot;subject&quot;: &quot;=[SOC Incident Report] Alert: {{ $json.alertId }} - Severity: {{ $json.severity }}&quot;,<br>        &quot;html&quot;: &quot;=&lt;h2&gt;SOC Threat Intelligence Alert Report&lt;/h2&gt;\n&lt;table border=\&quot;1\&quot; cellpadding=\&quot;8\&quot; style=\&quot;border-collapse: collapse; width: 100%;\&quot;&gt;\n  &lt;tr style=\&quot;background-color: #f4f4f4;\&quot;&gt;\n    &lt;th&gt;Attribute&lt;/th&gt;\n    &lt;th&gt;Value&lt;/th&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Alert ID&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.alertId }}&lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Calculated Severity&lt;/strong&gt;&lt;/td&gt;\n    &lt;td style=\&quot;font-weight: bold; color: {{ $json.severity === &#39;HIGH&#39; ? &#39;red&#39; : ($json.severity === &#39;MEDIUM&#39; ? &#39;orange&#39; : &#39;green&#39;) }};\&quot;&gt;\n      {{ $json.severity }}\n    &lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.description }}&lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Extracted IPs&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.iocs.ips.join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Extracted URLs &amp; Domains&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.iocs.domains.concat($json.iocs.urls).join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Extracted Hashes&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.iocs.hashes.join(&#39;, &#39;) || &#39;None&#39; }}&lt;/td&gt;\n  &lt;/tr&gt;\n  &lt;tr&gt;\n    &lt;td&gt;&lt;strong&gt;Reputation Summary&lt;/strong&gt;&lt;/td&gt;\n    &lt;td&gt;{{ $json.reputation.summary }}&lt;/td&gt;\n  &lt;/tr&gt;\n&lt;/table&gt;&quot;,<br>        &quot;options&quot;: {}<br>      },<br>      &quot;type&quot;: &quot;n8n-nodes-base.emailSend&quot;,<br>      &quot;typeVersion&quot;: 2.1,<br>      &quot;position&quot;: [<br>        1120,<br>        -144<br>      ],<br>      &quot;id&quot;: &quot;6ab02ea4-8319-4ceb-907a-996a410bcf27&quot;,<br>      &quot;name&quot;: &quot;Send an Email&quot;<br>    }<br>  ],<br>  &quot;pinData&quot;: {},<br>  &quot;connections&quot;: {<br>    &quot;Webhook&quot;: {<br>      &quot;main&quot;: [<br>        [<br>          {<br>            &quot;node&quot;: &quot;Code in JavaScript&quot;,<br>            &quot;type&quot;: &quot;main&quot;,<br>            &quot;index&quot;: 0<br>          }<br>        ]<br>      ]<br>    },<br>    &quot;Code in JavaScript&quot;: {<br>      &quot;main&quot;: [<br>        [<br>          {<br>            &quot;node&quot;: &quot;HTTP Request&quot;,<br>            &quot;type&quot;: &quot;main&quot;,<br>            &quot;index&quot;: 0<br>          }<br>        ]<br>      ]<br>    },<br>    &quot;HTTP Request&quot;: {<br>      &quot;main&quot;: [<br>        [<br>          {<br>            &quot;node&quot;: &quot;HTTP Request1&quot;,<br>            &quot;type&quot;: &quot;main&quot;,<br>            &quot;index&quot;: 0<br>          }<br>        ]<br>      ]<br>    },<br>    &quot;HTTP Request1&quot;: {<br>      &quot;main&quot;: [<br>        [<br>          {<br>            &quot;node&quot;: &quot;Code in JavaScript1&quot;,<br>            &quot;type&quot;: &quot;main&quot;,<br>            &quot;index&quot;: 0<br>          }<br>        ]<br>      ]<br>    },<br>    &quot;Code in JavaScript1&quot;: {<br>      &quot;main&quot;: [<br>        [<br>          {<br>            &quot;node&quot;: &quot;Send an Email&quot;,<br>            &quot;type&quot;: &quot;main&quot;,<br>            &quot;index&quot;: 0<br>          }<br>        ]<br>      ]<br>    }<br>  },<br>  &quot;active&quot;: false,<br>  &quot;settings&quot;: {<br>    &quot;executionOrder&quot;: &quot;v1&quot;,<br>    &quot;binaryMode&quot;: &quot;separate&quot;<br>  },<br>  &quot;meta&quot;: {<br>    &quot;templateCredsSetupCompleted&quot;: false<br>  },<br>  &quot;nodeGroups&quot;: [],<br>  &quot;tags&quot;: []<br>}</pre><p><strong>Instructions to run this code and get the workflow:</strong></p><p>To import the workflow directly into n8n using the JSON code, choose either of the two standard methods below:</p><h3>Method 1: Copy and Paste Directly onto the Canvas (Fastest)</h3><ol><li><strong>Copy the Code</strong>: Select and copy the entire sanitized JSON block above (Ctrl + C or Cmd + C).</li><li><strong>Open n8n</strong>: Go to your n8n dashboard and click <strong>Create Workflow</strong> (or open a blank workflow canvas).</li><li><strong>Paste onto Canvas</strong>: Click once anywhere on the blank grey grid canvas, then press Ctrl + V (Windows) or Cmd + V (Mac).</li><li><strong>Result</strong>: All 6 nodes and their connections will instantly appear on your screen.</li></ol><h3>Method 2: Import via the Menu</h3><ol><li><strong>Save the File</strong>: Copy the sanitized JSON code, paste it into a text editor (Notepad, VS Code), and save it as wazuh-ioc-enrichment.json.</li><li><strong>Open n8n</strong>: Open a new or blank workflow in n8n.</li><li><strong>Open the Menu</strong>: Click the <strong>three dots (</strong>...<strong>)</strong> in the top-right or top-left area near your workflow name.</li><li><strong>Import</strong>: Select <strong>Import from File</strong> (or <strong>Import from URL / Clipboard</strong>).</li><li><strong>Select File</strong>: Choose the wazuh-ioc-enrichment.json file you saved.</li></ol><h3>Post-Import Configuration (Required Steps)</h3><p>Because the JSON was sanitized for security, update these 3 nodes before running:</p><ul><li><strong>AbuseIPDB Node (</strong>HTTP Request<strong>)</strong>:</li><li>Open the node $\rightarrow$ expand <strong>Send Headers</strong> $\rightarrow$ replace YOUR_ABUSEIPDB_API_KEY with your actual AbuseIPDB API key.</li><li><strong>VirusTotal Node (</strong>HTTP Request1<strong>)</strong>:</li><li>Open the node expand <strong>Send Headers</strong> replace YOUR_VIRUSTOTAL_API_KEY with your actual VirusTotal API key.</li></ul><p><strong>. Email Node (</strong>Send an Email<strong>)</strong>:</p><ul><li>Open the node $\rightarrow$ under <strong>Credential to connect with</strong>, select your configured <strong>SMTP account</strong>.</li><li>Set <strong>From Email</strong> to your sender Gmail address and <strong>To Email</strong> to your recipient address.</li></ul><h3>Summary</h3><p>By orchestrating Wazuh alerts through n8n with AbuseIPDB and VirusTotal enrichment, SOC teams can eliminate manual indicator lookups, prioritize true-positive security events faster, and reduce alert fatigue through structured, contextual reporting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=795732689a0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom SOC Dashboard: Integrating Grafana with Wazuh (OpenSearch)]]></title>
            <link>https://medium.com/@usmannazir5503/building-a-custom-soc-dashboard-integrating-grafana-with-wazuh-opensearch-37711ff0e1f9?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/37711ff0e1f9</guid>
            <category><![CDATA[opensearchj]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[wazuh]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 05:52:43 GMT</pubDate>
            <atom:updated>2026-08-15T05:52:43.286Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Security Operations Center (SOC) environments, real-time visibility into security telemetry is critical. While the native Wazuh dashboard offers strong built-in monitoring capabilities, integrating Wazuh with <strong>Grafana</strong> unlocks advanced visualization possibilities, custom alerting pipelines, and multi-source correlation within a single pane of glass.</p><p>In this guide, we will walk through the complete step-by-step implementation of connecting Grafana to a Wazuh SIEM deployment (via the Wazuh OpenSearch Indexer), troubleshooting network socket bindings, and building real-time SOC monitoring panels.</p><h3>1. Architecture Overview</h3><p>To understand the integration flow, let’s look at how the components interact:</p><ul><li><strong>Wazuh Manager:</strong> Collects, decodes, and analyzes telemetry and logs forwarded by Wazuh agents across endpoints.</li><li><strong>Wazuh Indexer (OpenSearch Engine):</strong> Stores analyzed security alerts and telemetry inside the wazuh-alerts-* index on port 9200.</li><li><strong>Grafana Server:</strong> Queries the OpenSearch index via HTTPS and renders custom SOC metrics and dashboards in real time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NhCrLZCFGbcU6S6vH37sg.png" /><figcaption><strong>Workflow Diagram</strong></figcaption></figure><h3>2. Prerequisites</h3><p>Before starting, ensure you have:</p><ul><li>A functional <strong>Wazuh</strong> installation (All-in-One OVA or distributed cluster).</li><li>A machine running <strong>Grafana</strong> (Linux VM, container, or host environment).</li><li>Network reachability between the Grafana host and the Wazuh Indexer on port 9200.</li></ul><h3>3. Step 1: Install and Start Grafana</h3><p>If Grafana is not yet installed on your monitoring host (e.g., Debian/Ubuntu/Kali), install it via the official repository:</p><p>Bash</p><pre># 1. Install prerequisites<br>sudo apt-get install -y apt-transport-https software-properties-common wget<br># 2. Add Grafana GPG key<br>sudo mkdir -p /etc/apt/keyrings/<br>wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/grafana.gpg &gt; /dev/null<br># 3. Add Grafana stable repository<br>echo &quot;deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main&quot; | sudo tee -a /etc/apt/sources.list.d/grafana.list<br># 4. Update and install<br>sudo apt-get update<br>sudo apt-get install -y grafana</pre><p>Start and enable the Grafana system daemon:</p><p>Bash</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable grafana-server<br>sudo systemctl start grafana-server<br>sudo systemctl status grafana-server</pre><p>Confirm that the service is running and accessible via browser at http://localhost:3000 (Default credentials: admin / admin).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgWJGwE_Jg_a9rN3LuKa5g.jpeg" /><figcaption><strong>Grafana Running</strong></figcaption></figure><h3>4. Step 2: Configure Wazuh Indexer Network Binding</h3><p>By default, the Wazuh Indexer binds strictly to the loopback interface (127.0.0.1:9200), rejecting external queries. To allow Grafana to fetch logs, update the binding configuration.</p><h3>1. Edit opensearch.yml</h3><p>On your Wazuh server, open the configuration file:</p><p>Bash</p><pre>sudo nano /etc/wazuh-indexer/opensearch.yml</pre><p>Find the network.host directive and modify it:</p><p>YAML</p><pre>network.host: &quot;0.0.0.0&quot;</pre><p>Save and exit (Ctrl + O, Enter, then Ctrl + X).</p><h3>2. Restart &amp; Verify</h3><p>Restart the indexer service and verify that it is listening across all network interfaces:</p><p>Bash</p><pre>sudo systemctl restart wazuh-indexer<br>sudo ss -tulpn | grep 9200</pre><p><em>Expected output:</em></p><p>Plaintext</p><pre>tcp  LISTEN  0  4096  *:9200  *:*  users:((&quot;java&quot;,pid=...,fd=...))</pre><h3>3. Verify Remote Connectivity</h3><p>From your Grafana host, test access using curl:</p><p>Bash</p><pre>curl -k -u admin:&lt;YOUR_PASSWORD&gt; https://&lt;WAZUH_IP&gt;:9200</pre><p>A JSON response containing &quot;cluster_name&quot;: &quot;wazuh-cluster&quot; confirms that the Indexer is accessible.</p><h3>5. Step 3: Add OpenSearch Data Source in Grafana</h3><ul><li>Log into your Grafana web interface (http://&lt;GRAFANA_IP&gt;:3000).</li><li>Navigate to <strong>Connections</strong> $\rightarrow$ <strong>Data sources</strong> $\rightarrow$ <strong>Add data source</strong>.</li><li>Select <strong>OpenSearch</strong>.</li><li>Configure the parameters:</li></ul><p><strong>Configuration FieldValue / SettingNotesURL</strong>https://&lt;WAZUH_INDEXER_IP&gt;:9200HTTPS protocol is mandatory<strong>Basic authEnabled</strong>Required for authenticated Indexer access<strong>User / Password</strong>admin / &lt;Wazuh_Indexer_Password&gt;Wazuh Indexer credentials<strong>Skip TLS VerifyEnabled</strong>Bypasses self-signed certificate warnings<strong>Index name</strong>wazuh-alerts-*</p><p>Targets active Wazuh alert indices</p><p><strong>Time field name</strong>timestamp</p><p>Wazuh uses timestamp (without @)</p><p><strong>Version</strong>OpenSearch (compatibility mode) / 2.x.xMatches the OpenSearch version</p><ul><li>Click <strong>Save &amp; test</strong>.</li><li>A green banner stating <strong>Index OK. Time field name OK.</strong> confirms a successful connection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd5v9wj0N_cBuRG8hFKTdg.jpeg" /><figcaption>Opensearch Integrated</figcaption></figure><h3>6. Step 4: Build SOC Security Visualizations</h3><p>With the data source active, create a new dashboard (<strong>Dashboards</strong> $\rightarrow$ <strong>New</strong> $\rightarrow$ <strong>New Dashboard</strong>) and add the following monitoring panels:</p><h3>Panel 1: Security Alerts Over Time (Event Trends)</h3><ul><li><strong>Visualization:</strong> Time Series / Bar Chart</li><li><strong>Query Type:</strong> Lucene</li><li><strong>Metric:</strong> Count</li><li><strong>Group By:</strong> Date Histogram $\rightarrow$ Field: timestamp</li><li><strong>Purpose:</strong> Visualizes event velocity, traffic patterns, and sudden anomalous security spikes.</li></ul><h3>Panel 2: Alerts by Severity Level</h3><ul><li><strong>Visualization:</strong> Donut / Pie Chart</li><li><strong>Query Type:</strong> Lucene</li><li><strong>Metric:</strong> Count</li><li><strong>Group By:</strong> Terms $\rightarrow$ Field: rule.level</li><li><strong>Purpose:</strong> Classifies incoming alerts across low, medium, high, and critical threat levels to prioritize triage.</li></ul><h3>Panel 3: Top Triggered Security Rules</h3><ul><li><strong>Visualization:</strong> Horizontal Bar Chart or Table</li><li><strong>Query Type:</strong> Lucene</li><li><strong>Metric:</strong> Count</li><li><strong>Group By:</strong> Terms $\rightarrow$ Field: rule.description</li><li><strong>Size:</strong> 10</li><li><strong>Purpose:</strong> Highlights the most frequently firing detection signatures and potential recurring attack patterns.</li></ul><h3>Panel 4: Active Agent Telemetry Distribution</h3><ul><li><strong>Visualization:</strong> Table / Stat Panel</li><li><strong>Query Type:</strong> Lucene</li><li><strong>Metric:</strong> Count</li><li><strong>Group By:</strong> Terms $\rightarrow$ Field: agent.name</li><li><strong>Purpose:</strong> Tracks monitored endpoints and monitors agent reporting health.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16Q3PypgnC57--NsuvgXmw.jpeg" /><figcaption><strong>How the Dashboard Will Look</strong></figcaption></figure><h3>7. Step 5: Data Validation &amp; Verification</h3><p>To validate dashboard accuracy:</p><ul><li><strong>Time-Window Alignment:</strong> Match the timeframe in Grafana (e.g., <em>Last 24 hours</em>) with the native Wazuh Dashboard.</li><li><strong>Count Correlation:</strong> Verify that total alert metrics and rule distribution numbers match between both interfaces.</li><li><strong>Live Alert Ingestion:</strong> Trigger an event on a monitored endpoint (such as an authentication failure) and verify that the event appears on the Grafana dashboard panels within seconds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POhbELKYuaSXSMajHjjQng.jpeg" /><figcaption><strong>Last 15 minutes alerts in Wazuh Dashboard</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Wx3QdKysR-LeH0Aphsy1wQ.jpeg" /><figcaption><strong>Last 15 minutes alerts in Grafana</strong></figcaption></figure><h3>8. Summary</h3><p>Integrating Grafana with Wazuh creates a responsive, flexible SOC monitoring setup. By querying OpenSearch directly, security analysts can design customized visualization panels, build tailored reporting views, and aggregate security telemetry efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37711ff0e1f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Phishing Detection System and Browser History Monitoring with Wazuh SIEM & Windows…]]></title>
            <link>https://medium.com/@usmannazir5503/building-a-phishing-detection-system-and-browser-history-monitoring-with-wazuh-siem-windows-75ddfa1700f9?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ddfa1700f9</guid>
            <category><![CDATA[track-browser-history]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[power]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 00:21:50 GMT</pubDate>
            <atom:updated>2026-09-08T10:51:47.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Phishing Detection System and Browser History Monitoring with Wazuh SIEM &amp; Windows Telemetry</h3><h3>Building a Privacy-First Phishing Detection System with Wazuh SIEM &amp; Windows Telemetry</h3><p>Phishing remains one of the most persistent attack vectors in modern cybersecurity. While enterprise email security gateways catch a lot of bad traffic, monitoring what happens at the endpoint when a user actually interacts with a link or receives a malicious payload is where Security Operations Centers (SOCs) win or lose.</p><p>In this guide, we will walk through building a complete, locally hosted phishing detection pipeline. We’ll extract browser telemetry and email events from a Windows endpoint, structure the data using custom PowerShell pipelines, and ingest it into <strong>Wazuh SIEM</strong> to trigger real-time, correlated alerts.</p><h3>1. System Architecture Overview</h3><p>Before diving into the configuration, here is how the data flows through our setup:</p><ul><li><strong>Windows Endpoint (Agent):</strong> Runs a custom PowerShell script (export-chrome-history.ps1) that extracts Chrome browser history and writes structured JSON logs to C:\wazuh-scripts\chrome_history.log. It also logs inbound simulated email events to mail_events.log.</li><li><strong>Wazuh Agent:</strong> Monitors these JSON log files in real-time and forwards events to the SIEM manager over an encrypted channel.</li><li><strong>Wazuh Server (Manager):</strong> Receives the raw JSON, parses fields using the standard json decoder, and evaluates events against custom detection rules in local_rules.xml.</li><li><strong>Wazuh Dashboard:</strong> Visualizes incoming alerts (from baseline event logging to Level 15 correlated phishing detections).</li></ul><h3>2. Endpoint Configuration (Windows Agent)</h3><h3>Step 1: Set Up Scripting Directory &amp; Extraction</h3><p>On the Windows endpoint, create a dedicated folder at C:\wazuh-scripts\. Place your PowerShell browser history extraction script inside this folder.</p><h3>Create the PowerShell export script</h3><p>On the Windows endpoint, create the folder C:\wazuh-scripts and save the following script as C:\wazuh-scripts\export-chrome-history.ps1. It copies the locked History file, reads it with the SQLite CLI, converts Chrome’s timestamp format to normal date/time, and appends new rows to a plain-text log that Wazuh will monitor.</p><p>Powershell Script</p><pre>monitor.<br># export-chrome-history.ps1<br>$ChromeHistory = &quot;$env:LOCALAPPDATA\Google\Chrome\User Data\Default\History&quot;<br>$TempCopy      = &quot;C:\wazuh-scripts\History_copy.db&quot;<br>$OutputLog     = &quot;C:\wazuh-scripts\chrome_history.log&quot;<br>$SqliteExe     = &quot;C:\wazuh-scripts\sqlite3.exe&quot;<br> <br>Copy-Item -Path $ChromeHistory -Destination $TempCopy -Force<br> <br>$Query = @&quot;<br>SELECT urls.url, urls.title, urls.visit_count,<br>       datetime(urls.last_visit_time/1000000-11644473600,&#39;unixepoch&#39;,&#39;localtime&#39;)<br>FROM urls ORDER BY urls.last_visit_time DESC LIMIT 50;<br>&quot;@<br> <br>$Rows = &amp; $SqliteExe $TempCopy $Query<br>foreach ($Row in $Rows) {<br>    $Fields = $Row -split &#39;\|&#39;<br>    $Entry = [PSCustomObject]@{<br>        timestamp  = $Fields[3]<br>        url        = $Fields[0]<br>        title      = $Fields[1]<br>        visitCount = $Fields[2]<br>        host       = ([uri]$Fields[0]).Host<br>        user       = $env:USERNAME<br>    }<br>    $Entry | ConvertTo-Json -Compress | Out-File -Append -Encoding utf8 $OutputLog<br>}<br></pre><p><strong><em>Ensure:</em></strong></p><p><strong><em>Download the sqlite3.exe command-line tool from sqlite.org and place it at C:\wazuh-scripts\sqlite3.exe (referenced by the script above).</em></strong></p><p>To test the script manually and ensure JSON formatting works:</p><p>PowerShell</p><pre>powershell.exe -ExecutionPolicy Bypass -File &quot;C:\wazuh-scripts\export-chrome-history.ps1&quot;</pre><p>Verify that C:\wazuh-scripts\chrome_history.log contains structured JSON output similar to this:</p><p>JSON</p><pre>{&quot;timestamp&quot;:&quot;2026-08-13T10:12:03&quot;,&quot;url&quot;:&quot;https://example.com&quot;,&quot;title&quot;:&quot;Example&quot;,&quot;visitCount&quot;:&quot;1&quot;,&quot;host&quot;:&quot;example.com&quot;,&quot;user&quot;:&quot;Usman&quot;}</pre><blockquote><strong><em>📸 PROOF / SCREENSHOT 1:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ru53gcCx1pPO1FOdECt6nQ.jpeg" /><figcaption>Terminal execution of <em>export-chrome-history.ps1</em> in Administrative PowerShell showing successful JSON log generation in <em>C:\wazuh-scripts\</em>.</figcaption></figure><h3>Schedule the script to run periodically</h3><p>Use Windows Task Scheduler so the log is refreshed automatically:</p><p><strong>1. Open Task Scheduler </strong>→ Create Task.</p><p><strong>2. General tab:</strong> Name it “Chrome History Export”; select “Run whether user is logged on or not”.</p><p><strong>3. Triggers tab:</strong> New → Begin the task “On a schedule” → Repeat task every 5 minutes, indefinitely.</p><p><strong>4. Actions tab: </strong>New → Program/script: powershell.exe →</p><p><strong>Arguments:</strong> -ExecutionPolicy Bypass -File “C:\wazuh-scripts\export-chrome-history.ps1”.</p><p>5. Save the task, supplying the local admin credentials when prompted.</p><h3>Step 2: Configure the Wazuh Agent</h3><p>Open the agent configuration file located at C:\Program Files (x86)\ossec-agent\ossec.conf and add the custom localfile ingestion blocks under &lt;ossec_config&gt;:</p><p>XML</p><pre>&lt;localfile&gt;<br>  &lt;log_format&gt;json&lt;/log_format&gt;<br>  &lt;location&gt;C:\wazuh-scripts\chrome_history.log&lt;/location&gt;<br>&lt;/localfile&gt;<br>&lt;localfile&gt;<br>  &lt;log_format&gt;json&lt;/log_format&gt;<br>  &lt;location&gt;C:\wazuh-scripts\mail_events.log&lt;/location&gt;<br>&lt;/localfile&gt;</pre><p>Restart the agent service using PowerShell to apply changes:</p><p>PowerShell</p><pre>Restart-Service -Name WazuhSvc</pre><blockquote><strong><em>📸 PROOF / SCREENSHOT 2:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUcan4Gw7Gt2wOc48TL3Sw.jpeg" /><figcaption>PowerShell service status confirming <em>WazuhSvc</em> is active.</figcaption></figure><h3>3. SIEM Detection Engine Setup (Wazuh Manager)</h3><p>Now, let’s configure the Wazuh Manager on Linux to detect suspicious browser navigation and inbound phishing emails.</p><h3>Custom Rule Logic (local_rules.xml)</h3><p>Open /var/ossec/etc/rules/local_rules.xml on the manager and replace or append the following rule group:</p><p>XML</p><pre>&lt;group name=&quot;phishing,browser_history,&quot;&gt;<br>&lt;!-- Base rule: Chrome browsing history event --&gt;<br>  &lt;rule id=&quot;100100&quot; level=&quot;3&quot;&gt;<br>    &lt;decoded_as&gt;json&lt;/decoded_as&gt;<br>    &lt;match&gt;&quot;url&quot;:&lt;/match&gt;<br>    &lt;description&gt;Chrome browsing history event recorded&lt;/description&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Visited a domain present on phishing list --&gt;<br>  &lt;rule id=&quot;100101&quot; level=&quot;12&quot;&gt;<br>    &lt;if_sid&gt;100100&lt;/if_sid&gt;<br>    &lt;match&gt;phishing-test.com|secure-login-update.net&lt;/match&gt;<br>    &lt;description&gt;Suspicious/known-bad domain visited&lt;/description&gt;<br>    &lt;group&gt;phishing_domain_visit,&lt;/group&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- URL shortener visited --&gt;<br>  &lt;rule id=&quot;100102&quot; level=&quot;7&quot;&gt;<br>    &lt;if_sid&gt;100100&lt;/if_sid&gt;<br>    &lt;match&gt;bit.ly|tinyurl.com|goo.gl|t.co&lt;/match&gt;<br>    &lt;description&gt;User visited a URL-shortener link&lt;/description&gt;<br>    &lt;group&gt;suspicious_url,&lt;/group&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Base rule: Mail event --&gt;<br>  &lt;rule id=&quot;100110&quot; level=&quot;3&quot;&gt;<br>    &lt;decoded_as&gt;json&lt;/decoded_as&gt;<br>    &lt;match&gt;&quot;subject&quot;:&lt;/match&gt;<br>    &lt;description&gt;Inbound mail event recorded&lt;/description&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Phishing email subject keywords --&gt;<br>  &lt;rule id=&quot;100111&quot; level=&quot;10&quot;&gt;<br>    &lt;if_sid&gt;100110&lt;/if_sid&gt;<br>    &lt;match&gt;verify|suspend|password|expire|urgent|confirm&lt;/match&gt;<br>    &lt;description&gt;Possible phishing email subject detected&lt;/description&gt;<br>    &lt;group&gt;phishing_email,&lt;/group&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Sender domain matches known bad pattern --&gt;<br>  &lt;rule id=&quot;100112&quot; level=&quot;13&quot;&gt;<br>    &lt;if_sid&gt;100110&lt;/if_sid&gt;<br>    &lt;match&gt;secure-login-update.net|phishing-test.com&lt;/match&gt;<br>    &lt;description&gt;Email received from a listed phishing domain&lt;/description&gt;<br>    &lt;group&gt;phishing_email,phishing_domain_sender,&lt;/group&gt;<br>  &lt;/rule&gt;<br>  &lt;!-- Correlated phishing indicator --&gt;<br>  &lt;rule id=&quot;100120&quot; level=&quot;15&quot; frequency=&quot;2&quot; timeframe=&quot;3600&quot;&gt;<br>    &lt;if_matched_sid&gt;100101&lt;/if_matched_sid&gt;<br>    &lt;if_sid&gt;100111,100112&lt;/if_sid&gt;<br>    &lt;description&gt;Correlated phishing indicator: user received AND visited a suspicious link&lt;/description&gt;<br>    &lt;group&gt;phishing_confirmed,&lt;/group&gt;<br>  &lt;/rule&gt;<br>&lt;/group&gt;</pre><blockquote><strong><em>📸 PROOF / SCREENSHOT 3:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3NxixfniGZZam5L4fLuIw.jpeg" /><figcaption>Terminal view of GNU nano editing <em>/var/ossec/etc/rules/local_rules.xml</em> showing rules 100100 through 100120 cleanly defined.</figcaption></figure><h3>Validate and Restart</h3><ul><li>Test the syntax to ensure there are no XML formatting errors:</li><li>Bash</li></ul><pre>sudo /var/ossec/bin/wazuh-analysisd -t</pre><ul><li>Restart the Wazuh Manager service:</li><li>Bash</li></ul><pre>sudo systemctl restart wazuh-manager</pre><h3>4. Validating Rules with wazuh-logtest</h3><p>Before running live endpoint tests, verify that the manager correctly decodes raw JSON logs:</p><p>Bash</p><pre>sudo /var/ossec/bin/wazuh-logtest</pre><p>Paste a sample simulated email event line:</p><p>JSON</p><pre>{&quot;timestamp&quot;:&quot;2026-08-13T10:12:03&quot;,&quot;sender&quot;:&quot;support@secure-login-update.net&quot;,&quot;subject&quot;:&quot;Your account will be suspended - verify now&quot;,&quot;recipient&quot;:&quot;user@company.com&quot;,&quot;link&quot;:&quot;http://secure-login-update.net/verify&quot;}</pre><blockquote><strong><em>📸 PROOF / SCREENSHOT 5:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhSwqKbSokOKJzre3P1PMg.jpeg" /><figcaption>Output of <em>wazuh-logtest</em> showing Phase 1 (Pre-decoding), Phase 2 (JSON Decoding), and Phase 3 (Filtering triggered for Rules 100110, 100111, and 100112).</figcaption></figure><h3>5. Simulating Real-World Phishing Scenarios</h3><p>To prove effectiveness, execute these test scenarios on the Windows host:</p><h3>Scenario A: Visiting a Suspicious Domain</h3><p>Visit [http://phishing-test.com](http://phishing-test.com) in Chrome and trigger the export script.</p><ul><li><strong>Result:</strong> Fires <strong>Rule 100101</strong> (Level 12 alert).</li></ul><h3>Scenario B: Inbound Phishing Email Simulation</h3><p>Append a simulated phishing email to mail_events.log:</p><p>PowerShell</p><pre>&#39;{&quot;timestamp&quot;:&quot;2026-08-13T10:15:00&quot;,&quot;sender&quot;:&quot;support@secure-login-update.net&quot;,&quot;subject&quot;:&quot;Your account will be suspended - verify now&quot;,&quot;recipient&quot;:&quot;user@company.com&quot;,&quot;link&quot;:&quot;http://secure-login-update.net/verify&quot;}&#39; | Out-File -Append -Encoding utf8 C:\wazuh-scripts\mail_events.log</pre><ul><li><strong>Result:</strong> Fires <strong>Rule 100111</strong> (Subject keywords, Level 10) and <strong>Rule 100112</strong> (Bad sender domain, Level 13).</li></ul><h3>Scenario C: Multi-Vector Correlation Escalation</h3><p>When both Scenario A and Scenario B occur within a 1-hour window, Rule <strong>100120</strong> triggers automatically.</p><ul><li><strong>Result:</strong> Fires <strong>Rule 100120</strong> (Level 15 Critical Alert) indicating a confirmed user click-through on an inbound phishing link.</li></ul><blockquote><strong><em>📸 PROOF / SCREENSHOT 6:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwAAJGXm5bojhtER0r-I4w.jpeg" /><figcaption>Wazuh Dashboard Discover view (<em>wazuh-alerts-*</em>) showing real-time alerts for Rule 100101, Rule 100111, Rule 100112, and correlated Rule 100120.</figcaption></figure><h3>Key Technical Takeaways</h3><ul><li><strong>Standard JSON Decoder Mapping:</strong> Using &lt;match&gt; tags inside custom rules avoids complex dynamic schema mismatches while maintaining fast, reliable event parsing.</li><li><strong>Correlation Rules:</strong> Combining email ingestion with browser history monitoring enables SOC teams to automatically escalate priority when a user actually clicks a malicious link.</li><li><strong>Privacy-First Telemetry:</strong> Local log parsing ensures endpoint monitoring takes place within your owned infrastructure without third-party data reliance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ddfa1700f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an SSH Honeypot with Cowrie and Ingesting Logs into Wazuh SIEM]]></title>
            <link>https://medium.com/@usmannazir5503/building-an-ssh-honeypot-with-cowrie-and-ingesting-logs-into-wazuh-siem-4aa2129eb222?source=rss-b2b1ff46958f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa2129eb222</guid>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[honeypot]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cowrie]]></category>
            <category><![CDATA[soc-analyst]]></category>
            <dc:creator><![CDATA[Muhammad Usman]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 21:05:29 GMT</pubDate>
            <atom:updated>2026-07-20T21:07:21.075Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Executive Summary &amp; Lab Architecture</h3><h3>1.1 Overview</h3><p>This lab demonstrates the end-to-end deployment, network integration, and SIEM monitoring of an SSH/Telnet Honeypot (<strong>Cowrie</strong>) connected to a <strong>Wazuh</strong> Security Information and Event Management (SIEM) platform.</p><p>By deploying a decoy service on standard authentication ports, a Security Operations Center (SOC) team can detect unauthorized network scanning, log credential brute-force attempts, and capture post-exploitation commands executed by attackers in a safe, controlled sandbox environment.</p><h3>1.2 Environment &amp; Lab Specifications</h3><p>● <strong>SIEM Platform:</strong> Wazuh Manager &amp; Dashboard (Version 4.x)</p><p>● <strong>Wazuh Manager Server IP:</strong> 10.111.xxx.xxx</p><p>● <strong>Honeypot OS:</strong> Kali Linux (Rolling Release)</p><p>● <strong>Honeypot IP Address:</strong> 10.111.xxx.xxx (Configured with Bridged Network Adapter)</p><p>● <strong>Honeypot Software:</strong> Cowrie SSH/Telnet Honeypot</p><p>● <strong>Attacker Simulation Host:</strong> External Windows Machine (10.111.23x.x)</p><h3>2. Exhaustive Step-by-Step Implementation</h3><h3>Step 1: Network &amp; Dependency Preparation</h3><p>Before installing the honeypot software, the underlying host operating system (Kali Linux) required package repository re-indexing and core Python/build tools.</p><p>1. <strong>Fixing Network DNS &amp; Repository Mirrors:</strong> To resolve initial APT mirror timeout errors (Temporary failure resolving ‘http.kali.org’), public DNS resolvers were added to /etc/resolv.conf:</p><pre>echo -e &quot;nameserver 1.1.1.1\nnameserver 8.8.8.8&quot; | sudo tee /etc/resolv.conf</pre><p>The APT repository source was updated to pull directly from the primary archive:</p><pre>echo &quot;deb http://archive.kali.org/kali kali-rolling main non-free contrib&quot; | sudo tee /etc/apt/sources.list</pre><p>2. <strong>Package Installation:</strong> The system package cache was cleared (apt clean), updated (apt update), and the necessary build tools and Python development libraries were downloaded:</p><pre>sudo apt install git python3-virtualenv libssl-dev libffi-dev build-essential libpython3-dev python3-minimal authbind -y</pre><p>○ <strong>git</strong>: Used to clone the Cowrie source code repository from GitHub.</p><p>○ <strong>python3-virtualenv</strong>: Creates isolated Python execution environments to avoid breaking global system packages.</p><p>○ <strong>libssl-dev / libffi-dev</strong>: C libraries required to compile cryptographic Python modules (OpenSSL/Cryptography).</p><p>○ <strong>authbind</strong>: Allows non-root users to bind to low-numbered privileged sockets if needed.</p><h3>Step 2: Creating an Isolated Non-Root User</h3><p>Running a honeypot as root is a critical security vulnerability because any remote code execution vulnerability in the honeypot code could lead to full host compromise.</p><ol><li><strong>User Creation Command:</strong></li></ol><pre>sudo adduser - disabled-password - gecos &quot;&quot; cowrie</pre><p>○ <strong>— disabled-password</strong>: Prevents password-based interactive logins from external actors into this account.</p><p>○ <strong>— gecos “”</strong>: Suppresses extra prompt requests for system user details (e.g., Room Number, Work Phone).</p><p>○ <strong>Result:</strong> Creates the restricted service user cowrie along with its home directory /home/cowrie.</p><h3>Step 3: Rebinding Real SSH Daemon &amp; Setting Up Port Forwarding</h3><p>By default, legitimate SSH runs on TCP port 22. Because Cowrie must listen on port 22 to catch incoming attacker connections, the true administrative SSH service was moved to a secondary port.</p><ol><li><strong>Rebinding Host SSH:</strong> Opened the OpenSSH server configuration file:</li></ol><pre>sudo nano /etc/ssh/sshd_config</pre><p>Modified the directive:</p><p>Port 22222</p><p>Restarted the legitimate SSH service to apply changes:</p><pre>sudo systemctl restart ssh</pre><p>2. <strong>Configuring NAT Port Forwarding:</strong> Cowrie naturally runs on unprivileged port 2222. Using Linux iptables, network traffic arriving on the default SSH port (22) was silently forwarded to Cowrie’s port (2222):</p><pre>sudo iptables -t nat -A PREROUTING -p tcp - dport 22 -j REDIRECT - to-port 2222</pre><h3>Step 4: Cowrie Source Downloading &amp; Virtual Environment Setup</h3><ol><li><strong>Switched to the cowrie user account:</strong></li></ol><pre>sudo su - cowrie</pre><p>2. <strong>Cloned the repository:</strong></p><pre>git clone https://github.com/cowrie/cowrie.git<br> cd cowrie</pre><p>3. <strong>Built the Python Environment:</strong> Created a standalone virtual environment named cowrie-env and activated it:</p><pre>python3 -m venv cowrie-env<br> source cowrie-env/bin/activate</pre><p>4. <strong>Installed Cowrie Python Modules:</strong> Upgraded pip and installed required modules defined in requirements.txt:</p><pre>pip install - upgrade pip<br> pip install -r requirements.txt<br> pip install -e .</pre><p><em>(The pip install -e . command compiles and places the cowrie control binary directly into cowrie-env/bin/cowrie).</em></p><p>5. <strong>Starting Cowrie:</strong> Started the honeypot and verified its execution state:</p><pre>cowrie start<br> cowrie status</pre><p><em>Output confirmed:</em> cowrie is running (PID: 15864).</p><h3>Step 5: Integrating Cowrie Logs with Wazuh Agent</h3><p>Cowrie writes real-time structured attack logs to <strong>/home/cowrie/cowrie/var/log/cowrie/cowrie.json.</strong></p><ol><li><strong>Installed Wazuh Agent on Honeypot Host:</strong> Exited back to the root account and added the official Wazuh package repository:</li></ol><pre>curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | gpg - no-default-keyring - keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg - import &amp;&amp; chmod 644 /usr/share/keyrings/wazuh.gpg<br> echo &quot;deb [signed-by=/usr/share/keyrings/wazuh.gpg] https://packages.wazuh.com/4.x/apt/ stable main&quot; | tee /etc/apt/sources.list.d/wazuh.list<br> apt update<br> WAZUH_MANAGER=&#39;&lt;wazuh-manager-ip&gt;&#39; apt-get install wazuh-agent -y</pre><p>2. <strong>Directory Permission Adjustments:</strong> Ensured the wazuh-agent daemon had directory traversal and read permissions over Cowrie’s log path:</p><pre>chmod 755 /home/cowrie /home/cowrie/cowrie /home/cowrie/cowrie/var /home/cowrie/cowrie/var/log /home/cowrie/cowrie/var/log/cowrie</pre><p>3. <strong>Configured ossec.conf:</strong> Opened /var/ossec/etc/ossec.conf and added the JSON log collection block right above &lt;/ossec_config&gt;:</p><pre>&lt;localfile&gt;<br> &lt;log_format&gt;json&lt;/log_format&gt;<br> &lt;location&gt;/home/cowrie/cowrie/var/log/cowrie/cowrie.json&lt;/location&gt;<br> &lt;/localfile&gt;</pre><p>4. <strong>Restarted the Wazuh Agent:</strong></p><pre>systemctl restart wazuh-agent</pre><h3>Step 6: Custom Decoder &amp; Rule Definition on Wazuh Manager</h3><p>To turn ingested JSON logs into actionable alerts on the Wazuh Dashboard, custom rules were added to the Manager.</p><ol><li><strong>Opened /var/ossec/etc/rules/local_rules.xml on the Wazuh Manager:</strong></li></ol><pre>sudo nano /var/ossec/etc/rules/local_rules.xml</pre><p>2. <strong>Inserted Custom Detection Rules:</strong></p><pre>&lt;group name=&quot;cowrie,&quot;&gt;<br> &lt;rule id=&quot;100200&quot; level=&quot;3&quot;&gt;<br> &lt;decoded_as&gt;json&lt;/decoded_as&gt;<br> &lt;field name=&quot;eventid&quot;&gt;^cowrie\.&lt;/field&gt;<br> &lt;description&gt;Cowrie Honeypot Event Received&lt;/description&gt;<br> &lt;/rule&gt;<br> <br> &lt;rule id=&quot;100201&quot; level=&quot;7&quot;&gt;<br> &lt;if_sid&gt;100200&lt;/if_sid&gt;<br> &lt;field name=&quot;eventid&quot;&gt;cowrie.login.failed&lt;/field&gt;<br> &lt;description&gt;Cowrie Honeypot: Failed login attempt for user &#39;$(user)&#39; with password &#39;$(password)&#39; from IP $(src_ip)&lt;/description&gt;<br> &lt;/rule&gt;<br> <br> &lt;rule id=&quot;100202&quot; level=&quot;10&quot;&gt;<br> &lt;if_sid&gt;100200&lt;/if_sid&gt;<br> &lt;field name=&quot;eventid&quot;&gt;cowrie.login.success&lt;/field&gt;<br> &lt;description&gt;Cowrie Honeypot: Successful login spoof for user &#39;$(user)&#39; with password &#39;$(password)&#39; from IP $(src_ip)&lt;/description&gt;<br> &lt;/rule&gt;<br> &lt;/group&gt;</pre><p>3. <strong>Validated &amp; Restarted Manager:</strong> Checked rule syntax (sudo /var/ossec/bin/wazuh-analysisd -t) and restarted the manager service:</p><pre>sudo systemctl restart wazuh-manager</pre><h3>Step 7: Attacker Simulation &amp; Verification</h3><p>From an external Windows host terminal, an unauthorized connection was initiated to simulate real-world probing:</p><ol><li><strong>SSH Attack Command:</strong></li></ol><pre>ssh fakeuser@10.111.234.162</pre><p>ssh fakeuser@10.111.234.162</p><p>2. <strong>Session Interaction:</strong> Accepted the key fingerprint and entered test credentials. Upon gaining access to Cowrie’s emulated Debian shell (fakeuser@svr04:~$), reconnaissance commands were executed:</p><pre>whoami<br> ls -la<br> uname -a</pre><h3>3. Evidence &amp; Screenshots Section</h3><p><strong>Screenshot 1:</strong></p><p><strong>Description:</strong> Terminal output on Kali Linux displaying cowrie status confirming that the honeypot process is active with a valid PID (PID: 15864).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*pnr8HbCrLr2j4TrCIZAsMA.jpeg" /></figure><p><strong>Screenshot 2:</strong></p><p><strong>Description:</strong> External Windows PowerShell terminal showing the completed SSH connection to 10.111.234.162 and command execution within Cowrie’s decoy prompt (fakeuser@svr04:~$).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__aUGrk8jRc9-OXm5yCCnQ.jpeg" /></figure><p><strong>Screenshot 3:</strong></p><p><strong>Description:</strong> Wazuh Dashboard <strong>Security Events</strong> view filtered by rule.groups: cowrie, showing real-time alerts generated for Rule ID 100201 and 100202.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-Ui-9VSWlEsRStk3uADOQ.jpeg" /></figure><p><strong>Screenshot 4:</strong></p><p><strong>Description:</strong> Expanded event details on the Wazuh Dashboard displaying extracted JSON fields including source IP, username (fakeuser), typed password, and session event IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr70oNCEgKxnbSMfYk-Vlg.jpeg" /></figure><h3>4. Attacker Activity &amp; Findings Analysis</h3><h3>Summary Table of Captured Metrics:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*vc4hS1mFcjdAnGLlTcOmOQ.jpeg" /></figure><h3>SOC Analyst Findings &amp; Conclusion</h3><p>1. <strong>Zero False Positives:</strong> Because honeypots do not host legitimate production services or business users, <strong>100% of traffic touching this system is malicious or unauthorized</strong>. This allows SOC teams to set high-severity alerts without noise.</p><p>2. <strong>Credential Capture:</strong> Ingesting structured cowrie.json events directly into Wazuh provides visibility into wordlists and password combinations currently being utilized by attackers in the wild.</p><p>3. <strong>Early Warning Threat Detection:</strong> Integrating honeypot logs into a central SIEM provides an immediate early-warning mechanism, allowing analysts to block offending source IPs at the firewall before production assets are targeted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa2129eb222" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>