Prevent XXE in Ruby (Nokogiri, REXML)
To prevent XXE in Ruby, lean on Nokogiri's safe defaults: it parses without substituting external entities and without network access unless you explicitly add the NOENT, DTDLOAD or NONET-clearing options — so the rule is simply not to enable them on untrusted XML.
Nokogiri (the de-facto Ruby XML library, built on libxml2) uses a default option set that does not include NOENT or DTDLOAD and keeps NONET on, so external entities are not resolved out of the box. REXML, the pure-Ruby parser, has had entity-expansion limits since Ruby 2.x. Keep the safe defaults and never opt into entity substitution.
Secure parser configuration
Nokogiri (safe default)
require 'nokogiri'
doc = Nokogiri::XML(untrusted) # defaults: no NOENT, no DTDLOAD, NONET on
# DANGEROUS — do NOT enable these on untrusted input:
# doc = Nokogiri::XML(untrusted) { |c| c.noent.dtdload.nononet }noent substitutes entities; dtdload loads external DTDs; nononet re-enables network.
Nokogiri (explicit hardening)
doc = Nokogiri::XML(untrusted) do |config|
config.strict.nonet # strict parsing, network disabled
endREXML
require 'rexml/document'
# REXML enforces entity-expansion limits by default (Ruby 2.x+). Avoid raising
# REXML::Security.entity_expansion_limit / entity_expansion_text_limit.
doc = REXML::Document.new(untrusted)Common pitfalls that re-introduce XXE
- Passing a block that enables noent, dtdload or clears nonet on Nokogiri.
- Using Nokogiri::XML::ParseOptions::DEFAULT_XML and then OR-ing in NOENT.
- Lowering or disabling REXML's entity-expansion limits.
- Trusting that older Nokogiri/libxml builds share today's defaults.
Verifying the fix
Parse a classic file-read payload; with defaults, &xxe; is not substituted and no file content appears. Submit a blind OOB payload and confirm no outbound request is made. Audit for any Nokogiri block enabling noent/dtdload/nononet.