PowerShell Suspicious Discovery Related Windows API Functions

Detects PowerShell scripts that references native Windows API functions commonly used for discovery of users, groups, shares, sessions, domain trusts, and service security. Attackers use these APIs for situational awareness and targeting prior to lateral movement or collection.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2021/10/13"
  3integration = ["windows"]
  4maturity = "production"
  5updated_date = "2026/02/09"
  6
  7[rule]
  8author = ["Elastic"]
  9description = """
 10Detects PowerShell scripts that references native Windows API functions commonly used for discovery of users, groups,
 11shares, sessions, domain trusts, and service security. Attackers use these APIs for situational awareness and targeting
 12prior to lateral movement or collection.
 13"""
 14false_positives = ["Legitimate PowerShell scripts that make use of these functions."]
 15from = "now-9m"
 16index = ["winlogbeat-*", "logs-windows.powershell*"]
 17language = "kuery"
 18license = "Elastic License v2"
 19name = "PowerShell Suspicious Discovery Related Windows API Functions"
 20note = """## Triage and analysis
 21
 22> **Disclaimer**:
 23> 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.
 24
 25### Investigating PowerShell Suspicious Discovery Related Windows API Functions
 26
 27This rule flags PowerShell script block content that references Windows API functions commonly used to enumerate users, groups, shares, sessions, domain trusts, and service security. These APIs are frequently accessed via native interop patterns (for example, runtime-compiled type definitions) and can be used to build an inventory of the environment before follow-on activity such as lateral movement or collection.
 28
 29#### Key alert fields to review
 30
 31- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping.
 32- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping.
 33- `powershell.file.script_block_text`: Script block content that matched the detection logic.
 34- `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.
 35- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
 36- `powershell.file.script_block_length`: Script block length (size) context.
 37
 38#### Possible investigation steps
 39
 40- Establish context and expected behavior:
 41  - Review `host.name`/`host.id` to understand where the activity occurred and whether the host is expected to perform administrative discovery.
 42  - Review `user.name`, `user.domain`, and `user.id` to determine whether the executing identity aligns with expected administrative or automation activity for that host.
 43  - Use `powershell.file.script_block_length` (when present) as a quick indicator of complexity; unusually large blocks may indicate embedded helper libraries or inline compiled source.
 44
 45- Review, reconstruct, and characterize the script content:
 46  - Inspect `powershell.file.script_block_text` and identify which API function name(s) are present and what discovery objective they imply.
 47  - If the script is fragmented, reconstruct it by grouping events on `powershell.file.script_block_id` and ordering by `powershell.sequence` until `powershell.total` is reached. Capture the complete reconstructed content for case notes.
 48  - Look for indicators of native API invocation rather than standard cmdlets, such as embedded type definitions, interop attributes, or inline compiled source. This can increase confidence that the script was designed to directly call Windows APIs.
 49  - Identify additional capabilities in the same script block (or neighboring fragments) that may indicate follow-on behavior, such as credential access, remote execution logic, output staging, or data access from remote resources.
 50
 51- Map API functions to likely discovery intent:
 52  - Share and server discovery: `NetShareEnum`, `NetServerGetInfo`, `GetComputerNameEx`.
 53  - User and group discovery: `NetUserEnum`, `NetUserGetInfo`, `NetGroupEnum`, `NetGroupGetInfo`, `NetGroupGetUsers`, `NetLocalGroupEnum`, `NetLocalGroupGetMembers`, `GetUserNameEx`, `NetUserModalsGet`.
 54  - Session and workstation discovery: `NetSessionEnum`, `NetWkstaUserEnum`, `NetWkstaGetInfo`, `NetWkstaTransportEnum`, `WTSEnumerateSessionsEx`, `WTSQuerySessionInformation`, `LsaGetLogonSessionData`.
 55  - Domain trust and site discovery: `DsEnumerateDomainTrusts`, `LsaEnumerateTrustedDomains`, `DsGetSiteName`.
 56  - Service permission discovery: `QueryServiceObjectSecurity`.
 57  - Job discovery: `NetScheduleJobEnum`.
 58
 59- Determine discovery scope and targets from the content:
 60  - Extract any referenced hostnames, domain names, share names, or service names directly from `powershell.file.script_block_text` (when present) and record them as potential discovery targets.
 61  - Look for indications of remote enumeration (for example, multiple target strings, iteration constructs, or repeated API calls with varying targets) versus single-host local discovery.
 62  - Prioritize cases that include higher-impact reconnaissance (trust enumeration, session enumeration, logon session data, or service security descriptor queries), especially when the account or host context is unusual.
 63
 64- Validate script origin and execution source:
 65  - If file context is present, review `file.path`, `file.directory`, and `file.name` to understand whether the script block originated from an on-disk script and whether that location aligns with approved tooling.
 66  - Treat scripts originating from unexpected or user-writable locations, or scripts with unusual naming, as higher risk and scope for other related activity on the same host and by the same user.
 67
 68- Scope for related activity using alert-available pivots:
 69  - Search for other script blocks with the same `powershell.file.script_block_id` to ensure no fragments are missed and to identify repeated execution.
 70  - Search for additional hits of the same `file.path`/`file.name` across hosts to determine whether the script is broadly deployed or opportunistically introduced.
 71  - Identify other occurrences of similar discovery content by pivoting on distinctive substrings within `powershell.file.script_block_text` (such as specific API function names) and the same `user.id` to detect a broader reconnaissance pattern.
 72
 73- Correlate with adjacent telemetry (as available in your environment):
 74  - Process context: determine how PowerShell was started and whether the initiation method is consistent with expected activity for `user.name` on `host.name`.
 75  - Authentication and remote access: look for logons or remote session activity involving the same `user.name` around the alert time, especially if the script content suggests remote enumeration of servers or sessions.
 76  - Network and share access: review evidence of access to discovered targets (servers/shares) following the enumeration to identify potential collection from network shares.
 77  - Persistence or privilege escalation follow-on: if service security or job enumeration is present, look for subsequent changes consistent with service or scheduled job manipulation.
 78
 79### False positive analysis
 80
 81- Benign administrative discovery can occur during routine inventory, troubleshooting, or access validation, especially from dedicated administration hosts and by well-known administrative identities.
 82- False positives are more likely when the same script content appears regularly, is consistently associated with the same `file.path`/`file.name`, and is executed by expected `user.name` accounts on expected hosts.
 83- Prioritize as suspicious when the activity is new for the environment, originates from an unexpected script location, is executed by a non-administrative or unusual account, or appears across multiple hosts in a short period.
 84
 85### Response and remediation
 86
 87- If the activity is confirmed or strongly suspected malicious:
 88  - Contain the affected host and restrict the involved account to prevent further reconnaissance and follow-on actions.
 89  - Preserve evidence from the alert, including the fully reconstructed `powershell.file.script_block_text`, `powershell.file.script_block_id`, and any extracted target identifiers, along with `host.id` and `user.id` for reliable correlation.
 90  - Scope across the environment for additional executions using pivots on `user.id`, `host.id`, `file.path`/`file.name`, and distinctive content within `powershell.file.script_block_text`.
 91  - Review the enumerated targets (hosts, shares, users/groups, trusts, services, sessions) for unauthorized access attempts and follow-on activity such as network share access, credential misuse, or lateral movement.
 92
 93- If the activity is determined to be legitimate but unexpected:
 94  - Identify the script owner and document the business purpose, expected execution scope (hosts/users), and expected cadence.
 95  - Reduce future noise by baselining approved scripts and execution contexts, and ensure logging and monitoring coverage remains sufficient to investigate future occurrences.
 96"""
 97references = [
 98    "https://github.com/BC-SECURITY/Empire/blob/9259e5106986847d2bb770c4289c0c0f1adf2344/data/module_source/situational_awareness/network/powerview.ps1#L21413",
 99    "https://github.com/atc-project/atc-data/blob/master/docs/Logging_Policies/LP_0109_windows_powershell_script_block_log.md",
100]
101risk_score = 21
102rule_id = "61ac3638-40a3-44b2-855a-985636ca985e"
103setup = """## Setup
104
105PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
106Setup instructions: https://ela.st/powershell-logging-setup
107"""
108severity = "low"
109tags = [
110    "Domain: Endpoint",
111    "OS: Windows",
112    "Use Case: Threat Detection",
113    "Tactic: Discovery",
114    "Tactic: Collection",
115    "Tactic: Execution",
116    "Resources: Investigation Guide",
117    "Data Source: PowerShell Logs",
118]
119timestamp_override = "event.ingested"
120type = "query"
121
122query = '''
123event.category:process and host.os.type:windows and
124  powershell.file.script_block_text : (
125    NetShareEnum or
126    NetWkstaUserEnum or
127    NetSessionEnum or
128    NetLocalGroupEnum or
129    NetLocalGroupGetMembers or
130    DsGetSiteName or
131    DsEnumerateDomainTrusts or
132    WTSEnumerateSessionsEx or
133    WTSQuerySessionInformation or
134    LsaGetLogonSessionData or
135    QueryServiceObjectSecurity or
136    GetComputerNameEx or
137    NetWkstaGetInfo or
138    GetUserNameEx or
139    NetUserEnum or
140    NetUserGetInfo or
141    NetGroupEnum or
142    NetGroupGetInfo or
143    NetGroupGetUsers or
144    NetWkstaTransportEnum or
145    NetServerGetInfo or
146    LsaEnumerateTrustedDomains  or
147    NetScheduleJobEnum or
148    NetUserModalsGet
149  ) and
150  not powershell.file.script_block_text : (
151    ("DsGetSiteName" and ("DiscoverWindowsComputerProperties.ps1" and "param($SourceType, $SourceId, $ManagedEntityId, $ComputerIdentity)")) or
152    ("# Copyright: (c) 2018, Ansible Project" and "#Requires -Module Ansible.ModuleUtils.AddType" and "#AnsibleRequires -CSharpUtil Ansible.Basic") or
153    ("Ansible.Windows.Setup" and "Ansible.Windows.Setup" and "NativeMethods.NetWkstaGetInfo(null, 100, out netBuffer);")
154  ) and
155  not file.directory: "C:\Program Files (x86)\Automox\WDK\Win32\WinSession"
156'''
157
158
159[[rule.filters]]
160
161[rule.filters.meta]
162negate = true
163[rule.filters.query.wildcard."file.path"]
164case_insensitive = true
165value = "?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender Advanced Threat Protection\\\\DataCollection\\\\*"
166[[rule.threat]]
167framework = "MITRE ATT&CK"
168[[rule.threat.technique]]
169id = "T1069"
170name = "Permission Groups Discovery"
171reference = "https://attack.mitre.org/techniques/T1069/"
172[[rule.threat.technique.subtechnique]]
173id = "T1069.001"
174name = "Local Groups"
175reference = "https://attack.mitre.org/techniques/T1069/001/"
176
177
178[[rule.threat.technique]]
179id = "T1087"
180name = "Account Discovery"
181reference = "https://attack.mitre.org/techniques/T1087/"
182[[rule.threat.technique.subtechnique]]
183id = "T1087.001"
184name = "Local Account"
185reference = "https://attack.mitre.org/techniques/T1087/001/"
186
187
188[[rule.threat.technique]]
189id = "T1135"
190name = "Network Share Discovery"
191reference = "https://attack.mitre.org/techniques/T1135/"
192
193[[rule.threat.technique]]
194id = "T1482"
195name = "Domain Trust Discovery"
196reference = "https://attack.mitre.org/techniques/T1482/"
197
198
199[rule.threat.tactic]
200id = "TA0007"
201name = "Discovery"
202reference = "https://attack.mitre.org/tactics/TA0007/"
203[[rule.threat]]
204framework = "MITRE ATT&CK"
205[[rule.threat.technique]]
206id = "T1059"
207name = "Command and Scripting Interpreter"
208reference = "https://attack.mitre.org/techniques/T1059/"
209[[rule.threat.technique.subtechnique]]
210id = "T1059.001"
211name = "PowerShell"
212reference = "https://attack.mitre.org/techniques/T1059/001/"
213
214
215[[rule.threat.technique]]
216id = "T1106"
217name = "Native API"
218reference = "https://attack.mitre.org/techniques/T1106/"
219
220
221[rule.threat.tactic]
222id = "TA0002"
223name = "Execution"
224reference = "https://attack.mitre.org/tactics/TA0002/"
225[[rule.threat]]
226framework = "MITRE ATT&CK"
227[[rule.threat.technique]]
228id = "T1039"
229name = "Data from Network Shared Drive"
230reference = "https://attack.mitre.org/techniques/T1039/"
231
232
233[rule.threat.tactic]
234id = "TA0009"
235name = "Collection"
236reference = "https://attack.mitre.org/tactics/TA0009/"
237
238[rule.investigation_fields]
239field_names = [
240    "@timestamp",
241    "user.name",
242    "user.id",
243    "user.domain",
244    "powershell.file.script_block_text",
245    "powershell.file.script_block_id",
246    "powershell.sequence",
247    "powershell.total",
248    "file.path",
249    "file.directory",
250    "file.name",
251    "process.pid",
252    "host.name",
253    "host.id",
254    "powershell.file.script_block_length"
255]

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.

