Reputation: 81
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?
Upvotes: 4
Views: 9200
Reputation: 162
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
Upvotes: 4