[Rule Tuning] PowerShell Rules Revamp - 1 (#5619)

* [Rule Tuning] PowerShell Rules Revamp - 1

* bump
This commit is contained in:
Jonhnathan
2026-01-26 19:01:48 -03:00
committed by GitHub
parent 42e7f3b4ce
commit fc55e8b308
5 changed files with 442 additions and 227 deletions
@@ -2,13 +2,13 @@
creation_date = "2023/01/11"
integration = ["windows"]
maturity = "production"
updated_date = "2025/09/03"
updated_date = "2026/01/26"
[rule]
author = ["Elastic"]
description = """
Identifies the use of the Exchange PowerShell cmdlet, New-MailBoxExportRequest, to export the contents of a primary
mailbox or archive to a .pst file. Adversaries may target user email to collect sensitive information.
Detects PowerShell script block content that creates Exchange mailbox export requests via New-MailboxExportRequest,
commonly writing PST files. Adversaries can abuse export requests to collect and stage email content for exfiltration.
"""
false_positives = ["Legitimate exchange system administration activity."]
from = "now-9m"
@@ -18,41 +18,72 @@ license = "Elastic License v2"
name = "Exchange Mailbox Export via PowerShell"
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.
### Investigating Exchange Mailbox Export via PowerShell
The `New-MailBoxExportRequest` cmdlet is used to begin the process of exporting contents of a primary mailbox or archive to a .pst file. Note that this is done on a per-mailbox basis and this cmdlet is available only in on-premises Exchange.
Attackers can abuse this functionality in preparation for exfiltrating contents, which is likely to contain sensitive and strategic data.
This alert indicates PowerShell script block content associated with creation of an Exchange mailbox export request. Mailbox exports can produce PST files and may represent sensitive email collection and staging for later access or exfiltration. Prioritize understanding who initiated the activity, which mailbox(es) were targeted, where the output was intended to be written, and whether the activity aligns with approved administrative workflows.
#### 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
- 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.
- Investigate the export operation:
- Identify the user account that performed the action and whether it should perform this kind of action.
- Contact the account owner and confirm whether they are aware of this activity.
- Check if this operation was approved and performed according to the organization's change management policy.
- Retrieve the operation status and use the `Get-MailboxExportRequest` cmdlet to review previous requests.
- By default, no group in Exchange has the privilege to import or export mailboxes. Investigate administrators that assigned the "Mailbox Import Export" privilege for abnormal activity.
- Investigate if there is a significant quantity of export requests in the alert timeframe. This operation is done on a per-mailbox basis and can be part of a mass export.
- If the operation was completed successfully:
- Check if the file is on the path specified in the command.
- Investigate if the file was compressed, archived, or retrieved by the attacker for exfiltration.
- Validate what the script block is attempting to do using `powershell.file.script_block_text`:
- Identify the mailbox target(s). Look for explicit `-Mailbox` values, mailbox identifiers, or mailbox enumeration logic (for example, use of `Get-Mailbox` as an input source).
- Identify the intended export destination from `-FilePath`. Note whether the path appears to be a local path or a network location, and whether the naming pattern suggests a single mailbox export or bulk export activity.
- Note whether the content suggests automation (loops, iteration over multiple mailboxes, variable-driven file paths) versus a single interactive export request.
- Reconstruct full script block content when fragmented:
- If `powershell.file.script_block_text` appears truncated or incomplete, group related events by `powershell.file.script_block_id` and order by `powershell.sequence` up to `powershell.total` to rebuild the full script before assessing intent.
- Pivot to other script blocks from the same `user.id` and `host.id` near `@timestamp` to capture supporting context (variable definitions, functions, or preceding logic that populates mailbox or file path parameters).
- Establish execution context and initiating source:
- Use `host.name` and `host.id` to determine whether the activity originated from an expected Exchange management host (for example, an Exchange server or approved administrative workstation) or from an unexpected endpoint.
- Use `user.domain`, `user.name`, and `user.id` to determine whether the initiating account is expected to perform mailbox export operations (administrator or approved automation account) and whether the timing aligns with known operational windows.
- Use `process.pid` and `host.id` to correlate with process execution telemetry and determine how PowerShell was launched (interactive session vs automated execution) and whether there is an unusual parent process lineage for administrative activity.
- If `file.path` or `file.name` is present, treat the referenced script as a key artifact:
- Determine whether the path and file name match known administrative tooling or expected automation locations.
- If the script is not recognized, preserve it for analysis and assess whether it contains additional collection, staging, or cleanup logic beyond the export request.
- Scope the activity across users, hosts, and time:
- Identify other `powershell.file.script_block_id` values associated with the same `user.id` or `host.id` to determine whether the export activity is part of a larger PowerShell workflow.
- Review whether multiple distinct `process.pid` values are associated with similar export activity for the same user, which may indicate multiple sessions or parallel execution.
- Assess potential impact and staging indicators:
- If an export destination path is identifiable in `powershell.file.script_block_text`, correlate with file activity on the relevant host(s) to determine whether a PST file was created, modified, accessed, moved, or archived after `@timestamp`.
- Correlate with network telemetry for `host.id` around `@timestamp` to identify access to the export destination location and any subsequent outbound transfers that could indicate staging or exfiltration.
- Review authentication activity associated with `user.id` and the involved `host.id` around `@timestamp` for anomalies such as unusual logon sources, new sessions, or activity outside normal administrative patterns.
- Preserve evidence for follow-on analysis:
- Record the reconstructed script content, `powershell.file.script_block_id`, and the full `powershell.sequence`/`powershell.total` range used for reconstruction.
- Capture the specific mailbox identifiers and destination paths observed in `powershell.file.script_block_text` to support scoping and data exposure assessment.
### False positive analysis
- This mechanism can be used legitimately. Analysts can dismiss the alert if the administrator is aware of the activity and it is done with proper approval.
- Legitimate mailbox exports may occur for compliance, eDiscovery, user support, migrations, or incident response. Validate the presence of an authorized business request, ticket, or approved workflow that matches the timing and the scope of the export.
- Benign activity is more likely when:
- The initiating `user.name` is a known Exchange administrator or authorized automation account in `user.domain`.
- The `host.name` is an expected administrative host for Exchange management tasks.
- The destination path referenced in `powershell.file.script_block_text` aligns with approved export storage locations and expected naming conventions.
- Activity is higher risk when it originates from an unexpected `host.name`, uses an unusual `user.name`, targets many mailboxes, or writes to atypical destinations.
### Response and remediation
- Initiate the incident response process based on the outcome of the triage.
- If the involved host is not the Exchange server, isolate the host to prevent further post-compromise behavior.
- Use the `Remove-MailboxExportRequest` cmdlet to remove fully or partially completed export requests.
- Prioritize cases that involve personally identifiable information (PII) or other classified data.
- 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.
- Review the privileges of users with the "Mailbox Import Export" privilege to ensure that the least privilege principle is being followed.
- 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 unauthorized or cannot be validated:
- Contain the initiating account (`user.id`/`user.name`) by disabling the account or removing access to mailbox export capabilities, and rotate credentials as appropriate.
- Contain affected systems (`host.id`/`host.name`) based on scope and confidence. Isolate endpoints used for unexpected Exchange administrative actions to prevent further collection or staging.
- Identify and secure any exported PST output referenced in `powershell.file.script_block_text`. Treat recovered PST files and scripts as sensitive evidence; restrict access and preserve copies for investigation.
- Use approved administrative procedures to cancel or remove unauthorized export requests and prevent completion of in-progress exports.
- Conduct follow-on threat hunting and scoping:
- Search for additional mailbox export activity by the same `user.id` and `host.id`, including repeated or bulk export patterns.
- Review additional PowerShell script block activity for the same `powershell.file.script_block_id` and adjacent script blocks around `@timestamp` to identify related collection, staging, or cleanup actions.
- Reduce recurrence risk:
- Apply least-privilege controls for accounts that can initiate mailbox exports and restrict where exports can be written.
- Limit Exchange administrative actions to approved management hosts and monitored administrative workflows.
- Enhance monitoring for repeated mailbox export requests, unusual export destinations, and suspicious PowerShell activity associated with the same users and hosts.
"""
references = [
"https://www.volexity.com/blog/2020/12/14/dark-halo-leverages-solarwinds-compromise-to-breach-organizations/",
@@ -61,6 +92,11 @@ references = [
]
risk_score = 47
rule_id = "54a81f68-5f2a-421e-8eed-f888278bb712"
setup = """## Setup
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 = [
"Domain: Endpoint",
@@ -75,25 +111,13 @@ type = "query"
query = '''
event.category:process and host.os.type:windows and
powershell.file.script_block_text : "New-MailboxExportRequest"
powershell.file.script_block_text : "New-MailboxExportRequest" and
(
powershell.file.script_block_text : ("-FilePath" or ".pst") and
powershell.file.script_block_text : ("-Mailbox" or "Get-Mailbox" or "ExportToPSTFile" or "-Identity")
)
'''
[[rule.filters]]
[rule.filters.meta]
negate = true
[rule.filters.query.wildcard."file.path"]
case_insensitive = true
value = "?:\\\\Users\\\\*\\\\AppData\\\\Roaming\\\\Microsoft\\\\Exchange\\\\RemotePowerShell\\\\*"
[[rule.filters]]
[rule.filters.meta]
negate = true
[rule.filters.query.wildcard."file.path"]
case_insensitive = true
value = "*\\\\tmp_????????.???\\\\tmp_????????.???.ps?1"
[[rule.threat]]
framework = "MITRE ATT&CK"
[[rule.threat.technique]]
@@ -122,3 +146,22 @@ id = "TA0009"
name = "Collection"
reference = "https://attack.mitre.org/tactics/TA0009/"
[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"
]
@@ -2,11 +2,14 @@
creation_date = "2021/10/19"
integration = ["windows"]
maturity = "production"
updated_date = "2025/09/03"
updated_date = "2026/01/26"
[rule]
author = ["Elastic"]
description = "Detects PowerShell scripts that can record audio, a common feature in popular post-exploitation tooling."
description = """
Detects PowerShell script block content that invokes microphone capture routines or WinMM audio APIs.
Adversaries may use audio recording to surveil users or capture sensitive conversations for theft or extortion.
"""
from = "now-9m"
index = ["winlogbeat-*", "logs-windows.powershell*"]
language = "kuery"
@@ -14,63 +17,83 @@ license = "Elastic License v2"
name = "PowerShell Suspicious Script with Audio Capture Capabilities"
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.
### Investigating PowerShell Suspicious Script with Audio Capture Capabilities
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 associated with microphone recording or Windows multimedia audio capture routines. Because audio capture can expose sensitive conversations, prioritize investigation when the activity is unexpected for the user, host, or time of day, or when the script suggests local staging or external transfer.
Attackers can use PowerShell to interact with the Windows API with the intent of capturing audio from input devices connected to the victim's computer.
#### 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.
- Investigate if the script stores the recorded data locally and determine if anything was recorded.
- Investigate whether the script contains exfiltration capabilities and identify the exfiltration server.
- Assess network data to determine if the host communicated with the exfiltration server.
- Establish alert context and ownership:
- Identify the execution context using `user.name`, `user.domain`, and `user.id`, and the impacted endpoint using `host.name` and `host.id`.
- If `file.path` or `file.name` is populated, note the script origin and whether the location is expected for administrative scripts.
- Analyze `powershell.file.script_block_text` for capability and intent:
- Determine whether the script enumerates devices, starts/stops recording, sets recording duration, or saves output.
- Capture any referenced output paths, filenames, or extensions (for example, `.wav`) that may indicate where audio was written.
- Look for higher-risk patterns in the same content, such as dynamic unmanaged API access (for example, `Add-Type` with `DllImport`), obfuscation, looping/retry logic, or cleanup routines (delete after save/upload).
- Note any embedded remote destinations, credentials, or upload logic if present to support containment and scoping.
- Reconstruct full script content when the script block is split:
- Pivot on `powershell.file.script_block_id` for the same endpoint and time window.
- Rebuild the full content by ordering fragments with `powershell.sequence` and validating completeness with `powershell.total` before drawing conclusions from a single fragment.
- Review nearby script blocks from the same `user.id` and `host.id` to identify configuration, helper functions, or follow-on actions not present in the matching fragment.
- Validate execution chain and likely launch method (if additional telemetry is available):
- Correlate the alert time on `host.name` with process execution telemetry to identify the PowerShell host process and its parent process.
- Assess whether the parent process and timing are consistent with expected user/admin activity on that host.
- If the script content indicates remote execution, scheduled execution, or automation, review surrounding activity for corroborating evidence (repeated runs, multiple hosts, or multiple users).
- Assess evidence of audio collection and data handling:
- If the script indicates an output location, correlate with file activity around `@timestamp` to identify newly created or modified files that could contain recorded audio.
- Review `file.path` and `file.name` (when present) for suspicious or deceptive naming and whether the same artifact appears on multiple endpoints.
- If the script references encoding or compression, consider that audio may be staged as non-audio file types; use distinctive filenames or directories from the script content to guide searches.
- Identify possible exfiltration or secondary objectives:
- Review the script content for staging steps (chunking, encoding, archiving) and any explicit network transfer logic.
- If remote destinations are present in the script content, correlate with network telemetry for outbound connections from the same host near the alert time and evaluate whether transfer volume and timing are consistent with audio data movement.
- Scope and prevalence:
- Search for the same function names, API strings, or distinctive substrings from `powershell.file.script_block_text` across other endpoints to identify reuse.
- Check whether the same `user.id` is associated with similar script blocks on multiple hosts, or whether multiple users on the same `host.id` exhibit similar activity.
- If `file.name` is populated, look for the same filename and path patterns elsewhere to determine distribution.
### False positive analysis
- Regular users should not need scripts to capture audio, which makes false positives unlikely. In the case of authorized benign true positives (B-TPs), exceptions can be added.
### Related rules
- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe
- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d
- Benign scripts typically show consistent script content and stable provenance (reused script name/path and predictable execution patterns). Unexpected users, ad hoc locations, or one-off executions on user workstations increase suspicion.
### 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.
- Prioritize the response if this alert involves key executives or potentially valuable targets for espionage.
- 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 unauthorized audio capture is suspected:
- Contain the endpoint to prevent further collection and reduce the risk of data loss.
- Preserve evidence: the full reconstructed script content (all fragments), related PowerShell events in the same time window, and any identified output or staging artifacts.
- If audio files are discovered, handle them as potentially sensitive data per your incident response and privacy procedures.
- Identify any remote destinations from the script content and take network containment actions appropriate for your environment.
- Scope for related activity using `user.id`, `host.id`, and distinctive content from `powershell.file.script_block_text` to identify other affected endpoints or users.
- Assess the associated account for compromise and take account-level containment actions (credential reset, session revocation, access review) when misuse is confirmed.
- If confirmed benign:
- Document the business purpose, script owner, and expected execution scope (accounts, hosts, and schedule).
- If the activity is legitimate but creating operational noise, add rule exceptions with narrowly scoped constraints based on stable attributes (consistent script content patterns, known script file path/name, and expected executing accounts) rather than broadly suppressing audio-related indicators.
"""
references = ["https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-MicrophoneAudio.ps1"]
risk_score = 73
rule_id = "2f2f4939-0b34-40c2-a0a3-844eb7889f43"
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 = "high"
tags = [
@@ -88,13 +111,19 @@ query = '''
event.category:process and host.os.type:windows and
powershell.file.script_block_text : (
"Get-MicrophoneAudio" or
("Get-AudioDevice" and "Recording" and "Set-AudioDevice") or
"WindowsAudioDevice-Powershell-Cmdlet" or
(waveInGetNumDevs and mciSendStringA)
)
and not powershell.file.script_block_text : (
(
"winmm.dll" and
(
"waveInGetNumDevs" or "waveInOpen" or "waveInStart" or
"mciSendString" or "mciSendStringA" or "mciSendStringW"
)
)
) and
not powershell.file.script_block_text : (
"sentinelbreakpoints" and "Set-PSBreakpoint" and "PowerSploitIndicators"
)
and not user.id : "S-1-5-18"
'''
@@ -133,3 +162,21 @@ 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"
]
@@ -2,13 +2,13 @@
creation_date = "2023/01/12"
integration = ["windows"]
maturity = "production"
updated_date = "2025/09/03"
updated_date = "2026/01/26"
[rule]
author = ["Elastic"]
description = """
Detects PowerShell scripts that can get the contents of the clipboard, which attackers can abuse to retrieve sensitive
information like credentials, messages, etc.
Detects PowerShell script block content that retrieves clipboard data using Get-Clipboard or Windows clipboard APIs.
Adversaries can collect copied credentials, tokens, or other sensitive data from the clipboard.
"""
from = "now-9m"
index = ["winlogbeat-*", "logs-windows.powershell*"]
@@ -17,41 +17,63 @@ license = "Elastic License v2"
name = "PowerShell Suspicious Script with Clipboard Retrieval Capabilities"
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.
### Investigating PowerShell Suspicious Script with Clipboard Retrieval Capabilities
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 associated with clipboard access. The matched script may use the Get-Clipboard cmdlet or Windows clipboard APIs (for example, Windows.Forms.Clipboard or related UI components) to retrieve user-copied data. Clipboard collection is often opportunistic and may be used to capture credentials, tokens, and other sensitive information copied during normal workflows.
Attackers can abuse PowerShell capabilities to get the contents of the clipboard with the goal of stealing credentials and other valuable information, such as credit card data and confidential conversations.
#### 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.
- Determine whether the script stores the captured data locally.
- Investigate whether the script contains exfiltration capabilities and identify the exfiltration server.
- Assess network data to determine if the host communicated with the exfiltration server.
- Review `powershell.file.script_block_text` to understand the clipboard access technique and usage pattern:
- Get-Clipboard usage versus .NET/UI based access (for example, Windows.Forms.Clipboard, Windows.Clipboard, TextBox.Paste, or methods such as GetText).
- Whether clipboard access appears to be a one-time action or part of repeated/polled collection logic (for example, loops, timers, or repeated calls in the same script).
- Reconstruct the complete script when content is split across multiple events:
- Pivot on `powershell.file.script_block_id` and order related events by `powershell.sequence` to rebuild the full script up to `powershell.total`.
- Use `powershell.file.script_block_length` as context for unusually large scripts, which may indicate additional functionality beyond clipboard retrieval.
- Evaluate intent by reviewing surrounding logic in `powershell.file.script_block_text`:
- Where clipboard contents are stored (variables, arrays, buffers) and whether the script transforms data after retrieval (for example, encoding, compression, string manipulation, or obfuscation).
- Any indications of staging or transfer behavior following clipboard access (for example, writing data to disk or preparing network requests).
- Validate provenance and expected use:
- Use `user.name`, `user.domain`, and `user.id` to determine whether the execution context is expected to run PowerShell that interacts with the clipboard.
- Use `host.name` and `host.id` to determine whether the affected host is a typical endpoint for interactive clipboard use or an unusual target for clipboard collection.
- If `file.path`, `file.directory`, or `file.name` are present, assess whether the script source is expected for the user and host, and whether it is located in a user-writable or temporary location.
- Determine execution context and whether the activity is user-driven or automated:
- Correlate activity for the same `host.id` and `user.id` with process execution telemetry (if available) to identify the PowerShell host and its parent process, and whether execution was interactive or automated.
- If authentication telemetry is available, correlate nearby logon activity for the same user and host to identify newly established sessions or unusual remote access preceding the alert.
- Scope and prevalence:
- Search for other script block events with similar clipboard-related strings in `powershell.file.script_block_text` for the same `user.id` and `host.id`, and then across other hosts to identify reuse.
- Look for reuse of the same `file.name` or `file.path` across hosts, which can indicate shared tooling or broader distribution.
- Assess impact and potential exposure:
- If the script suggests repeated clipboard reads or immediate staging/transfer behavior, treat clipboard contents handled by the affected user on the host during the timeframe as potentially exposed and prioritize investigation accordingly.
### False positive analysis
- Regular users are unlikely to use scripting utilities to capture contents of the clipboard, making false positives unlikely. In the case of authorized benign true positives (B-TPs), exceptions can be added.
### Related rules
- PowerShell Keylogging Script - bd2c86a0-8b61-4457-ab38-96943984e889
- Clipboard retrieval can be legitimate in user productivity scripts, developer/test utilities, and administrative automation that transforms or inserts copied content into other workflows.
- Benign activity is more likely when the script source (`file.path`/`file.name`) aligns with known internal tooling, the user context is expected, and the script block text shows clear user-facing intent without follow-on staging or transfer behavior.
- False positives are less likely when clipboard access is repeated or automated, appears on atypical hosts for interactive use, or is coupled with suspicious handling of the retrieved data (for example, encoding, buffering, or writing to unexpected locations).
### 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.
- Prioritize the response if this alert involves key executives or potentially valuable targets for espionage.
- 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 confirmed benign, document the script, expected users/hosts, and the business justification. Ensure the script source is maintained under change control to detect unauthorized modifications.
- If suspicious or malicious activity is suspected:
- Contain the affected host to prevent further collection and preserve evidence.
- Preserve relevant artifacts, including all related script block events for the `powershell.file.script_block_id` and any referenced script file from `file.path` (if present).
- Investigate for downstream handling of clipboard data (staging or transfer) using available endpoint, file, network, and authentication telemetry scoped to `host.id` and `user.id`.
- Assess potential credential or token exposure for the affected user and initiate credential hygiene actions appropriate to your environment.
- Remove or remediate the execution source (malicious scripts or unauthorized automation) and investigate for persistence mechanisms that could re-run the clipboard collection.
- Expand scoping by hunting for the same clipboard retrieval patterns in `powershell.file.script_block_text`, and for reuse of the same `file.name`/`file.path` across other hosts.
- Capture lessons learned and update monitoring and access controls to reduce future abuse of PowerShell-based collection techniques while preserving required operational use cases.
"""
references = [
"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-clipboard",
@@ -61,21 +83,8 @@ risk_score = 47
rule_id = "92984446-aefb-4d5e-ad12-598042ca80ba"
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 = [
@@ -91,15 +100,20 @@ type = "query"
query = '''
event.category:process and host.os.type:windows and
(powershell.file.script_block_text : (
"Windows.Clipboard" or
"Windows.Forms.Clipboard" or
"Windows.Forms.TextBox"
) and
powershell.file.script_block_text : (
"]::GetText" or
".Paste()"
)) or powershell.file.script_block_text : "Get-Clipboard" and
(
(
powershell.file.script_block_text : (
"Windows.Clipboard" or
"Windows.Forms.Clipboard" or
"Windows.Forms.TextBox"
) and
powershell.file.script_block_text : (
"]::GetText" or
".Paste()"
)
) or
powershell.file.script_block_text : "Get-Clipboard"
) and
not powershell.file.script_block_text : (
"sentinelbreakpoints" and "Set-PSBreakpoint" and "PowerSploitIndicators"
) and
@@ -107,6 +121,11 @@ event.category:process and host.os.type:windows and
not (
file.path : *WindowsPowerShell\\Modules\\*.ps1 and
file.name : ("Convert-ExcelRangeToImage.ps1" or "Read-Clipboard.ps1")
) and
not powershell.file.script_block_text : (
"Set-Alias -Name \"gcb\" -Value \"Get-Clipboard\"" or
"[Windows.Clipboard]::SetText($colorizedText" or
"EEFCB906-B326-4E99-9F54-8B4BB6EF3C6D"
)
'''
@@ -162,3 +181,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"
]
+95 -47
View File
@@ -2,13 +2,13 @@
creation_date = "2021/10/15"
integration = ["windows"]
maturity = "production"
updated_date = "2025/03/20"
updated_date = "2026/01/26"
[rule]
author = ["Elastic"]
description = """
Detects the use of Win32 API Functions that can be used to capture user keystrokes in PowerShell scripts. Attackers use
this technique to capture user input, looking for credentials and/or other valuable data.
Detects PowerShell script block content that references Win32 keylogging primitives such as key state polling or
low-level input hooks. Adversaries use keylogging to capture credentials and other sensitive user input.
"""
from = "now-9m"
index = ["winlogbeat-*", "logs-windows.powershell*"]
@@ -17,41 +17,80 @@ license = "Elastic License v2"
name = "PowerShell Keylogging Script"
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.
### Investigating PowerShell Keylogging Script
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 that PowerShell Script Block Logging recorded code referencing Win32 API functions commonly used to capture keystrokes or register low-level keyboard or mouse hooks. These primitives are frequently used by offensive tooling and custom implants to collect credentials and other sensitive input.
Attackers can abuse PowerShell capabilities to capture user keystrokes with the goal of stealing credentials and other valuable information as credit card data and confidential conversations.
#### 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.
- Determine whether the script stores the captured data locally.
- Investigate whether the script contains exfiltration capabilities and identify the exfiltration server.
- Assess network data to determine if the host communicated with the exfiltration server.
- Identify the execution scope and prioritize response:
- Review `host.name` and `host.id` to understand where the activity occurred and whether the asset is high value.
- Review `user.name`, `user.domain`, and `user.id` to determine the executing account and whether the activity is expected for that user.
- Use `@timestamp` to establish when the script block executed and to anchor a timeline for related activity on the same host.
- Analyze the script block content for intent and capability:
- Review `powershell.file.script_block_text` and note which capability is present:
- Key state polling: `GetAsyncKeyState`, `NtUserGetAsyncKeyState`, `GetKeyboardState`.
- Input hooking: `SetWindowsHookEx`, `SetWindowsHookExA`, `SetWindowsHookExW`, or `NtUserSetWindowsHookEx` with hook constants like `WM_KEYBOARD_LL`, `WH_KEYBOARD_LL`, or `WH_MOUSE_LL`, and hook flow indicators such as `LowLevelKeyboardProc` or `CallNextHookEx`.
- Foreground window context capture often used to label keystrokes: `GetForegroundWindow`, `GetWindowTextA`, `GetWindowTextW`.
- Commodity keylogging functions or modules: `Get-Keystrokes`.
- Determine whether the script block only defines helper functions or actively invokes hook registration or polling loops (higher confidence of active collection).
- Look for common interop patterns used to call Win32 APIs from PowerShell (for example, `Add-Type`, `DllImport`, or embedded C#) and for logic that maps virtual key codes to readable output.
- Identify any referenced output handling within the script text (for example, file writes, buffering, encoding, or remote transmission routines) and capture those strings for scoping.
- Reconstruct the full script when content is split across multiple events:
- If `powershell.total` is greater than 1 or the content appears truncated, collect all events that share the same `powershell.file.script_block_id`.
- Rebuild the script by ordering fragments using `powershell.sequence` until the expected `powershell.total` is reached.
- If expected sequences are missing, widen the time range around `@timestamp` to account for ingestion delays or gaps before concluding reconstruction.
- Preserve the fully reconstructed script text as evidence and for further scoping.
- Determine the source of the script and how it was introduced:
- If `file.path` and `file.name` are present, treat the script as file-backed and assess whether the location and name are consistent with approved tooling and change control.
- Prioritize review when `file.path` suggests a user-writable or transient location, or when `file.name` is unusual for your environment.
- If file origin fields are not present, treat the execution as inline or dynamically generated and focus on surrounding PowerShell activity from the same `user.id` and `host.id` around `@timestamp`.
- Correlate the alert time on the same host with available process telemetry to identify the PowerShell host process and its parent process, then evaluate whether the execution chain aligns with expected administrative behavior.
- Check for evidence of collection, staging, or downstream actions:
- Within `powershell.file.script_block_text`, identify any referenced output locations, file names, or remote destinations that could indicate where captured input is stored or transmitted.
- Review nearby endpoint file and network telemetry (if available) for unexpected file creation/modification in user-writable locations and unusual outbound connections following the alert time.
- Review authentication telemetry around the alert time to understand which accounts may have been exposed on the affected host during the suspected collection window.
- Look for repeated executions from the same `host.id` and `user.id` over time, which can indicate persistence or scheduled collection.
- Scope for additional executions and impacted hosts:
- Search for other alerts or script block events that match the same `powershell.file.script_block_id`, the same `file.name`, or distinctive substrings from `powershell.file.script_block_text` across the environment.
- Identify whether the same `user.id` executed similar script blocks on multiple hosts or whether multiple users are affected on the same host, which may indicate broader compromise.
- If multiple hosts show the same file-backed script (`file.name` and `file.path`), determine whether it is a legitimate deployment versus unauthorized propagation.
### False positive analysis
- Regular users do not have a business justification for using scripting utilities to capture keystrokes, making false positives unlikely. In the case of authorized benign true positives (B-TPs), exceptions can be added.
### Related rules
- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe
- Some legitimate PowerShell automation may reference low-level input or window APIs for specialized use cases such as accessibility utilities, kiosk or lab automation, macro/hotkey tooling, or authorized security testing.
- False positives are more likely when the script is part of a known internal toolkit with a documented business purpose, runs on a limited and expected host scope, and lacks evidence of sustained collection loops or output handling.
- Treat as higher risk when the script content includes continuous polling or hook registration combined with logic that records, formats, stores, or prepares data for transmission, or when the activity occurs on user workstations outside of expected maintenance windows.
### 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.
- Prioritize the response if this alert involves key executives or potentially valuable targets for espionage.
- 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 unauthorized or suspicious:
- Contain the host to prevent further input collection and limit follow-on actions.
- Preserve evidence from the alert, including the complete `powershell.file.script_block_text` reconstructed via `powershell.file.script_block_id`, `powershell.sequence`, and `powershell.total`, and any associated `file.path` and `file.name` values.
- Use the script content to extract any indicators (for example, output file names, remote destinations, or unique strings) and scope for related activity on other hosts.
- Assume potential credential exposure on the affected host and follow incident response procedures for credential reset, session revocation, and review of privileged access activity during the suspected collection window.
- Remediate the initial access path and remove any persistence or secondary payloads identified during correlation, including removing unauthorized scripts referenced by `file.path`.
- If the activity is confirmed benign:
- Document the legitimate script or tool, expected operators (`user.id`), and expected host scope (`host.id`).
- Apply narrowly scoped tuning based on stable, repeatable identifiers (for example, specific `file.path` and expected accounts) to reduce recurring noise while maintaining coverage for unauthorized keylogging behavior.
"""
references = [
"https://github.com/EmpireProject/Empire/blob/master/data/module_source/collection/Get-Keystrokes.ps1",
@@ -61,21 +100,8 @@ risk_score = 73
rule_id = "bd2c86a0-8b61-4457-ab38-96943984e889"
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 = "high"
tags = [
@@ -92,13 +118,16 @@ type = "query"
query = '''
event.category:process and host.os.type:windows and
(
powershell.file.script_block_text : (GetAsyncKeyState or NtUserGetAsyncKeyState or GetKeyboardState or "Get-Keystrokes") or
powershell.file.script_block_text : (
(SetWindowsHookA or SetWindowsHookW or SetWindowsHookEx or SetWindowsHookExA or NtUserSetWindowsHookEx) and
(GetForegroundWindow or GetWindowTextA or GetWindowTextW or "WM_KEYBOARD_LL" or "WH_MOUSE_LL")
powershell.file.script_block_text : (GetAsyncKeyState or NtUserGetAsyncKeyState or GetKeyboardState or "Get-Keystrokes") or
powershell.file.script_block_text : (
(SetWindowsHookEx or SetWindowsHookExA or SetWindowsHookExW or NtUserSetWindowsHookEx) and
(
GetForegroundWindow or GetWindowTextA or GetWindowTextW or "WM_KEYBOARD_LL" or "WH_MOUSE_LL" or
"WH_KEYBOARD_LL" or "LowLevelKeyboardProc" or "CallNextHookEx"
)
)
) and not user.id : "S-1-5-18"
and not powershell.file.script_block_text : (
) and not user.id : "S-1-5-18" and
not powershell.file.script_block_text : (
"sentinelbreakpoints" and "Set-PSBreakpoint"
)
'''
@@ -144,3 +173,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"
]
+80 -41
View File
@@ -2,13 +2,13 @@
creation_date = "2023/01/11"
integration = ["windows"]
maturity = "production"
updated_date = "2025/09/03"
updated_date = "2026/01/26"
[rule]
author = ["Elastic"]
description = """
Detects PowerShell scripts that can be used to collect data from mailboxes. Adversaries may target user email to collect
sensitive information.
Detects PowerShell script block content that indicates programmatic mailbox access using Outlook Interop/MAPI or EWS
APIs. Adversaries can use mailbox access to collect email content and attachments for exfiltration.
"""
from = "now-9m"
index = ["winlogbeat-*", "logs-windows.powershell*"]
@@ -17,42 +17,75 @@ license = "Elastic License v2"
name = "PowerShell Mailbox Collection Script"
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.
### Investigating PowerShell Mailbox Collection Script
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 consistent with programmatic mailbox access using Outlook Interop/MAPI or Exchange Web Services (EWS) managed APIs. This can support legitimate administration and support workflows, but it can also be used to collect messages and attachments for discovery or theft. Prioritize determining (1) who ran the script and where, (2) which mailbox(es) and folders were accessed, and (3) whether any content was staged or transferred.
Email mailboxes and their information can be valuable assets for attackers. Company mailboxes often contain sensitive information such as login credentials, intellectual property, financial data, and personal information, making them high-value targets for malicious actors.
#### Key alert fields to review
This rule identifies scripts that contains methods and classes that can be abused to collect emails from local and remote mailboxes.
- `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.
- Determine whether the script was executed and capture relevant information, such as arguments that reveal intent or are indicators of compromise (IoCs).
- Investigate other alerts associated with the user/host during the past 48 hours.
- Evaluate whether the user needs to use PowerShell to complete tasks.
- Determine whether the script stores the captured data locally.
- Investigate whether the script contains exfiltration capabilities and identify the exfiltration server.
- Assess network data to determine if the host communicated with the exfiltration server.
- Confirm the execution context:
- Review `user.name`, `user.domain`, and `user.id` to identify the executing account and whether it commonly performs mailbox-related automation.
- Review `host.name` and `host.id` to identify the endpoint and whether it is expected to run mailbox access scripts.
- Use the alert time as an anchor to check for other suspicious activity from the same user and host in the surrounding timeframe.
- Analyze `powershell.file.script_block_text` for technique, targeting, and scope:
- Outlook Interop/MAPI usage commonly includes `Microsoft.Office.Interop.Outlook`, `Interop.Outlook.olDefaultFolders`, `Outlook.Application`, `GetNamespace`/`MAPI`, `Session`, `GetDefaultFolder`, `GetSharedDefaultFolder`, and default folder references such as `olFolderInBox`.
- EWS usage commonly includes `Microsoft.Exchange.WebServices.Data.ExchangeService`, `Microsoft.Exchange.WebServices.Data.Folder`, `Microsoft.Exchange.WebServices.Data.FileAttachment`, and mailbox enumeration or retrieval methods such as `FindItems`, `Bind`, `WellKnownFolderName`, `FolderId`, `ItemView`, `PropertySet`, `SearchFilter`, and `Attachments`.
- Identify mailbox identifiers (email addresses, aliases), folder targets (default folders, explicit folder names), and any shared mailbox references.
- Determine collection breadth by noting loops over folders/items, pagination settings (such as item views), and filtering criteria (date/keyword filters).
- Identify how items or attachments are handled (enumeration only vs retrieval and save/export) and any referenced storage locations.
- Reconstruct the full script:
- Pivot on `powershell.file.script_block_id` to collect all fragments related to the same script block.
- Use `powershell.sequence` and `powershell.total` to order fragments and confirm completeness; missing fragments can change intent and scope.
- Use `powershell.file.script_block_length` to understand whether the alert contains a short snippet or part of a larger tool.
- Determine script provenance and reuse:
- If present, review `file.path` and `file.name` to identify the on-disk script/module source and whether the location aligns with expected administrative tooling.
- If `file.path` is absent, treat the execution as potentially interactive or dynamically loaded; rely on the reconstructed script content to determine intent and scope.
- Search for the same `file.name`/`file.path` and distinctive strings from `powershell.file.script_block_text` across other hosts and users to identify reuse or deployment.
- Correlate with adjacent telemetry (if available) to identify launch method and downstream activity:
- Process execution: identify the PowerShell host process and any parent process/launcher to determine whether execution was interactive, automated, or initiated by another application.
- Network activity: review outbound connections around the alert time for access to Exchange/EWS endpoints and for unexpected external destinations that could indicate transfer of collected data.
- File activity: review for new or modified files consistent with staging mail content (exports, archives, or attachment dumps), especially in locations referenced by the script.
- Authentication activity: review for unusual sign-ins or repeated authentications by the executing account that align with mailbox enumeration or access to multiple mailboxes.
- Assess impact and prioritize response:
- Treat as higher priority when the script references shared mailboxes, multiple mailbox identifiers, broad folder enumeration, or attachment retrieval.
- Coordinate with messaging administrators to validate whether the access scope is authorized and to help identify potentially affected mailboxes and data types.
### False positive analysis
- This mechanism can be used legitimately. Analysts can dismiss the alert if the administrator is aware of the activity and it is done with proper approval.
### Related rules
- Exporting Exchange Mailbox via PowerShell - 6aace640-e631-4870-ba8e-5fdda09325db
- Approved administration, reporting, archiving, or migration workflows that programmatically access mailbox data using Outlook Interop/MAPI or EWS.
- Support or troubleshooting activity where staff retrieve specific messages or attachments under an approved request.
- Development or testing of Outlook automation or EWS integrations on non-production hosts.
### Response and remediation
- Initiate the incident response process based on the outcome of the triage.
- If the involved host is not the Exchange server, isolate the host to prevent further post-compromise behavior.
- Prioritize cases that involve personally identifiable information (PII) or other classified data.
- 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 unauthorized or suspicious, contain the affected host to prevent continued mailbox access and reduce the risk of data transfer.
- Restrict the executing account (disable or reset credentials based on severity) and review mailbox permissions and delegation associated with the account.
- Preserve evidence for investigation and response:
- Retain the reconstructed script content and all associated script block events for `powershell.file.script_block_id`.
- If `file.path` is present, preserve the referenced script/module for forensic review and determine how it was introduced.
- Identify and remediate persistence or automation mechanisms that could re-run the script and expand collection scope.
- Assess and document impact using the reconstructed script content:
- Determine which mailbox(es), folders, and item types (messages and attachments) were targeted.
- Identify any local staging locations or transfer destinations referenced by the script.
- Coordinate with messaging administrators and relevant stakeholders to support mailbox-level investigation and response actions if sensitive data may have been accessed.
- Increase monitoring for recurrence by tracking similar script block content, repeated executions by the same user, and reuse of the same script file paths across hosts.
"""
references = [
"https://github.com/dafthack/MailSniper/blob/master/MailSniper.ps1",
@@ -62,21 +95,8 @@ risk_score = 47
rule_id = "a2d04374-187c-4fd9-b513-3ad4e7fdd67a"
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 = [
@@ -153,3 +173,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"
]