Skip to content

Commit

Permalink
Fixed - XML parsers should not be vulnerable to XXE attacks java:S2755
Browse files Browse the repository at this point in the history
  • Loading branch information
jumperchen committed Jan 15, 2024
1 parent 20d8fb6 commit 702639c
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions zcommon/src/main/java/org/zkoss/idom/transform/Transformer.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import java.util.Properties;

import javax.xml.XMLConstants;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
Expand All @@ -30,8 +31,6 @@
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.idom.DocType;
import org.zkoss.idom.Document;
import org.zkoss.idom.Element;
Expand All @@ -44,8 +43,6 @@
* @author tomyeh
*/
public class Transformer {
private static final Logger log = LoggerFactory.getLogger(Transformer.class);

/** The transformer. */
private final javax.xml.transform.Transformer _tfmr;
/** Whether to output doc-type. */
Expand All @@ -56,7 +53,7 @@ public class Transformer {
*/
public Transformer()
throws TransformerConfigurationException {
final TransformerFactory tf = TransformerFactory.newInstance();
final TransformerFactory tf = initFactory();
_tfmr = tf.newTransformer();
}
/** Constructs a transformer with a stylesheet in form of Source.
Expand All @@ -78,10 +75,30 @@ public Transformer()
*/
public Transformer(Source source)
throws TransformerConfigurationException {
final TransformerFactory tf = TransformerFactory.newInstance();
final TransformerFactory tf = initFactory();
_tfmr = source != null ? tf.newTransformer(source): tf.newTransformer();
}

// Fix XXE issue
private TransformerFactory initFactory() {
final TransformerFactory tf = TransformerFactory.newInstance();
try {
// Prevents external entity attacks (XXE)
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

// Alternatively, you can use the following settings
// These settings might be required for some Java versions
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
tf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
tf.setFeature("http://xml.org/sax/features/external-general-entities", false);
tf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (TransformerConfigurationException e) {
// Handle the potential exception here
}
return tf;
}

/** Sets whether to output the doc type.
* Default: true.
*
Expand Down

0 comments on commit 702639c

Please sign in to comment.