How to prevent XSS attack while parsing XML

Attack

XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.
Risk 1: Expose local file content (XXE: XML eXternal Entity)
 ]>
&xxe;
Risk 2: Denial of service (XEE: Xml Entity Expansion)

 
 
 
 
[...]
 
]>
&lol9;

Solution

In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code.
Vulnerable Code:
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

parser.parse(inputStream, customHandler);

The following snippets show two available solutions. You can set one feature or both.
Solution using "Secure processing" mode:
This setting will protect you against Denial of Service attack and remote file access.
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
SAXParser parser = spf.newSAXParser();

parser.parse(inputStream, customHandler);
Solution disabling DTD:
By disabling DTD, almost all XXE attacks will be prevented.


SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser parser = spf.newSAXParser();

parser.parse(inputStream, customHandler);

Comments

Popular posts from this blog

Let's try to build scrum masters/project managers/software architects/even a company with training AI models

TCP Ports list

Problem Solving: Allotment calculator