Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar: Disable XML external entity (XXE) processing

Tags:

java

sonarqube

I am using javax.xml.validation.Validator to validate my xml as below

        private final Validator validator;
        ...

        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        Schema schema = factory.newSchema(new File(getResource(path)));
        validator = schema.newValidator();
        validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

Any idea why sonar says this code is noncompliant?

like image 772
Michał Kaliszewski Avatar asked Oct 25 '25 20:10

Michał Kaliszewski


1 Answers

You have to set XMLConstants.ACCESS_EXTERNAL_DTD and XMLConstants.ACCESS_EXTERNAL_SCHEMA to "".

Below code will not give any violation with SonarLint and SonarQube.

private Validator validator;
...
    
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema(new File(getResource(path)));
validator = schema.newValidator();
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

Then, Block external entities where you are validating it. For example, If you are using STAX parser. Then set XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES and XMLInputFactory.SUPPORT_DTD to False.

XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
validator.validate(new StAXSource(factory.createXMLStreamReader(inputStream)));

If you are using sonarLint then clean your caches by deleting target folder of the project.

For more info: https://rules.sonarsource.com/java/RSPEC-2755

like image 68
Krishna Kumar Singh Avatar answered Oct 27 '25 09:10

Krishna Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!