76 lines
1.8 KiB
Plaintext
Raw Normal View History

2023-06-22 11:25:00 +02:00
== How to fix it in Java SE
=== Code examples
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
2023-06-22 11:25:00 +02:00
----
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
2023-06-22 11:25:00 +02:00
public void decode() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Noncompliant
}
----
2023-06-22 11:25:00 +02:00
[source,java,diff-id=2,diff-type=noncompliant]
2023-06-22 11:25:00 +02:00
----
import javax.xml.stream.XMLInputFactory;
public void decode() {
XMLInputFactory factory = XMLInputFactory.newInstance(); // Noncompliant
}
2023-06-22 11:25:00 +02:00
----
==== Compliant solution
2023-06-22 11:25:00 +02:00
For `DocumentBuilderFactory`, `SAXParserFactory`, `TransformerFactory`, and
`SchemaFactory` set `XMLConstants.FEATURE_SECURE_PROCESSING` to `true`.
[source,java,diff-id=1,diff-type=compliant]
2023-06-22 11:25:00 +02:00
----
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
public void decode() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
2023-06-22 11:25:00 +02:00
----
For `XMLInputFactory` set `SUPPORT_DTD` to `false`.
2023-06-22 11:25:00 +02:00
[source,java,diff-id=2,diff-type=compliant]
2023-06-22 11:25:00 +02:00
----
import javax.xml.stream.XMLInputFactory;
public void decode() {
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
2023-06-22 11:25:00 +02:00
----
Other combinations of settings are secure, but in general, it is recommendable
to use the approaches shown here, as they are the most clear.
2023-06-22 11:25:00 +02:00
=== How does this work?
include::../../common/fix/xxe.adoc[]
=== Going the extra mile
==== Disable entity expansion
2023-06-22 11:25:00 +02:00
Specifically for `DocumentBuilderFactory`, it is possible to disable the entity
expansion. Note, however, that this does not prevent the retrieval of external
entities.
[source, java]
----
factory.setExpandEntityReferences(false);
----