This rule flags PowerShell script block content that references Windows API functions commonly used to enumerate users, groups, shares, sessions, domain trusts, and service security. These APIs are frequently accessed via native interop patterns (for example, runtime-compiled type definitions) and can be used to build an inventory of the environment before follow-on activity such as lateral movement or collection.

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

  • Establish context and expected behavior:

    • Review host.name/host.id to understand where the activity occurred and whether the host is expected to perform administrative discovery.
    • Review user.name, user.domain, and user.id to determine whether the executing identity aligns with expected administrative or automation activity for that host.
    • Use powershell.file.script_block_length (when present) as a quick indicator of complexity; unusually large blocks may indicate embedded helper libraries or inline compiled source.
  • Review, reconstruct, and characterize the script content:

    • Inspect powershell.file.script_block_text and identify which API function name(s) are present and what discovery objective they imply.
    • If the script is fragmented, reconstruct it by grouping events on powershell.file.script_block_id and ordering by powershell.sequence until powershell.total is reached. Capture the complete reconstructed content for case notes.
    • Look for indicators of native API invocation rather than standard cmdlets, such as embedded type definitions, interop attributes, or inline compiled source. This can increase confidence that the script was designed to directly call Windows APIs.
    • Identify additional capabilities in the same script block (or neighboring fragments) that may indicate follow-on behavior, such as credential access, remote execution logic, output staging, or data access from remote resources.
  • Map API functions to likely discovery intent:

    • Share and server discovery: NetShareEnum, NetServerGetInfo, GetComputerNameEx.
    • User and group discovery: NetUserEnum, NetUserGetInfo, NetGroupEnum, NetGroupGetInfo, NetGroupGetUsers, NetLocalGroupEnum, NetLocalGroupGetMembers, GetUserNameEx, NetUserModalsGet.
    • Session and workstation discovery: NetSessionEnum, NetWkstaUserEnum, NetWkstaGetInfo, NetWkstaTransportEnum, WTSEnumerateSessionsEx, WTSQuerySessionInformation, LsaGetLogonSessionData.
    • Domain trust and site discovery: DsEnumerateDomainTrusts, LsaEnumerateTrustedDomains, DsGetSiteName.
    • Service permission discovery: QueryServiceObjectSecurity.
    • Job discovery: NetScheduleJobEnum.
  • Determine discovery scope and targets from the content:

    • Extract any referenced hostnames, domain names, share names, or service names directly from powershell.file.script_block_text (when present) and record them as potential discovery targets.
    • Look for indications of remote enumeration (for example, multiple target strings, iteration constructs, or repeated API calls with varying targets) versus single-host local discovery.
    • Prioritize cases that include higher-impact reconnaissance (trust enumeration, session enumeration, logon session data, or service security descriptor queries), especially when the account or host context is unusual.
  • Validate script origin and execution source:

    • If file context is present, review file.path, file.directory, and file.name to understand whether the script block originated from an on-disk script and whether that location aligns with approved tooling.
    • Treat scripts originating from unexpected or user-writable locations, or scripts with unusual naming, as higher risk and scope for other related activity on the same host and by the same user.
  • Scope for related activity using alert-available pivots:

    • Search for other script blocks with the same powershell.file.script_block_id to ensure no fragments are missed and to identify repeated execution.
    • Search for additional hits of the same file.path/file.name across hosts to determine whether the script is broadly deployed or opportunistically introduced.
    • Identify other occurrences of similar discovery content by pivoting on distinctive substrings within powershell.file.script_block_text (such as specific API function names) and the same user.id to detect a broader reconnaissance pattern.
  • Correlate with adjacent telemetry (as available in your environment):

    • Process context: determine how PowerShell was started and whether the initiation method is consistent with expected activity for user.name on host.name.
    • Authentication and remote access: look for logons or remote session activity involving the same user.name around the alert time, especially if the script content suggests remote enumeration of servers or sessions.
    • Network and share access: review evidence of access to discovered targets (servers/shares) following the enumeration to identify potential collection from network shares.
    • Persistence or privilege escalation follow-on: if service security or job enumeration is present, look for subsequent changes consistent with service or scheduled job manipulation.

