CVE-2021-23463 (published 2021-12-10T20:15Z)

The package com.h2database:h2 from 1.4.198 and before 2.0.202 are vulnerable to XML External Entity (XXE) Injection via the org.h2.jdbc.JdbcSQLXML class object, when it receives parsed string data from org.h2.jdbc.JdbcResultSet.getSQLXML() method. If it executes the getSource() method when the parameter is DOMSource.class it will trigger the vulnerability.

Severity: MEDIUM
CVSS v2 base score: 6.4 (AV:N/AC:L/Au:N/C:P/I:N/A:P)
CVSS v3 base score: 9.1, CRITICAL (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:H)

Weakness information:
cwe_id: CWE-611
cwe_name: Improper Restriction of XML External Entity Reference
description: The product processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
extended_description: 
            XML documents optionally contain a Document Type Definition (DTD), which, among other features, enables the definition of XML entities. It is possible to define an entity by providing a substitution string in the form of a URI. The XML parser can access the contents of this URI and embed these contents back into the XML document for further processing.
            By submitting an XML file that defines an external entity with a file:// URI, an attacker can cause the processing application to read the contents of a local file. For example, a URI such as "file:///c:/winnt/win.ini" designates (in Windows) the file C:\Winnt\win.ini, or file:///etc/passwd designates the password file in Unix-based systems. Using URIs with other schemes such as http://, the attacker can force the application to make outgoing requests to servers that the attacker cannot reach directly, which can be used to bypass firewall restrictions or hide the source of attacks such as port scanning.
            Once the content of the URI is read, it is fed back into the application that is processing the XML. This application may echo back the data (e.g. in an error message), thereby exposing the file contents.
         
         

Fix information:
repo_url: https://github.com/h2database/h2database
commit_details: repo_url: https://github.com/h2database/h2database
author: Andrei Tokar
author_date: 2021-10-30 13:19:57-04:00
msg: fix for #3195 CQLXML XXE vulnerability
repository: repo_url: https://github.com/h2database/h2database
repo_name: h2database/h2database
description: H2 is an embeddable RDBMS written in Java.
repo_language: Java
owner: h2database
file_changes: filename: JdbcSQLXML.java
change_type: ModificationType.MODIFY
diff: @@ -16,7 +16,11 @@
 import java.io.Writer;
 import java.sql.SQLException;
 import java.sql.SQLXML;
+import java.util.HashMap;
+import java.util.Map;
 
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLOutputFactory;
@@ -24,6 +28,7 @@
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.URIResolver;
 import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.sax.SAXResult;
@@ -39,13 +44,29 @@
 import org.h2.message.TraceObject;
 import org.h2.value.Value;
 import org.w3c.dom.Node;
+import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * Represents a SQLXML value.
  */
 public final class JdbcSQLXML extends JdbcLob implements SQLXML {
 
+    private static final Map<String,Boolean> secureFeatureMap = new HashMap<>();
+    private static final EntityResolver NOOP_ENTITY_RESOLVER = (publicId, systemId) -> new InputSource(new StringReader(""));
+    private static final URIResolver NOOP_URI_RESOLVER = (href, base) -> new StreamSource(new StringReader(""));
+
+    static {
+        secureFeatureMap.put(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+        secureFeatureMap.put("http://apache.org/xml/features/disallow-doctype-decl", true);
+        secureFeatureMap.put("http://xml.org/sax/features/external-general-entities", false);
+        secureFeatureMap.put("http://xml.org/sax/features/external-parameter-entities", false);
+        secureFeatureMap.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
+    }
+
     private DOMResult domResult;
 
     /**
@@ -107,15 +128,41 @@ public <T extends Source> T getSource(Class<T> sourceClass) throws SQLException
                         "getSource(" + (sourceClass != null ? sourceClass.getSimpleName() + ".class" : "null") + ')');
             }
             checkReadable();
+            // According to https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
             if (sourceClass == null || sourceClass == DOMSource.class) {
                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-                return (T) new DOMSource(dbf.newDocumentBuilder().parse(new InputSource(value.getInputStream())));
+                for (Map.Entry<String,Boolean> entry : secureFeatureMap.entrySet()) {
+                    try {
+                        dbf.setFeature(entry.getKey(), entry.getValue());
+                    } catch (Exception ignore) {/**/}
+                }
+                dbf.setXIncludeAware(false);
+                dbf.setExpandEntityReferences(false);
+                dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
+                DocumentBuilder db = dbf.newDocumentBuilder();
+                db.setEntityResolver(NOOP_ENTITY_RESOLVER);
+                return (T) new DOMSource(db.parse(new InputSource(value.getInputStream())));
             } else if (sourceClass == SAXSource.class) {
-                return (T) new SAXSource(new InputSource(value.getInputStream()));
+                XMLReader reader = XMLReaderFactory.createXMLReader();
+                for (Map.Entry<String,Boolean> entry : secureFeatureMap.entrySet()) {
+                    try {
+                        reader.setFeature(entry.getKey(), entry.getValue());
+                    } catch (Exception ignore) {/**/}
+                }
+                reader.setEntityResolver(NOOP_ENTITY_RESOLVER);
+                return (T) new SAXSource(reader, new InputSource(value.getInputStream()));
             } else if (sourceClass == StAXSource.class) {
                 XMLInputFactory xif = XMLInputFactory.newInstance();
+                xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
+                xif.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+                xif.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
                 return (T) new StAXSource(xif.createXMLStreamReader(value.getInputStream()));
             } else if (sourceClass == StreamSource.class) {
+                TransformerFactory tf = TransformerFactory.newInstance();
+                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
+                tf.setURIResolver(NOOP_URI_RESOLVER);
+                tf.newTransformer().transform(new StreamSource(value.getInputStream()), new SAXResult(new DefaultHandler()));
                 return (T) new StreamSource(value.getInputStream());
             }
             throw unsupported(sourceClass.getName());
@@ -165,7 +212,7 @@ public <T extends Result> T setResult(Class<T> resultClass) throws SQLException
         try {
             if (isDebugEnabled()) {
                 debugCode(
-                        "getSource(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')');
+                        "setResult(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')');
             }
             checkEditable();
             if (resultClass == null || resultClass == DOMResult.class) {

programming_language: Java