Nokogiri, a popular open source XML and HTML library for Ruby, was found to have a critical security vulnerability affecting versions before 1.13.6. The issue, tracked by CVE-2022-29181, can lead to illegal memory access errors (segfault) or reads from unrelated memory, potentially causing crashes or leaking sensitive information. The vulnerability is fixed in Nokogiri version 1.13.6. In this post, we will discuss in detail the cause of the vulnerability, provide a code snippet to showcase the issue, and explain how to apply the patch.

Details

The vulnerability in Nokogiri stems from improper type checking of inputs into the XML and HTML4 SAX parsers. When the parser processes specially crafted, untrusted inputs, it can get confused and access memory it's not meant to. This behavior may not only cause the application to crash but also expose sensitive information from the accessed memory.

Code Snippet

Below is a simplified code snippet that demonstrates the unsafe parsing behavior in Nokogiri prior to version 1.13.6, which might result in a segfault:

require 'nokogiri'

malicious_input = <<~EOM
  <!-- Malicious code here causing a segfault -->
EOM

doc = Nokogiri::XML::SAX::Parser.new.process(malicious_input)

To fix this vulnerability, Nokogiri released version 1.13.6, which properly type-checks all inputs into the XML and HTML4 SAX parsers. Updating to this version is highly recommended.

To update Nokogiri to version 1.13.6 and eliminate the vulnerability, run the following command

gem update nokogiri --version 1.13.6

In case you cannot update to version 1.13.6 immediately, you can implement the following workaround

Before inputting untrusted data into the Nokogiri parser, ensure the data is of the String class by calling the #to_s method or an equivalent. This would prevent the illegal memory access behavior.

require 'nokogiri'

malicious_input = <<~EOM.to_s
  <!-- Malicious code here that would cause a segfault -->
EOM

doc = Nokogiri::XML::SAX::Parser.new.process(malicious_input)

1. Nokogiri GitHub issue detailing the vulnerability
2. Nokogiri's official documentation
3. CVE-2022-29181 entry on the MITRE CVE database

Conclusion

Developers using Nokogiri should update to version 1.13.6 immediately to protect their applications from segfaults, crashes, and potential information leaks. If updating is not possible right away, the provided workaround should be employed to minimize the risk. Always be cautious when handling untrusted data and ensure that the input processing adheres to best security practices.

Timeline

Published on: 05/20/2022 19:15:00 UTC
Last modified on: 08/15/2022 11:20:00 UTC