False positive analysis

  • Benign administrative discovery can occur during routine inventory, troubleshooting, or access validation, especially from dedicated administration hosts and by well-known administrative identities.
  • False positives are more likely when the same script content appears regularly, is consistently associated with the same file.path/file.name, and is executed by expected user.name accounts on expected hosts.
  • Prioritize as suspicious when the activity is new for the environment, originates from an unexpected script location, is executed by a non-administrative or unusual account, or appears across multiple hosts in a short period.

Response and remediation

  • If the activity is confirmed or strongly suspected malicious:

    • Contain the affected host and restrict the involved account to prevent further reconnaissance and follow-on actions.
    • Preserve evidence from the alert, including the fully reconstructed powershell.file.script_block_text, powershell.file.script_block_id, and any extracted target identifiers, along with host.id and user.id for reliable correlation.
    • Scope across the environment for additional executions using pivots on user.id, host.id, file.path/file.name, and distinctive content within powershell.file.script_block_text.
    • Review the enumerated targets (hosts, shares, users/groups, trusts, services, sessions) for unauthorized access attempts and follow-on activity such as network share access, credential misuse, or lateral movement.
  • If the activity is determined to be legitimate but unexpected:

    • Identify the script owner and document the business purpose, expected execution scope (hosts/users), and expected cadence.
    • Reduce future noise by baselining approved scripts and execution contexts, and ensure logging and monitoring coverage remains sufficient to investigate future occurrences.

References

Related rules

to-top