From a7176a3ba08dc26a784b5d53abdd178ca532a503 Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sun, 15 Nov 2026 23:06:50 +0900 Subject: [PATCH] fix: refuse a document whose elements are nested too deeply A SAML message is parsed before its signature or schema is checked, and the DOM is then walked recursively (Element#normalize in the Response and LogoutRequest constructors, importNode, the canonicalization of a signature). A document nested thousands of levels deep fits in a short deflated request, and it ended in a StackOverflowError that catch (Exception) does not see, so it left the library. Util.parseXML now walks the parsed tree without recursion and throws XMLParsingException for a document nested more than 100 levels deep. A SAML message is a few dozen levels deep at most. loadXML answers such a document with null, as it does for any other document it cannot parse. --- .../org/codelibs/saml2/core/util/Util.java | 44 +++++++++++++++++++ .../core/test/logout/LogoutRequestTest.java | 26 +++++++++++ .../saml2/core/test/util/UtilsTest.java | 44 +++++++++++++++++++ 3 files changed, 114 insertions(+) diff --git a/core/src/main/java/org/codelibs/saml2/core/util/Util.java b/core/src/main/java/org/codelibs/saml2/core/util/Util.java index 7f2268f..671cdcd 100644 --- a/core/src/main/java/org/codelibs/saml2/core/util/Util.java +++ b/core/src/main/java/org/codelibs/saml2/core/util/Util.java @@ -360,6 +360,49 @@ public static Document convertStringToDocument(final String xmlStr) { } } + /** The deepest element nesting accepted in a parsed document. A SAML message is a few dozen levels deep at most. */ + private static final int MAX_XML_DEPTH = 100; + + /** + * Refuses a document whose elements are nested deeper than {@link #MAX_XML_DEPTH}. + * + *

The DOM is walked recursively later on ({@code Element#normalize}, {@code importNode}, the + * canonicalization of a signature), and the document is parsed before any signature or schema check, + * so a few hundred bytes of nested elements sent to an anonymous endpoint would end in a + * {@link StackOverflowError} that no {@code catch (Exception)} sees. The check walks the tree without + * recursion.

+ * + * @param doc the parsed document + * @throws XMLParsingException if the document is nested too deeply + */ + private static void checkNestingDepth(final Document doc) { + final Element root = doc.getDocumentElement(); + if (root == null) { + return; + } + Node node = root; + int depth = 1; + while (true) { + if (depth > MAX_XML_DEPTH && node.getNodeType() == Node.ELEMENT_NODE) { + throw new XMLParsingException("The document is nested more than " + MAX_XML_DEPTH + " levels deep.", null); + } + final Node child = node.getFirstChild(); + if (child != null) { + node = child; + depth++; + continue; + } + while (node != root && node.getNextSibling() == null) { + node = node.getParentNode(); + depth--; + } + if (node == root) { + return; + } + node = node.getNextSibling(); + } + } + /** * Parse an XML from input source to a Document object * @@ -400,6 +443,7 @@ public static Document parseXML(final InputSource inputSource) { final XMLErrorAccumulatorHandler errorAccumulator = new XMLErrorAccumulatorHandler(); builder.setErrorHandler(errorAccumulator); final Document doc = builder.parse(inputSource); + checkNestingDepth(doc); // Loop through the doc and tag every element with an ID attribute // as an XML ID node. diff --git a/core/src/test/java/org/codelibs/saml2/core/test/logout/LogoutRequestTest.java b/core/src/test/java/org/codelibs/saml2/core/test/logout/LogoutRequestTest.java index 4dc96f7..69add84 100644 --- a/core/src/test/java/org/codelibs/saml2/core/test/logout/LogoutRequestTest.java +++ b/core/src/test/java/org/codelibs/saml2/core/test/logout/LogoutRequestTest.java @@ -1216,4 +1216,30 @@ protected String postProcessXml(String logoutRequestXml, LogoutRequestParams par }; assertEquals("changed", logoutRequest.getLogoutRequestXml()); } + + /** + * Tests the constructor + * Case: a deflated request whose elements are nested thousands of levels deep, which used to + * overflow the stack in Element#normalize before any signature or schema check + */ + @Test + public void testDeeplyNestedRequestIsRefusedWithoutAnError() throws Exception { + Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); + settings.setStrict(true); + int depth = 20000; + StringBuilder xml = new StringBuilder(""); + for (int i = 0; i < depth; i++) { + xml.append(""); + } + for (int i = 0; i < depth; i++) { + xml.append(""); + } + xml.append(""); + String encoded = Util.deflatedBase64encoded(xml.toString()); + assertTrue("the request must stay small enough for a GET", encoded.length() < 1000); + + LogoutRequest logoutRequest = new LogoutRequest(settings, newHttpRequest("http://stuff.com/endpoints/endpoints/sls.php", encoded)); + assertFalse(logoutRequest.isValid()); + } } diff --git a/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java b/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java index b884845..f5a5b18 100644 --- a/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java +++ b/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java @@ -259,6 +259,50 @@ public void testSanitizeForLogOfTheSignatureAlgorithmTheSecurityLibraryQuotes() assertFalse(Util.validateSignNode(signature, null, "00", "sha256")); } + /** + * Tests the loadXML method + * Case: element nesting at and beyond the limit + * + * @see org.codelibs.saml2.core.util.Util#loadXML + */ + @Test + public void testLoadXMLRefusesDeeplyNestedElements() { + assertNotNull(Util.loadXML(nested(100))); + assertNull(Util.loadXML(nested(101))); + // far deeper than the stack of a thread can take when the tree is walked recursively + assertNull(Util.loadXML(nested(50000))); + // siblings are not nesting + StringBuilder wide = new StringBuilder(""); + for (int i = 0; i < 5000; i++) { + wide.append(""); + } + assertNotNull(Util.loadXML(wide.append("").toString())); + } + + /** + * Tests the parseXML method + * Case: the refusal is reported as a parsing failure + * + * @see org.codelibs.saml2.core.util.Util#parseXML + */ + @Test + public void testParseXMLReportsDeeplyNestedElements() { + expectedEx.expect(XMLParsingException.class); + expectedEx.expectMessage("nested more than 100 levels"); + Util.parseXML(new org.xml.sax.InputSource(new java.io.StringReader(nested(101)))); + } + + private static String nested(int depth) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < depth; i++) { + sb.append(""); + } + for (int i = 0; i < depth; i++) { + sb.append(""); + } + return sb.toString(); + } + @Test public void testValidateXMLBadFormat() throws Exception { String metadataUnloaded = "";