cwe-91-xml-injection
CWE-91 XML Injection
Description
XML Injection
Reference: https://cwe.mitre.org/data/definitions/91.html
OWASP Category: A03:2021 – Injection
Vulnerable Pattern
❌ Example 1: Vulnerable Pattern
// VULNERABLE: User input directly in XML
String xml = "<user><name>" + userName + "</name></user>";
Why it's vulnerable: This pattern is vulnerable to XML Injection
Deterministic Fix
✅ Secure Implementation: Secure Implementation
// SECURE: Use XML library or escape special characters
import org.apache.commons.text.StringEscapeUtils;
String safeName = StringEscapeUtils.escapeXml11(userName);
String xml = "<user><name>" + safeName + "</name></user>";
// Better: Use JAXB or DOM API
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("user");
Element name = doc.createElement("name");
name.setTextContent(userName); // Auto-escapes
root.appendChild(name);
Why it's secure: Implements proper protection against XML Injection
Detection Pattern
Look for these patterns in your codebase:
# Find XML string concatenation
grep -rn "\"<.*>\".*+" --include="*.java" | grep -v "//"
Remediation Steps
-
Use XML libraries that auto-escape content (JAXB, DOM)
-
Escape XML special characters (<>&"') in user input
-
Use setTextContent() instead of string concatenation
Key Imports
import org.apache.commons.text.StringEscapeUtils;
import javax.xml.parsers.DocumentBuilder;
Verification
After remediation:
-
Run SAST scanner to confirm vulnerability is resolved
-
Review all instances of the vulnerable pattern
-
Add unit tests that verify the secure implementation
-
Check for similar patterns in related code
Trigger Examples
Fix CWE-91 vulnerability
Resolve XML Injection issue
Secure this Java code against xml injection
SAST reports CWE-91
Common Vulnerable Locations
| Layer | Files | Patterns |
|---|
| Controller | *Controller.java | User input handling |
| Service | *Service.java | Business logic |
| Repository | *Repository.java | Data access |
References
Source: Generated by Java CWE Security Skills Generator Last Updated: 2026-03-07