From 2d4d56bf21068fdc61a1c5b98c94fd449cc05c92 Mon Sep 17 00:00:00 2001 From: Jonhnathan <26856693+w0rk3r@users.noreply.github.com> Date: Wed, 11 Feb 2026 15:26:05 -0300 Subject: [PATCH] [Rule Tuning] PowerShell Rules Revamp - 4 (#5698) * [Rule Tuning] PowerShell Rules Revamp - 4 * bump * Apply suggestion from @Mikaayenson Co-authored-by: Mika Ayenson, PhD * Update defense_evasion_posh_compressed.toml * update disclaimer --------- Co-authored-by: Mika Ayenson, PhD --- ...asion_disable_posh_scriptblocklogging.toml | 107 +++++++--- .../defense_evasion_posh_assembly_load.toml | 200 ++++++++---------- .../defense_evasion_posh_compressed.toml | 183 ++++++++-------- ...fense_evasion_posh_defender_tampering.toml | 147 ++++++++----- .../defense_evasion_posh_encryption.toml | 103 +++++++-- 5 files changed, 452 insertions(+), 288 deletions(-) diff --git a/rules/windows/defense_evasion_disable_posh_scriptblocklogging.toml b/rules/windows/defense_evasion_disable_posh_scriptblocklogging.toml index 44663919c..be0fc9188 100644 --- a/rules/windows/defense_evasion_disable_posh_scriptblocklogging.toml +++ b/rules/windows/defense_evasion_disable_posh_scriptblocklogging.toml @@ -2,13 +2,13 @@ creation_date = "2022/01/31" integration = ["endpoint", "windows", "m365_defender", "sentinel_one_cloud_funnel", "crowdstrike"] maturity = "production" -updated_date = "2025/08/28" +updated_date = "2026/02/09" [rule] author = ["Elastic"] description = """ -Identifies attempts to disable PowerShell Script Block Logging via registry modification. Attackers may disable this -logging to conceal their activities in the host and evade detection. +Detects registry changes that disable PowerShell Script Block Logging. Attackers may disable this logging to conceal +their activities in the host and evade detection. """ from = "now-9m" index = [ @@ -25,43 +25,77 @@ license = "Elastic License v2" name = "PowerShell Script Block Logging Disabled" note = """## Triage and analysis +> **Disclaimer**: +> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies. + ### Investigating PowerShell Script Block Logging Disabled -PowerShell is one of the main tools system administrators use for automation, report routines, and other tasks, making it available in various environments and creating an attractive way for attackers to execute code. +This alert indicates a registry modification that set `EnableScriptBlockLogging` to a disabled value (`registry.data.strings` of `0` or `0x00000000`). Disabling Script Block Logging reduces visibility into PowerShell execution and is commonly used to evade detection, especially when followed by script-driven activity. -PowerShell Script Block Logging is a feature of PowerShell that records the content of all script blocks that it processes, giving defenders visibility of PowerShell scripts and sequences of executed commands. +#### Key alert fields to review + +- `process.executable`: The process responsible for modifying the registry value. +- `registry.value`: The registry value name that was changed (`EnableScriptBlockLogging`). +- `registry.data.strings`: The new data indicating the setting was disabled. +- `registry.path`: The full registry path of the modified value. +- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping. +- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping. #### Possible investigation steps -- Identify the user account that performed the action and whether it should perform this kind of action. -- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures. -- Investigate other alerts associated with the user/host during the past 48 hours. -- Check whether it makes sense for the user to use PowerShell to complete tasks. -- Investigate if PowerShell scripts were run after logging was disabled. +- Establish the affected endpoint and time window: + - Use `host.name`, `host.id`, and `@timestamp` to identify the impacted endpoint and define a review window (include activity immediately before and after the change). + - Prioritize based on endpoint role and criticality (for example, servers and admin workstations). + +- Validate the registry change and its scope: + - Review `registry.path`, `registry.value`, and `registry.data.strings` to confirm the setting was disabled and to understand where it was applied. + - Compare `registry.path` to common policy locations for Script Block Logging (for example, `HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging\\EnableScriptBlockLogging`). + - Determine whether the change is likely machine-wide or user-scoped based on the hive reflected in `registry.path`, and assess the blast radius accordingly. + - Check for repeated changes (toggling) to the same `registry.path` and `registry.value` around the alert time, which can indicate attempted evasion or policy enforcement conflicts. + +- Identify the modifying process and execution context: + - Review `process.executable` for legitimacy (expected binary name, expected install path) and whether it typically performs configuration changes. + - Pivoting using `process.entity_id`, review `process.command_line` to understand how the value was set and whether the command line suggests interactive administration, scripts, or automation. + - Using nearby endpoint process telemetry on the same host, reconstruct the process tree to identify the initiating process (parent) and any immediate follow-on execution that may have benefited from reduced PowerShell logging. + +- Assess the user context and authorization: + - Review `user.name`, `user.domain`, and `user.id` to determine whether the account is expected to manage logging or policy settings on this endpoint. + - If the change is attributed to a service or system context, identify the associated service, scheduled activity, or management workflow that could have performed the modification. + - Scope the user across other hosts for similar activity during the same window to identify potential credential misuse. + +- Hunt for related activity that may be masked by reduced logging: + - Review host activity immediately before the change for suspicious behavior that could explain the need to disable Script Block Logging (initial access, privilege escalation, or tool staging). + - Review host activity after the change for suspicious process launches, script interpreter activity, persistence attempts, credential access behavior, or lateral movement indicators. + - Review network activity from the host around the change for connections consistent with payload retrieval, remote access, or command and control. + - Review other registry changes around the same time that may further impair visibility or weaken defenses. + +- Scope and impact assessment across the environment: + - Search for other instances where `registry.value` is `EnableScriptBlockLogging` and `registry.data.strings` indicates a disabled state to determine whether this is isolated or widespread. + - Pivot on `process.executable` and `user.id` to identify other endpoints where the same process or account modified this setting. + - Identify whether the setting was later restored on the same host by looking for subsequent changes to the same `registry.path` and `registry.value`. ### False positive analysis -- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary. - -### Related rules - -- PowerShell Suspicious Discovery Related Windows API Functions - 61ac3638-40a3-44b2-855a-985636ca985e -- PowerShell Keylogging Script - bd2c86a0-8b61-4457-ab38-96943984e889 -- PowerShell Suspicious Script with Audio Capture Capabilities - 2f2f4939-0b34-40c2-a0a3-844eb7889f43 -- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d -- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad -- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a -- PowerShell Suspicious Script with Screenshot Capabilities - 959a7353-1129-4aa7-9084-30746b256a70 +- Authorized policy, baseline, or hardening changes that intentionally modify PowerShell logging settings, supported by change records and consistent execution by expected accounts and tooling. +- Provisioning or imaging workflows where configuration changes occur during early host lifecycle stages and are consistent across a known deployment batch. +- Short-lived administrative troubleshooting where the setting is temporarily changed and promptly restored, with supporting documentation. ### Response and remediation -- Initiate the incident response process based on the outcome of the triage. -- Isolate the involved hosts to prevent further post-compromise behavior. -- Review the privileges assigned to the involved users to ensure that the least privilege principle is being followed. -- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software. -- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components. -- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector. -- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the mean time to respond (MTTR). +- If the change is unexpected or suspicious: + - Treat as potential defense evasion and escalate according to incident response procedures. + - Contain the endpoint if there are indicators of follow-on malicious activity in the surrounding timeframe. + - Preserve evidence related to the change, including `process.executable`, `process.command_line`, user context, and any correlated endpoint telemetry. + +- Restore and enforce PowerShell visibility: + - Re-enable Script Block Logging using approved administrative processes and verify the setting persists through policy enforcement. + - Monitor for repeated attempts to disable Script Block Logging, especially from the same user or originating process. + +- Remediate root cause and reduce recurrence: + - Identify and remove unauthorized tooling or persistence associated with the modifying process. + - Investigate potential account compromise for the associated user and take appropriate actions (credential reset and access review), prioritizing privileged accounts. + - Hunt for additional endpoints impacted by the same user or process and remediate as needed. + - Apply least-privilege controls to limit who can modify logging-related registry settings and improve alerting for additional defense impairment behaviors observed during the investigation window. """ references = [ "https://admx.help/?Category=Windows_10_2016&Policy=Microsoft.Policies.PowerShell::EnableScriptBlockLogging", @@ -93,12 +127,14 @@ registry where host.os.type == "windows" and event.type == "change" and "?:\\Windows\\System32\\svchost.exe", "?:\\Windows\\System32\\DeviceEnroller.exe", "?:\\Windows\\system32\\omadmclient.exe", + "?:\\Program Files\\Trend Micro\\Cloud Endpoint\\CloudEndpointService.exe", "?:\\Program Files (x86)\\N-able Technologies\\AutomationManagerAgent\\AutomationManager.AgentService.exe", /* Crowdstrike specific exclusion as it uses NT Object paths */ "\\Device\\HarddiskVolume*\\Windows\\System32\\svchost.exe", "\\Device\\HarddiskVolume*\\Windows\\System32\\DeviceEnroller.exe", "\\Device\\HarddiskVolume*\\Windows\\system32\\omadmclient.exe", + "\\Device\\HarddiskVolume*\\Program Files\\Trend Micro\\Cloud Endpoint\\CloudEndpointService.exe", "\\Device\\HarddiskVolume*\\Program Files (x86)\\N-able Technologies\\AutomationManagerAgent\\AutomationManager.AgentService.exe" ) ''' @@ -127,3 +163,18 @@ id = "TA0005" name = "Defense Evasion" reference = "https://attack.mitre.org/tactics/TA0005/" +[rule.investigation_fields] +field_names = [ + "@timestamp", + "registry.path", + "registry.value", + "registry.data.strings", + "process.executable", + "process.entity_id", + "host.name", + "host.id", + "user.name", + "user.id", + "user.domain" +] + diff --git a/rules/windows/defense_evasion_posh_assembly_load.toml b/rules/windows/defense_evasion_posh_assembly_load.toml index 2f1c24bb6..b21cc5070 100644 --- a/rules/windows/defense_evasion_posh_assembly_load.toml +++ b/rules/windows/defense_evasion_posh_assembly_load.toml @@ -2,39 +2,13 @@ creation_date = "2021/10/15" integration = ["windows"] maturity = "production" -updated_date = "2025/07/02" - -[transform] -[[transform.osquery]] -label = "Osquery - Retrieve DNS Cache" -query = "SELECT * FROM dns_cache" - -[[transform.osquery]] -label = "Osquery - Retrieve All Services" -query = "SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services" - -[[transform.osquery]] -label = "Osquery - Retrieve Services Running on User Accounts" -query = """ -SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services WHERE -NOT (user_account LIKE '%LocalSystem' OR user_account LIKE '%LocalService' OR user_account LIKE '%NetworkService' OR -user_account == null) -""" - -[[transform.osquery]] -label = "Osquery - Retrieve Service Unsigned Executables with Virustotal Link" -query = """ -SELECT concat('https://www.virustotal.com/gui/file/', sha1) AS VtLink, name, description, start_type, status, pid, -services.path FROM services JOIN authenticode ON services.path = authenticode.path OR services.module_path = -authenticode.path JOIN hash ON services.path = hash.path WHERE authenticode.result != 'trusted' -""" - +updated_date = "2026/02/09" [rule] author = ["Elastic"] description = """ -Detects the use of Reflection.Assembly to load PEs and DLLs in memory in PowerShell scripts. Attackers use this method -to load executables and DLLs without writing to the disk, bypassing security solutions. +Detects PowerShell scripts that invoke Reflection.Assembly or Assembly.Load to load .NET assemblies. Attackers use this +method to load executables and DLLs without writing to the disk, bypassing security solutions. """ from = "now-9m" index = ["winlogbeat-*", "logs-windows.powershell*"] @@ -43,83 +17,90 @@ license = "Elastic License v2" name = "Suspicious .NET Reflection via PowerShell" note = """## Triage and analysis +> **Disclaimer**: +> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies. + ### Investigating Suspicious .NET Reflection via PowerShell -PowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This makes it available for use in various environments, and creates an attractive way for attackers to execute code. +This alert indicates PowerShell script block content attempted to load a .NET assembly using reflection-based APIs (for example, `[System.Reflection.Assembly]::Load` or `Assembly.Load(...)`). While this can be used for legitimate extensibility, it is also commonly used to execute .NET payloads in memory and reduce file-based artifacts. -Attackers can use .NET reflection to load PEs and DLLs in memory. These payloads are commonly embedded in the script, which can circumvent file-based security protections. +#### Key alert fields to review -> **Note**: -> This investigation guide uses the [Osquery Markdown Plugin](https://www.elastic.co/guide/en/security/current/invest-guide-run-osquery.html) introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide. +- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping. +- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping. +- `powershell.file.script_block_text`: Script block content that matched the detection logic. +- `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events. +- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file. +- `powershell.file.script_block_length`: Script block length (size) context. #### Possible investigation steps -- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration capabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. -- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures. -- Examine file or network events from the involved PowerShell process for suspicious behavior. -- Investigate other alerts associated with the user/host during the past 48 hours. -- Evaluate whether the user needs to use PowerShell to complete tasks. -- Examine the host for derived artifacts that indicate suspicious activities: - - Analyze the script using a private sandboxed analysis system. - - Observe and collect information about the following activities in both the sandbox and the alert subject host: - - Attempts to contact external domains and addresses. - - Use the Elastic Defend network events to determine domains and addresses contacted by the subject process by filtering by the process' `process.entity_id`. - - Examine the DNS cache for suspicious or anomalous entries. - - $osquery_0 - - Use the Elastic Defend registry events to examine registry keys accessed, modified, or created by the related processes in the process tree. - - Examine the host services for suspicious or anomalous entries. - - $osquery_1 - - $osquery_2 - - $osquery_3 - - Retrieve the files' SHA-256 hash values using the PowerShell `Get-FileHash` cmdlet and search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc. -- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target host after the registry modification. +- Triage the execution context: + - Identify the affected host and user using `host.name`, `host.id`, `user.name`, `user.domain`, and `user.id`. + - Prioritize alerts where the user is unexpected for the host role, or where the same user appears across multiple hosts in a short time window. +- Analyze the assembly load behavior in `powershell.file.script_block_text`: + - Identify what is being passed into the load call (assembly name vs. byte array or dynamically generated content). + - Check for indicators of staged content within the same script block, such as long encoded blobs, dynamic string construction, or multiple transformation steps (decoding, decompression, or concatenation) that produce the assembly bytes. + - Look for immediate follow-on actions suggesting the loaded assembly is executed (for example, accessing types/methods and invoking them after the load). +- Reconstruct the full script block when needed: + - If the content appears partial, group related events by `powershell.file.script_block_id` and order by `powershell.sequence` to `powershell.total` to rebuild the full script block before assessing intent. + - Use `powershell.file.script_block_length` as a signal for embedded content (large or unusually variable sizes can indicate payload staging). +- Determine script origin and persistence indicators: + - If `file.path`/`file.name` are present, assess whether the script is stored in an expected location for the user and host role, or in a user-writable / temporary directory indicated by `file.directory`. + - If `file.path` is present, retrieve and review the corresponding script file for additional context (embedded payloads, additional functions, or execution logic not visible in a single script block event). + - If `file.path` is not present, treat the activity as potentially interactive or remotely delivered and rely on `powershell.file.script_block_id` and time-based pivots to gather surrounding context. +- Scope related PowerShell activity on the same host and user: + - Pivot on `host.id` and `user.id` to identify additional script blocks around the alert time that may show setup, staging, or follow-on actions. + - Check for repeated `Assembly.Load` usage across multiple `powershell.file.script_block_id` values, which may indicate iterative execution attempts or multiple payload stages. +- Scope across the environment: + - Search for the same `file.path`/`file.name` and similar `powershell.file.script_block_text` patterns on other hosts to identify propagation or reuse. + - Identify whether the same `user.id` is associated with similar script blocks across multiple `host.id` values to assess potential lateral movement or shared automation. +- Correlate with adjacent telemetry (if available in your environment): + - Process telemetry: Determine how PowerShell was launched and by what parent process around the alert time to understand delivery (interactive use, scheduled execution, service context, or another process). + - Network telemetry: Review outbound activity near the alert time for signs of payload retrieval, staging infrastructure, or command-and-control. + - File/registry telemetry: Look for newly created or modified scripts, DLLs, or persistence-related changes temporally aligned with the script block execution. + - Authentication telemetry: Review logon patterns for the same user and host around the alert time to identify unusual access patterns that could explain the execution. +- If response actions are available: + - Collect host DNS cache and a snapshot of running/installed services to support scoping and to identify suspicious services or recent name resolution consistent with payload staging. ### False positive analysis -- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did not identify malware or suspicious activity related to the user or host, this alert can be dismissed. - -### Related rules - -- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe -- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d -- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a +- Legitimate scripts may load assemblies to support internal tooling, plugin models, packaged dependencies, or automation tasks that embed .NET functionality in PowerShell. +- Benign activity is more likely when: + - `file.path`/`file.name` map to a known, owned script with a stable operational purpose. + - The same `user.id` consistently runs the same script on the same `host.id` as part of normal operations. + - `powershell.file.script_block_text` is readable and clearly loads expected assemblies without embedded blobs or multi-step content staging. +- Suspicious activity is more likely when: + - The assembly is loaded from dynamically generated bytes (encoded or transformed content) and is followed by reflection-based invocation. + - The script originates from an unusual `file.directory` or the execution context (`user.name`/`host.name`) is inconsistent with expected administrative workflows. +- If confirmed benign, document the owning team, expected execution pattern, and the specific script identity (`file.path`/`file.name`) to enable narrowly scoped tuning. ### Response and remediation -- Initiate the incident response process based on the outcome of the triage. -- Isolate the involved hosts to prevent further post-compromise behavior. -- If the triage identified malware, search the environment for additional compromised hosts. - - Implement temporary network rules, procedures, and segmentation to contain the malware. - - Stop suspicious processes. - - Immediately block the identified indicators of compromise (IoCs). - - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system. -- Remove and block malicious artifacts identified during triage. -- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services. -- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software. -- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components. -- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector. -- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the mean time to respond (MTTR). +- If the activity is confirmed or strongly suspected to be malicious: + - Isolate the affected host to prevent further in-memory execution and follow-on activity. + - Preserve evidence from the alert: + - Export the full reconstructed script block content using `powershell.file.script_block_id` with `powershell.sequence`/`powershell.total`. + - Capture `host.id`, `host.name`, `user.id`, `user.name`, `user.domain`, and any associated `file.path`/`file.name` context. + - Identify and contain related activity: + - Hunt for additional related script blocks on the same host/user and across other hosts for similar `powershell.file.script_block_text` patterns. + - Contain any identified infrastructure or artifacts based on indicators found in the script content (for example, domains, IPs, or downloaded file names). + - Remediate: + - Remove persistence and stop any related malicious processes discovered during triage and correlation. + - Review the impacted account (`user.id`) for compromise and rotate credentials as appropriate, prioritizing privileged access. + - Validate the host is remediated and monitored for recurrence before returning it to service. +- If the activity is benign but requires reduction in alert volume: + - Record the approved use case and expected execution context (host role, user role, and script location). + - Apply targeted tuning anchored to stable identifiers (for example, specific `file.path` and expected accounts) rather than broadly suppressing assembly load behavior. + - Review PowerShell governance and monitoring to ensure in-memory loading is limited to approved workflows. """ references = ["https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load"] risk_score = 47 rule_id = "e26f042e-c590-4e82-8e05-41e81bd822ad" setup = """## Setup -The 'PowerShell Script Block Logging' logging policy must be enabled. -Steps to implement the logging policy with Advanced Audit Configuration: - -``` -Computer Configuration > -Administrative Templates > -Windows PowerShell > -Turn on PowerShell Script Block Logging (Enable) -``` - -Steps to implement the logging policy via registry: - -``` -reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1 -``` +PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104). +Setup instructions: https://ela.st/powershell-logging-setup """ severity = "medium" tags = [ @@ -136,26 +117,17 @@ type = "query" query = ''' event.category:process and host.os.type:windows and +( powershell.file.script_block_text : ( "[System.Reflection.Assembly]::Load" or "[Reflection.Assembly]::Load" or "Assembly.Load(" ) and - not powershell.file.script_block_text : ( - ("CommonWorkflowParameters" or "RelatedLinksHelpInfo") and - "HelpDisplayStrings" - ) and - not (powershell.file.script_block_text : - ("Get-SolutionFiles" or "Get-VisualStudio" or "Select-MSBuildPath") and - file.name : "PathFunctions.ps1" - ) and - not powershell.file.script_block_text : ( - "Microsoft.PowerShell.Workflow.ServiceCore" and "ExtractPluginProperties([string]$pluginDir" - ) and - - not powershell.file.script_block_text : ("reflection.assembly]::Load('System." or "LoadWithPartialName('Microsoft." or "::Load(\"Microsoft." or "Microsoft.Build.Utilities.Core.dll") and - - not user.id : "S-1-5-18" + powershell.file.script_block_text : ( + "FromBase64String" or "GzipStream" or "DeflateStream" or "IO.Compression" or + "MemoryStream" or "DownloadData" or "WebClient" or "ReadAllBytes" + ) +) ''' @@ -164,10 +136,7 @@ event.category:process and host.os.type:windows and negate = true [rule.filters.query.wildcard."file.path"] case_insensitive = true -value = """ -C:\\Program Files\\Microsoft Monitoring Agent\\Agent\\Health Service State\\Monitoring Host Temporary -Files*\\AvailabilityGroupMonitoring.ps1 -""" +value = "C:\\Program Files\\Microsoft Monitoring Agent\\Agent\\Health Service State\\Monitoring Host Temporary Files*\\AvailabilityGroupMonitoring.ps1" [[rule.filters]] [rule.filters.meta] @@ -222,3 +191,22 @@ id = "TA0002" name = "Execution" reference = "https://attack.mitre.org/tactics/TA0002/" +[rule.investigation_fields] +field_names = [ + "@timestamp", + "user.name", + "user.id", + "user.domain", + "powershell.file.script_block_text", + "powershell.file.script_block_id", + "powershell.sequence", + "powershell.total", + "file.path", + "file.directory", + "file.name", + "process.pid", + "host.name", + "host.id", + "powershell.file.script_block_length" +] + diff --git a/rules/windows/defense_evasion_posh_compressed.toml b/rules/windows/defense_evasion_posh_compressed.toml index f18e497a3..1af9d0caf 100644 --- a/rules/windows/defense_evasion_posh_compressed.toml +++ b/rules/windows/defense_evasion_posh_compressed.toml @@ -2,39 +2,13 @@ creation_date = "2021/10/19" integration = ["windows"] maturity = "production" -updated_date = "2025/03/20" - -[transform] -[[transform.osquery]] -label = "Osquery - Retrieve DNS Cache" -query = "SELECT * FROM dns_cache" - -[[transform.osquery]] -label = "Osquery - Retrieve All Services" -query = "SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services" - -[[transform.osquery]] -label = "Osquery - Retrieve Services Running on User Accounts" -query = """ -SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services WHERE -NOT (user_account LIKE '%LocalSystem' OR user_account LIKE '%LocalService' OR user_account LIKE '%NetworkService' OR -user_account == null) -""" - -[[transform.osquery]] -label = "Osquery - Retrieve Service Unsigned Executables with Virustotal Link" -query = """ -SELECT concat('https://www.virustotal.com/gui/file/', sha1) AS VtLink, name, description, start_type, status, pid, -services.path FROM services JOIN authenticode ON services.path = authenticode.path OR services.module_path = -authenticode.path JOIN hash ON services.path = hash.path WHERE authenticode.result != 'trusted' -""" - +updated_date = "2026/02/09" [rule] author = ["Elastic"] description = """ -Identifies the use of .NET functionality for decompression and base64 decoding combined in PowerShell scripts, which -malware and security tools heavily use to deobfuscate payloads and load them directly in memory to bypass defenses. +Identifies PowerShell script block content that combines Base64 decoding with .NET decompression (Deflate/GZip). +Attackers use this pattern to deobfuscate and reconstruct payloads in memory to evade defenses. """ false_positives = ["Legitimate PowerShell Scripts which makes use of compression and encoding."] from = "now-9m" @@ -44,82 +18,98 @@ license = "Elastic License v2" name = "PowerShell Suspicious Payload Encoded and Compressed" note = """## Triage and analysis +> **Disclaimer**: +> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies. + ### Investigating PowerShell Suspicious Payload Encoded and Compressed -PowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This makes it available for use in various environments, and creates an attractive way for attackers to execute code. +This rule flags PowerShell script blocks that decode Base64 data and decompress it using .NET Deflate or GZip streams. This pattern is frequently used to conceal secondary script content or payloads until runtime. Focus on reconstructing the full script, recovering the decoded content, and identifying any follow-on execution on the host. -Attackers can embed compressed and encoded payloads in scripts to load directly into the memory without touching the disk. This strategy can circumvent string and file-based security protections. +#### Key alert fields to review -> **Note**: -> This investigation guide uses the [Osquery Markdown Plugin](https://www.elastic.co/guide/en/security/current/invest-guide-run-osquery.html) introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide. +- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping. +- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping. +- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file. +- `powershell.file.script_block_text`: Script block content that matched the detection logic. +- `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events. +- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation. +- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability. +- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block. +- `powershell.file.script_block_length`: Script block length (size) context. #### Possible investigation steps -- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration capabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. -- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures. -- Examine file or network events from the involved PowerShell process for suspicious behavior. -- Investigate other alerts associated with the user/host during the past 48 hours. -- Evaluate whether the user needs to use PowerShell to complete tasks. -- Examine the host for derived artifacts that indicate suspicious activities: - - Analyze the script using a private sandboxed analysis system. - - Observe and collect information about the following activities in both the sandbox and the alert subject host: - - Attempts to contact external domains and addresses. - - Use the Elastic Defend network events to determine domains and addresses contacted by the subject process by filtering by the process' `process.entity_id`. - - Examine the DNS cache for suspicious or anomalous entries. - - $osquery_0 - - Use the Elastic Defend registry events to examine registry keys accessed, modified, or created by the related processes in the process tree. - - Examine the host services for suspicious or anomalous entries. - - $osquery_1 - - $osquery_2 - - $osquery_3 - - Retrieve the files' SHA-256 hash values using the PowerShell `Get-FileHash` cmdlet and search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc. -- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target host after the registry modification. +- Establish scope and priority using alert context: + - Review `host.name` / `host.id` to identify the affected endpoint and its role (workstation, server, jump host). + - Review `user.name` / `user.domain` / `user.id` to determine whether the account is expected to run PowerShell on this host and whether it is privileged or widely used. + - Check whether this user-host pairing is common or rare in your environment to help prioritize. + +- Identify script provenance and how it was introduced: + - Review `file.path`, `file.directory`, and `file.name` to determine whether the script block was sourced from an on-disk file. + - If `file.path` is present, assess whether the location aligns with normal administrative or automation activity for this host, or whether it appears user-writable, temporary, or otherwise unusual for the account and system role. + - If `file.path` is not present or is not informative, treat the content as potentially interactive or dynamically generated and prioritize reconstructing full script content. + +- Interpret the entropy indicators to guide analysis focus: + - Use `powershell.file.script_block_length` with `powershell.file.script_block_entropy_bits` to understand whether the alert is driven by a large embedded blob versus smaller obfuscation fragments. + - Use `powershell.file.script_block_surprisal_stdev` to distinguish between: + - Uniformly random-looking blocks (often consistent with compressed/encrypted data). + - Mixed content (often consistent with a readable wrapper that transforms and then executes an embedded payload). + - Use `powershell.file.script_block_unique_symbols` to identify whether the content resembles a limited alphabet encoding (for example, Base64-like) versus broader character sets. + +- Review and reconstruct script content before making a determination: + - Review `powershell.file.script_block_text` to identify: + - Large contiguous encoded strings, byte arrays, or character arrays. + - Transform routines (decode, decrypt, decompress) that produce secondary content. + - Secondary execution patterns where transformed content is immediately evaluated or invoked. + - Embedded external references (URLs, domains, IPs) or instructions to write content to disk. + +- Rebuild full content when script blocks are split across events: + - Pivot on `powershell.file.script_block_id` to collect all related fragments. + - Order fragments using `powershell.sequence` and validate completeness using `powershell.total`. + - Perform content review on the reconstructed output, not on individual fragments, to avoid missing loader logic or the embedded payload boundaries. + +- Extract indicators and correlate with adjacent telemetry to confirm impact: + - From `powershell.file.script_block_text` (and any safely decoded or decompressed content), extract indicators such as domains, URLs, IPs, file names/paths, and distinctive strings. + - Correlate on the same `host.id` and approximate timeframe with available endpoint telemetry to identify the PowerShell host process and its launch source (parent process or initiating mechanism). Use that context to assess whether execution is user-initiated, automation-driven, or suspicious. + - Correlate on the same `host.id` and timeframe with available network, file, registry, and authentication telemetry to identify follow-on activity consistent with script execution (downloads, file writes, persistence changes, or unusual sign-ins). + +- Expand scope to detect related activity: + - Search for additional high-entropy script blocks on the same `host.id` and `user.id` before and after the alert. + - Identify other hosts where the same `file.name` / `file.path` appears with similar suspicious content characteristics. + - Look for repeated substrings or structural similarities in `powershell.file.script_block_text` across different alerts to identify shared tooling or campaigns. ### False positive analysis -- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did not identify malware or suspicious activity related to the user or host, this alert can be dismissed. - -### Related rules - -- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe -- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d -- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad +- Benign activity can produce high-entropy script blocks when scripts embed packaged resources or data blobs (for example, installers, large configuration payloads, certificates, or compressed content used by administrative tooling). +- Indicators that support a benign determination: + - Consistent `file.path` / `file.name` associated with a known internal automation package or vendor tool across many hosts. + - Stable and expected `user.name` / `user.id` usage (for example, dedicated automation accounts) with predictable host targeting. + - Repeated, consistent script structure over time where decoding or decompression results in recognizable administrative logic rather than staging or secondary execution. +- If the alert is verified benign: + - Document the owning team/tool, expected hosts, and typical execution cadence. + - Suppress recurring noise by scoping on stable attributes available in the alert (for example, `user.id`, `host.id`, and `file.path`) while preserving visibility for new or unusual sources. ### Response and remediation -- Initiate the incident response process based on the outcome of the triage. -- Isolate the involved hosts to prevent further post-compromise behavior. -- If the triage identified malware, search the environment for additional compromised hosts. - - Implement temporary network rules, procedures, and segmentation to contain the malware. - - Stop suspicious processes. - - Immediately block the identified indicators of compromise (IoCs). - - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system. -- Remove and block malicious artifacts identified during triage. -- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services. -- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software. -- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components. -- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector. -- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the mean time to respond (MTTR). +- If malicious or suspicious activity is confirmed: + - Contain the affected host to limit further execution and lateral movement. + - Preserve evidence from the alert, including `powershell.file.script_block_text`, reconstructed content (using `powershell.file.script_block_id` / `powershell.sequence` / `powershell.total`), and associated context (`user.*`, `host.*`, `file.*`, and entropy metrics). + - Use extracted indicators from the script content to hunt for related activity across the environment and to identify additional affected hosts or accounts. + - Remediate any identified persistence or staging artifacts associated with the activity and remove malicious content from affected systems. + - If account compromise is suspected, reset credentials for `user.id` / `user.name` and review access paths and recent authentication activity for that account. + +- If benign activity is confirmed: + - Record the business justification and expected behavior for the script source, including the relevant `file.path` (when present) and the associated `user.id`. + - Monitor for deviations from the established benign baseline, such as new script sources, new hosts, or materially different `powershell.file.script_block_text` structure or entropy characteristics. """ risk_score = 73 rule_id = "81fe9dc6-a2d7-4192-a2d8-eed98afc766a" setup = """## Setup -The 'PowerShell Script Block Logging' logging policy must be enabled. -Steps to implement the logging policy with Advanced Audit Configuration: +PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104). +Setup instructions: https://ela.st/powershell-logging-setup -``` -Computer Configuration > -Administrative Templates > -Windows PowerShell > -Turn on PowerShell Script Block Logging (Enable) -``` - -Steps to implement the logging policy via registry: - -``` -reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1 -``` +This rule uses the following fields that require the Windows Integration v3.3.0 and up: `powershell.file.script_block_entropy_bits`. """ severity = "high" tags = [ @@ -135,6 +125,7 @@ type = "query" query = ''' event.category:process and host.os.type:windows and + powershell.file.script_block_entropy_bits >= 4.5 and powershell.file.script_block_text : ( ( "System.IO.Compression.DeflateStream" or @@ -155,6 +146,7 @@ negate = true [rule.filters.query.wildcard."file.path"] case_insensitive = true value = "?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender Advanced Threat Protection\\\\Downloads\\\\*" + [[rule.threat]] framework = "MITRE ATT&CK" [[rule.threat.technique]] @@ -190,3 +182,22 @@ id = "TA0002" name = "Execution" reference = "https://attack.mitre.org/tactics/TA0002/" +[rule.investigation_fields] +field_names = [ + "@timestamp", + "user.name", + "user.id", + "user.domain", + "powershell.file.script_block_text", + "powershell.file.script_block_id", + "powershell.sequence", + "powershell.total", + "file.path", + "file.directory", + "file.name", + "process.pid", + "host.name", + "host.id", + "powershell.file.script_block_length" +] + diff --git a/rules/windows/defense_evasion_posh_defender_tampering.toml b/rules/windows/defense_evasion_posh_defender_tampering.toml index e9fc5500b..c4d50b64d 100644 --- a/rules/windows/defense_evasion_posh_defender_tampering.toml +++ b/rules/windows/defense_evasion_posh_defender_tampering.toml @@ -2,84 +2,112 @@ creation_date = "2024/09/11" integration = ["windows"] maturity = "production" -updated_date = "2025/09/15" +updated_date = "2026/02/09" [rule] author = ["Elastic"] description = """ -Identifies PowerShell scripts containing cmdlets and parameters that attackers can abuse to disable Windows Defender -features. Attackers can tamper with antivirus to reduce the risk of detection when executing their payloads. +Detects PowerShell scripts that uses Set-MpPreference with parameters that disable or weaken Defender. +Attackers tamper with antivirus settings to reduce detection and enable follow-on payload execution. """ from = "now-9m" index = ["winlogbeat-*", "logs-windows.powershell*"] language = "kuery" license = "Elastic License v2" name = "PowerShell Script with Windows Defender Tampering Capabilities" -note = """ ## Triage and analysis +note = """## Triage and analysis > **Disclaimer**: -> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs. +> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies. ### Investigating PowerShell Script with Windows Defender Tampering Capabilities -PowerShell is a powerful scripting language used for task automation and configuration management in Windows environments. Adversaries exploit PowerShell to disable Windows Defender features, reducing detection risks. The detection rule identifies scripts attempting to modify Defender settings, such as disabling real-time monitoring, by analyzing script block text for specific cmdlets and parameters, while excluding legitimate processes and users. +This alert highlights PowerShell script block activity that attempts to change Windows Defender preferences in ways that can reduce host protections. These changes are frequently used to create a window for follow-on execution (for example, staging payloads, running tools, or maintaining access with reduced scanning and response). -### Possible investigation steps +Triage should focus on (1) what protections were targeted and how, (2) who initiated the change and on which host(s), (3) whether the change took effect and persisted, and (4) whether there is surrounding activity that suggests initial access or follow-on malicious actions. -- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration capabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. -- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures. -- Examine the script's execution context, such as the user account, privileges, the role of the system on which it was executed, and any relevant timestamps. -- Investigate other alerts associated with the user/host during the past 48 hours. -- Evaluate whether the user needs to use PowerShell to complete tasks. -- Investigate the origin of the PowerShell script, including its source, download method, and any associated URLs or IP addresses. -- Use the Get-MpPreference cmdlet to check defender settings for the host. Revert them to the desired state if needed. -- Check for Files written and executed after the settings were changed. +#### Key alert fields to review + +- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping. +- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping. +- `powershell.file.script_block_text`: Script block content that matched the detection logic. +- `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events. +- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file. +- `powershell.file.script_block_length`: Script block length (size) context. + +#### Possible investigation steps + +- Review the script block content and determine the intended Defender impact: + - Inspect `powershell.file.script_block_text` and enumerate each `Set-MpPreference` parameter present. + - Capture whether the script is disabling protections (for example, real-time monitoring, script scanning, network file scanning) or changing default threat actions (low/moderate/high) to more permissive outcomes. + - Note whether the script changes multiple settings in one execution, repeats the changes, or includes additional logic that suggests deliberate defense impairment rather than a single configuration adjustment. + +- Reconstruct full script content when it is split across multiple events: + - If `powershell.total` is greater than 1, pivot on `powershell.file.script_block_id` and order fragments by `powershell.sequence` to rebuild the full script. + - Ensure you capture all fragments for the same `powershell.file.script_block_id` on the same `host.id` and `user.id` near the alert time; missing fragments can hide follow-on behavior embedded in later chunks. + +- Establish scope across hosts and accounts: + - Use `@timestamp`, `host.name` / `host.id`, and `user.name` / `user.domain` / `user.id` to determine whether the activity is isolated or distributed. + - Look for the same user context making similar changes across multiple hosts in a short time window (suggesting automation or compromised credentials). + - Look for multiple distinct user contexts making similar changes on the same host (suggesting lateral movement or multiple access paths). + +- Determine the execution and origin context: + - If `file.path` or `file.name` is populated, treat the activity as file-backed scripting and capture the location for scoping (where else this script exists, who can write to it, and when it was last introduced). + - If the file fields are not populated, treat the activity as potentially interactive or dynamically generated content and expand the search for adjacent script blocks from the same `user.id` on the same `host.id` around `@timestamp` to identify staging, execution flow, or repeated attempts. + +- Validate whether Defender settings were actually changed and whether the change persisted: + - Using available endpoint security telemetry and configuration auditing, validate whether the targeted preferences were applied on the affected host(s) and whether they remained in the weakened state after the alert time. + - Compare against your approved baseline for Defender settings and identify deviations that would materially reduce protection coverage. + +- Correlate with adjacent activity to identify initial access and follow-on execution: + - Correlate by `host.id` and time to nearby process activity to identify the PowerShell host process and its launching context (interactive use vs scheduled/automated execution vs another process initiating PowerShell). + - Review file and network telemetry around the same time for indicators of payload staging or execution (new files written, unusual outbound connections, or repeated attempts after the change). + - Check for repeated Defender preference modifications over time on the same host (suggesting persistent tampering) and for other suspicious activity tied to the same `user.id`. ### False positive analysis -- Legitimate administrative scripts may trigger the rule if they use Set-MpPreference cmdlets for valid configuration changes. To handle this, review the script's purpose and source, and consider adding exceptions for trusted scripts or users. -- Automated system management tools might use similar cmdlets for routine maintenance. Identify these tools and exclude their processes or directories from the rule to prevent unnecessary alerts. -- Security software updates or installations could temporarily disable certain Defender features. Monitor these activities and whitelist known update processes to avoid false positives. -- PowerShell scripts executed by system administrators for troubleshooting may appear suspicious. Verify the user ID and script content, and exclude known administrator accounts from the rule if they frequently perform such tasks. +Legitimate activity can modify Defender preferences, but it should be explainable, consistent, and controlled. + +- Common benign drivers: + - Approved endpoint management or administrative maintenance that adjusts scanning behavior for performance or operational compatibility. + - Controlled troubleshooting where settings are temporarily changed and later restored. + +- Validation questions to reduce uncertainty: + - Does `user.id` map to an expected administrative or management identity for this host population? + - Is the activity aligned with known maintenance windows, change records, and documented procedures? + - Is `file.path` (when present) consistent with a known, maintained script location, and does the script content align with an approved baseline? + +If the activity is benign, document the owner, expected scope (hosts/users), expected recurrence, and the intended steady-state protection posture. ### Response and remediation -- Initiate the incident response process based on the outcome of the triage. - - If malicious activity is confirmed, perform a broader investigation to identify the scope of the compromise and determine the appropriate remediation steps. -- Isolate the involved hosts to prevent further post-compromise behavior. -- If the triage identified malware, search the environment for additional compromised hosts. - - Implement temporary network rules, procedures, and segmentation to contain the malware. - - Stop suspicious processes. - - Immediately block the identified indicators of compromise (IoCs). - - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system. -- Remove and block malicious artifacts identified during triage. -- Reimage the host operating system or restore the compromised files to clean versions. -- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software. -- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services. -- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components. -- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the mean time to respond (MTTR). +If the activity is unauthorized or suspicious, treat it as a defense evasion attempt with potential follow-on actions. + +- Contain and preserve evidence: + - Prioritize affected endpoints identified by `host.id` / `host.name` and preserve relevant evidence, including the full reconstructed script from `powershell.file.script_block_id` and `powershell.file.script_block_text`. + - Capture the initiating identity context (`user.name`, `user.domain`, `user.id`) for incident scoping and credential review. + +- Restore protections and eliminate the change source: + - Restore Windows Defender preferences to the approved baseline using authorized operational processes and verify protections are active. + - If `file.path` is present, identify the responsible script and remove or disable unauthorized automation that applies the changes. + - If the activity appears user-driven or interactive, investigate how the user obtained execution capability on the host and address the root cause. + +- Address potential account compromise and lateral movement: + - Review recent activity associated with the initiating account and affected hosts for signs of credential misuse, unexpected access patterns, or follow-on execution. + - Apply appropriate credential remediation for impacted identities and review privileged access assignments relevant to the affected endpoints. + +- Scope and monitor: + - Hunt for the same Defender-tampering parameters within `powershell.file.script_block_text` across other hosts and users to identify additional impacted systems. + - Continue monitoring for recurrence of similar preference changes tied to the same `user.id`, as repeated tampering may indicate persistence or an active intrusion. """ -risk_score = 21 +risk_score = 47 rule_id = "c124dc1b-cef2-4d01-8d74-ff6b0d5096b6" setup = """## Setup -The 'PowerShell Script Block Logging' logging policy must be enabled. -Steps to implement the logging policy with Advanced Audit Configuration: - -``` -Computer Configuration > -Administrative Templates > -Windows PowerShell > -Turn on PowerShell Script Block Logging (Enable) -``` - -Steps to implement the logging policy via registry: - -``` -reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1 -``` +PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104). +Setup instructions: https://ela.st/powershell-logging-setup """ -severity = "low" +severity = "medium" tags = [ "Domain: Endpoint", "OS: Windows", @@ -149,3 +177,22 @@ id = "TA0002" name = "Execution" reference = "https://attack.mitre.org/tactics/TA0002/" +[rule.investigation_fields] +field_names = [ + "@timestamp", + "user.name", + "user.id", + "user.domain", + "powershell.file.script_block_text", + "powershell.file.script_block_id", + "powershell.sequence", + "powershell.total", + "file.path", + "file.directory", + "file.name", + "process.pid", + "host.name", + "host.id", + "powershell.file.script_block_length" +] + diff --git a/rules/windows/defense_evasion_posh_encryption.toml b/rules/windows/defense_evasion_posh_encryption.toml index dd131d442..c5e38dabe 100644 --- a/rules/windows/defense_evasion_posh_encryption.toml +++ b/rules/windows/defense_evasion_posh_encryption.toml @@ -2,13 +2,13 @@ creation_date = "2023/01/23" integration = ["windows"] maturity = "production" -updated_date = "2025/03/20" +updated_date = "2026/02/09" [rule] author = ["Elastic"] description = """ -Identifies the use of Cmdlets and methods related to encryption/decryption of files in PowerShell scripts, which malware -and offensive security tools can abuse to encrypt data or decrypt payloads to bypass security solutions. +Identifies PowerShell script block content that uses .NET cryptography APIs for file encryption or decryption. +Attackers abuse these routines to encrypt data for impact or decrypt staged payloads to evade defenses. """ false_positives = ["Legitimate PowerShell Scripts which makes use of encryption."] from = "now-9m" @@ -18,33 +18,81 @@ license = "Elastic License v2" name = "PowerShell Script with Encryption/Decryption Capabilities" note = """## Triage and analysis +> **Disclaimer**: +> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies. + ### Investigating PowerShell Script with Encryption/Decryption Capabilities -PowerShell is one of the main tools system administrators use for automation, report routines, and other tasks, making it available for use in various environments, creating an attractive way for attackers to execute code. +This rule identifies PowerShell script block content that implements cryptographic encryption or decryption using .NET APIs. Matching script blocks commonly include symmetric cryptography classes (for example, AES/Rijndael or the SymmetricAlgorithm base type), key derivation helpers (for example, PasswordDeriveBytes or Rfc2898DeriveBytes), explicit cipher configuration (CipherMode and PaddingMode), and calls that create an encryptor or decryptor. -PowerShell offers encryption and decryption functionalities that attackers can abuse for various purposes, such as concealing payloads, C2 communications, and encrypting data as part of ransomware operations. +This behavior can be legitimate (protecting configuration values, packaging content, or controlled encryption for business workflows). It can also indicate malicious activity such as encrypting local data for impact or decrypting staged content to reduce static visibility before follow-on execution. Prioritize determining what data is being transformed, where outputs are written, and whether the user/host/script origin aligns with expected activity. + +#### Key alert fields to review + +- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping. +- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping. +- `powershell.file.script_block_text`: Script block content that matched the detection logic. +- `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events. +- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file. +- `powershell.file.script_block_length`: Script block length (size) context. #### Possible investigation steps -- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration capabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. -- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures. -- Examine file or network events from the involved PowerShell process for suspicious behavior. -- Investigate other alerts associated with the user/host during the past 48 hours. -- Evaluate whether the user needs to use PowerShell to complete tasks. +- Review `powershell.file.script_block_text` to understand the cryptographic intent and data flow: + - Identify whether the logic is primarily encrypting, decrypting, or doing both. + - Note which cryptographic primitives are used (for example, AES/Rijndael, hashing helpers, and key derivation routines) and how keys/IVs are produced (hard-coded values, derived from passwords, generated randomly, or passed in). + - Identify the transformed data source and destination: + - File-oriented operations: look for path construction, directory traversal patterns, repeated read/write loops, file extension changes, renames, or deletion of originals. + - In-memory operations: look for large embedded blobs, byte arrays, stream usage, or logic that converts decrypted content into executable form or writes it to a new artifact. + - Extract and preserve any embedded secrets or deterministic derivation parameters (password strings, salts, iteration counts, static IVs, or key material), as these can be critical for impact assessment and recovery. + +- Determine whether the alert contains the full implementation or only a fragment: + - Use `powershell.file.script_block_length` to gauge whether this is a complete routine (larger blocks) versus a wrapper or function invocation (smaller blocks). + - If the script appears incomplete, pivot on `powershell.file.script_block_id` and use `powershell.sequence` / `powershell.total` to retrieve and order all fragments before concluding intent. + +- Validate execution context and provenance: + - Review `user.name`, `user.domain`, and `user.id` to determine whether this account typically performs encryption/decryption tasks and whether the account scope matches the host role. + - Review `host.name` and `host.id` to determine asset criticality and whether similar activity is expected on this system (for example, administrative hosts may have more automation than standard endpoints). + - If `file.path` / `file.name` is present, evaluate whether the script origin is expected: + - Compare the path and name to approved automation locations and naming conventions. + - Treat unexpected paths, user-writable directories, or newly observed script locations as higher risk. + +- Scope the activity using alert fields: + - On the same host, search for additional script blocks tied to the same `powershell.file.script_block_id` to find related functions or setup code not visible in the initial alert fragment. + - Search across hosts for repeating patterns in `powershell.file.script_block_text` and for the same `file.name` to determine whether this is a widely deployed administrative script or isolated activity. + - Pivot on `user.id` to identify whether similar script blocks appear on multiple hosts, which may indicate coordinated activity. + +- Correlate with adjacent telemetry around `@timestamp` for the same `host.id` and `user.id` (if available in your environment): + - Process execution telemetry to identify the PowerShell host process and what initiated it, helping distinguish interactive use from automation or remotely initiated activity. + - File activity telemetry to identify bursts of file modifications/creations consistent with bulk encryption/decryption and to determine which directories and file types were affected. + - Network telemetry to identify connections that could support retrieval of encrypted content, exchange of key material, or staging/downloading of additional payloads. + - Authentication telemetry to identify unusual logons or session types for the user preceding execution. + +- Determine disposition and urgency: + - Treat as higher severity if the script indicates broad file processing, writes many outputs, modifies user data locations, or includes embedded key material/blobs associated with staged content. + - Treat as lower severity if the script is clearly tied to approved operations, originates from a known `file.path`, is executed by expected accounts, and shows consistent recurrence patterns with expected scope. ### False positive analysis -- This is a dual-use mechanism, meaning its usage is not inherently malicious. Analysts can dismiss the alert if the script doesn't contain malicious functions or potential for abuse, no other suspicious activity was identified, and there are justifications for the execution. +- Legitimate PowerShell automation may implement encryption/decryption for secure configuration handling, packaging, data protection, or interoperability with other systems. +- Benign activity is more likely to have consistent `file.path` / `file.name` values, execute under expected administrative accounts, and recur on appropriate hosts with stable script content. +- If the script is determined to be benign, document what data it protects, where it is expected to run, which accounts execute it, and what normal recurrence looks like to reduce future triage time. ### Response and remediation -- Initiate the incident response process based on the outcome of the triage. -- Isolate the involved hosts to prevent further post-compromise behavior. -- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software. -- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services. -- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components. -- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector. -- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the mean time to respond (MTTR). +- If the activity is suspicious or malicious: + - Contain the host to prevent further encryption/decryption activity and reduce the risk of spread or data impact. + - Preserve evidence from the alert, including the full `powershell.file.script_block_text` and any reconstructed fragments correlated via `powershell.file.script_block_id`. + - If `file.path` is present, collect the referenced script from disk and preserve it for forensic review and scoping. + - Identify impacted systems and data: + - If file-impact is suspected, prioritize backup protection, incident response escalation, and recovery planning. + - If payload staging is suspected, prioritize identifying the decrypted output or follow-on execution artifacts. + - Scope and hunt across the environment for related activity using `user.id`, `host.id`, recurring `file.name`, and distinctive fragments of `powershell.file.script_block_text`. + - Remediate the associated account and access path: validate legitimacy, reset credentials if compromise is suspected, and apply least-privilege controls where appropriate. + - Remove or block the identified script and any related artifacts discovered during analysis, and monitor for recurrence. + +- If the activity is confirmed benign: + - Record the expected `file.path` / `file.name`, the responsible `user.id`, and normal execution patterns to support consistent future triage and tuning decisions. """ risk_score = 47 rule_id = "1d9aeb0b-9549-46f6-a32d-05e2a001b7fd" @@ -108,3 +156,22 @@ id = "TA0005" name = "Defense Evasion" reference = "https://attack.mitre.org/tactics/TA0005/" +[rule.investigation_fields] +field_names = [ + "@timestamp", + "user.name", + "user.id", + "user.domain", + "powershell.file.script_block_text", + "powershell.file.script_block_id", + "powershell.sequence", + "powershell.total", + "file.path", + "file.directory", + "file.name", + "process.pid", + "host.name", + "host.id", + "powershell.file.script_block_length" +] +