Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions core/src/main/java/org/codelibs/saml2/core/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
*
* <p>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.</p>
*
* @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
*
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\""
+ " ID=\"l1\" Version=\"2.0\" IssueInstant=\"2026-01-01T00:00:00Z\"><samlp:Extensions>");
for (int i = 0; i < depth; i++) {
xml.append("<x>");
}
for (int i = 0; i < depth; i++) {
xml.append("</x>");
}
xml.append("</samlp:Extensions></samlp:LogoutRequest>");
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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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("<root>");
for (int i = 0; i < 5000; i++) {
wide.append("<x><y/></x>");
}
assertNotNull(Util.loadXML(wide.append("</root>").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("<x>");
}
for (int i = 0; i < depth; i++) {
sb.append("</x>");
}
return sb.toString();
}

@Test
public void testValidateXMLBadFormat() throws Exception {
String metadataUnloaded = "<xml><EntityDescriptor>";
Expand Down
Loading