Merge pull request #1072 from mechko/1071-xml-tostring-name-validation

#1071: reject invalid XML element names in XML.toString (CWE-91)
This commit is contained in:
Sean Leary
2026-08-24 12:22:44 -05:00
committed by GitHub
2 changed files with 65 additions and 0 deletions
+36
View File
@@ -565,6 +565,42 @@ public class XMLTest {
assertTrue("Illegal@node",result.contains("<Illegal@node>someValue2</Illegal@node>"));
}
/**
* A JSON key containing XML metacharacters must not be emitted as a raw
* tag name, since doing so allows the key to break out of its element and
* inject sibling structure into the output (CWE-91, issue #1071).
*/
@Test
public void toStringRejectsElementInjectionInKey()
{
JSONObject jo = new JSONObject(
"{\"a/><injected>evil</injected><a\":\"\"}");
try {
XML.toString(jo, "root");
fail("expected JSONException for key containing XML metacharacters");
} catch (JSONException expected) {
// expected: '/', '<', '>' are rejected in element names
}
// caller-supplied tagName is checked too
try {
XML.toString(new JSONObject(), "bad<tag");
fail("expected JSONException for tagName containing '<'");
} catch (JSONException expected) {
// expected: '<' is rejected in element names
}
// each metacharacter is rejected individually
for (char c : new char[] {'<', '>', '&', '"', '\'', '/'}) {
try {
XML.toString(new JSONObject().put("a" + c + "b", "v"));
fail("expected JSONException for key containing '" + c + "'");
} catch (JSONException expected) {
// expected
}
}
}
/**
* JSONObject with NULL value, to XML.toString()
*/