| name | secure-xml-parsing |
| description | Generate secure XML parsing code. Enforces secure parsing of XML content. Invoke when writing any XML parsing related code. |
| allowed-tools | Read Grep Glob |
| metadata | {"category":"security"} |
Secure XML parsing Code Generation Rules
Apply all rules below when generating or reviewing any code related to xml content parsing.
1. XXE / DTD / XInclude / Internal Entity Prevention (CRITICAL)
- ALWAYS disable resolution of Document Type Definition (DTD).
- ALWAYS disable resolution of XML External Entity.
- ALWAYS disable expansion/replacement of XML Internal Entity.
- ALWAYS disable XInclude support.
- ALWAYS limit the size of the XML input to prevent memory exhaustion (reject inputs larger than 1 MB).
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("data.xml"));
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.file.*;
int MAX_XML_SIZE_BYTES = 1 * 1024 * 1024;
byte[] xmlBytes = Files.readAllBytes(Path.of("data.xml"));
if (xmlBytes.length > MAX_XML_SIZE_BYTES) {
throw new IOException("XML input exceeds maximum allowed size of 1 MB");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setExpandEntityReferences(false);
factory.setXIncludeAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xmlBytes));
2. Output Checklist
Before finalizing generated code, verify:
References