PowerShell PSReflect Script

Detects the use of PSReflect in PowerShell scripts. Attackers leverage PSReflect as a library that enables PowerShell to access win32 API functions.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2021/10/15"
  3integration = ["windows"]
  4maturity = "production"
  5min_stack_comments = "Breaking change at 8.14.0 for the Windows Integration."
  6min_stack_version = "8.14.0"
  7updated_date = "2024/10/28"
  8
  9[transform]
 10[[transform.osquery]]
 11label = "Osquery - Retrieve DNS Cache"
 12query = "SELECT * FROM dns_cache"
 13
 14[[transform.osquery]]
 15label = "Osquery - Retrieve All Services"
 16query = "SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services"
 17
 18[[transform.osquery]]
 19label = "Osquery - Retrieve Services Running on User Accounts"
 20query = """
 21SELECT description, display_name, name, path, pid, service_type, start_type, status, user_account FROM services WHERE
 22NOT (user_account LIKE '%LocalSystem' OR user_account LIKE '%LocalService' OR user_account LIKE '%NetworkService' OR
 23user_account == null)
 24"""
 25
 26[[transform.osquery]]
 27label = "Osquery - Retrieve Service Unsigned Executables with Virustotal Link"
 28query = """
 29SELECT concat('https://www.virustotal.com/gui/file/', sha1) AS VtLink, name, description, start_type, status, pid,
 30services.path FROM services JOIN authenticode ON services.path = authenticode.path OR services.module_path =
 31authenticode.path JOIN hash ON services.path = hash.path WHERE authenticode.result != 'trusted'
 32"""
 33
 34
 35[rule]
 36author = ["Elastic"]
 37description = """
 38Detects the use of PSReflect in PowerShell scripts. Attackers leverage PSReflect as a library that enables PowerShell to
 39access win32 API functions.
 40"""
 41false_positives = ["Legitimate PowerShell scripts that make use of PSReflect to access the win32 API"]
 42from = "now-9m"
 43index = ["winlogbeat-*", "logs-windows.powershell*"]
 44language = "kuery"
 45license = "Elastic License v2"
 46name = "PowerShell PSReflect Script"
 47note = """## Triage and analysis
 48
 49### Investigating PowerShell PSReflect Script
 50
 51PowerShell 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.
 52
 53PSReflect is a library that enables PowerShell to access win32 API functions in an uncomplicated way. It also helps to create enums and structs easily—all without touching the disk.
 54
 55Although this is an interesting project for every developer and admin out there, it is mainly used in the red team and malware tooling for its capabilities.
 56
 57Detecting the core implementation of PSReflect means detecting most of the tooling that uses Windows API through PowerShell, enabling defenders to discover tools being dropped in the environment.
 58
 59> **Note**:
 60> This investigation guide uses the [Osquery Markdown Plugin](https://www.elastic.co/guide/en/security/master/invest-guide-run-osquery.html) introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide.
 61
 62#### Possible investigation steps
 63
 64- 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. The script content that may be split into multiple script blocks (you can use the field `powershell.file.script_block_id` for filtering).
 65- 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.
 66- Check for additional PowerShell and command-line logs that indicate that imported functions were run.
 67- Investigate other alerts associated with the user/host during the past 48 hours.
 68- Evaluate whether the user needs to use PowerShell to complete tasks.
 69- Examine the host for derived artifacts that indicate suspicious activities:
 70  - Analyze the script using a private sandboxed analysis system.
 71  - Observe and collect information about the following activities in both the sandbox and the alert subject host:
 72    - Attempts to contact external domains and addresses.
 73      - Use the Elastic Defend network events to determine domains and addresses contacted by the subject process by filtering by the process' `process.entity_id`.
 74      - Examine the DNS cache for suspicious or anomalous entries.
 75        - $osquery_0
 76    - Use the Elastic Defend registry events to examine registry keys accessed, modified, or created by the related processes in the process tree.
 77    - Examine the host services for suspicious or anomalous entries.
 78      - $osquery_1
 79      - $osquery_2
 80      - $osquery_3
 81  - 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.
 82- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target host after the registry modification.
 83
 84### False positive analysis
 85
 86- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.
 87
 88### Related rules
 89
 90- PowerShell Suspicious Discovery Related Windows API Functions - 61ac3638-40a3-44b2-855a-985636ca985e
 91- PowerShell Keylogging Script - bd2c86a0-8b61-4457-ab38-96943984e889
 92- PowerShell Suspicious Script with Audio Capture Capabilities - 2f2f4939-0b34-40c2-a0a3-844eb7889f43
 93- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d
 94- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad
 95- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a
 96- PowerShell Suspicious Script with Screenshot Capabilities - 959a7353-1129-4aa7-9084-30746b256a70
 97
 98### Response and remediation
 99
100- Initiate the incident response process based on the outcome of the triage.
101- Isolate the involved hosts to prevent further post-compromise behavior.
102- If the triage identified malware, search the environment for additional compromised hosts.
103  - Implement temporary network rules, procedures, and segmentation to contain the malware.
104  - Stop suspicious processes.
105  - Immediately block the identified indicators of compromise (IoCs).
106  - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
107- Remove and block malicious artifacts identified during triage.
108- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.
109- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
110- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
111- 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).
112"""
113references = [
114    "https://github.com/mattifestation/PSReflect/blob/master/PSReflect.psm1",
115    "https://github.com/atc-project/atc-data/blob/master/docs/Logging_Policies/LP_0109_windows_powershell_script_block_log.md",
116]
117risk_score = 73
118rule_id = "56f2e9b5-4803-4e44-a0a4-a52dc79d57fe"
119setup = """## Setup
120
121The 'PowerShell Script Block Logging' logging policy must be configured (Enable).
122
123Steps to implement the logging policy with Advanced Audit Configuration:

Computer Configuration > Administrative Templates > Windows PowerShell > Turn on PowerShell Script Block Logging (Enable)

1
2Steps to implement the logging policy via registry:

reg add "hklm\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1

 1"""
 2severity = "high"
 3tags = ["Domain: Endpoint", "OS: Windows", "Use Case: Threat Detection", "Tactic: Execution", "Resources: Investigation Guide", "Data Source: PowerShell Logs"]
 4timestamp_override = "event.ingested"
 5type = "query"
 6
 7query = '''
 8event.category:process and host.os.type:windows and
 9  powershell.file.script_block_text:(
10    "New-InMemoryModule" or
11    "Add-Win32Type" or
12    psenum or
13    DefineDynamicAssembly or
14    DefineDynamicModule or
15    "Reflection.TypeAttributes" or
16    "Reflection.Emit.OpCodes" or
17    "Reflection.Emit.CustomAttributeBuilder" or
18    "Runtime.InteropServices.DllImportAttribute"
19  ) and
20  not user.id : "S-1-5-18"
21'''
22
23[[rule.filters]]
24[rule.filters.meta]
25negate = true
26[rule.filters.query.wildcard."file.path"]
27"case_insensitive" = true
28"value" = "?:\\\\ProgramData\\\\MaaS360\\\\Cloud Extender\\\\AR\\\\Scripts\\\\ASModuleCommon.ps1"
29
30[[rule.threat]]
31framework = "MITRE ATT&CK"
32[[rule.threat.technique]]
33id = "T1059"
34name = "Command and Scripting Interpreter"
35reference = "https://attack.mitre.org/techniques/T1059/"
36[[rule.threat.technique.subtechnique]]
37id = "T1059.001"
38name = "PowerShell"
39reference = "https://attack.mitre.org/techniques/T1059/001/"
40
41
42[[rule.threat.technique]]
43id = "T1106"
44name = "Native API"
45reference = "https://attack.mitre.org/techniques/T1106/"
46
47
48[rule.threat.tactic]
49id = "TA0002"
50name = "Execution"
51reference = "https://attack.mitre.org/tactics/TA0002/"

Triage and analysis

Investigating PowerShell PSReflect 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.

PSReflect is a library that enables PowerShell to access win32 API functions in an uncomplicated way. It also helps to create enums and structs easily—all without touching the disk.

Although this is an interesting project for every developer and admin out there, it is mainly used in the red team and malware tooling for its capabilities.

Detecting the core implementation of PSReflect means detecting most of the tooling that uses Windows API through PowerShell, enabling defenders to discover tools being dropped in the environment.

Note: This investigation guide uses the Osquery Markdown Plugin introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide.

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. The script content that may be split into multiple script blocks (you can use the field powershell.file.script_block_id for filtering).
  • 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.
  • Check for additional PowerShell and command-line logs that indicate that imported functions were run.
  • 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.

False positive analysis

  • This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.
  • 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

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.
  • 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).

References

Related rules

to-top