From 80a54d08c943477c5d3eee5b077d5b65c1da20e5 Mon Sep 17 00:00:00 2001 From: Mike Angstadt Date: Sat, 4 Nov 2023 10:51:29 -0400 Subject: [PATCH] Improve XML XXE protection https://rules.sonarsource.com/java/RSPEC-2755/ --- src/main/java/biweekly/io/xml/XCalDocument.java | 5 ++++- src/main/java/biweekly/util/XmlUtils.java | 10 +++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/biweekly/io/xml/XCalDocument.java b/src/main/java/biweekly/io/xml/XCalDocument.java index 5c24754b..cf11c622 100644 --- a/src/main/java/biweekly/io/xml/XCalDocument.java +++ b/src/main/java/biweekly/io/xml/XCalDocument.java @@ -471,7 +471,10 @@ public void write(Writer writer, Integer indent, String xmlVersion) throws Trans public void write(Writer writer, Map outputProperties) throws TransformerException { Transformer transformer; try { - transformer = TransformerFactory.newInstance().newTransformer(); + TransformerFactory factory = TransformerFactory.newInstance(); + XmlUtils.applyXXEProtection(factory); + + transformer = factory.newTransformer(); } catch (TransformerConfigurationException e) { //should never be thrown because we're not doing anything fancy with the configuration throw new RuntimeException(e); diff --git a/src/main/java/biweekly/util/XmlUtils.java b/src/main/java/biweekly/util/XmlUtils.java index e2188d07..a3a6814e 100644 --- a/src/main/java/biweekly/util/XmlUtils.java +++ b/src/main/java/biweekly/util/XmlUtils.java @@ -202,6 +202,8 @@ public static void applyXXEProtection(DocumentBuilderFactory factory) { * @see * XXE Cheat Sheet + * @see SonarLint + * 2755 */ public static void applyXXEProtection(TransformerFactory factory) { //@formatter:off @@ -209,6 +211,9 @@ public static void applyXXEProtection(TransformerFactory factory) { //XMLConstants.ACCESS_EXTERNAL_DTD (Java 7 only) "http://javax.xml.XMLConstants/property/accessExternalDTD", + //XMLConstants.ACCESS_EXTERNAL_SCHEMA (Java 7 only) + "http://javax.xml.XMLConstants/property/accessExternalSchema", + //XMLConstants.ACCESS_EXTERNAL_STYLESHEET (Java 7 only) "http://javax.xml.XMLConstants/property/accessExternalStylesheet" }; @@ -283,7 +288,10 @@ public static void toWriter(Node node, Writer writer) throws TransformerExceptio */ public static void toWriter(Node node, Writer writer, Map outputProperties) throws TransformerException { try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); + TransformerFactory factory = TransformerFactory.newInstance(); + applyXXEProtection(factory); + + Transformer transformer = factory.newTransformer(); for (Map.Entry property : outputProperties.entrySet()) { try { transformer.setOutputProperty(property.getKey(), property.getValue());