This is an automated email from the ASF dual-hosted git repository.

robertlazarski pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/axis-axis2-java-core.git

commit 3436befc59ac845036a14df01f09bbaceedf7f73
Author: Robert Lazarski <[email protected]>
AuthorDate: Fri Nov 13 05:20:00 2026 -1000

    Harden identity transforms and codegen DOM parsing
    
    Add XMLUtils.newSecureTransformerFactory() and use it where JAX-WS and
    SAAJ copy a caller-supplied Source, since an identity transform parses a
    StreamSource or SAXSource with the transformer's own unhardened parser.
    The type-mapping and custom-schema loaders now use the secure DOM factory.
    The never-read SAX parser pool in XMLUtils becomes deprecated no-ops.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../codegen/extension/TypeMapperExtension.java     |   4 +-
 .../apache/axis2/datasource/SourceDataSource.java  |   4 +-
 .../axis2/jaxws/handler/LogicalMessageImpl.java    |   3 +-
 .../apache/axis2/jaxws/utility/ConvertUtils.java   |   4 +-
 .../java2wsdl/DefaultSchemaGenerator.java          |   4 +-
 .../kernel/src/org/apache/axis2/util/XMLUtils.java | 110 +++++++++------------
 .../axis2/util/XMLUtilsSecureTransformerTest.java  | 101 +++++++++++++++++++
 .../src/org/apache/axis2/saaj/SOAPPartImpl.java    |   4 +-
 8 files changed, 156 insertions(+), 78 deletions(-)

diff --git 
a/modules/codegen/src/org/apache/axis2/wsdl/codegen/extension/TypeMapperExtension.java
 
b/modules/codegen/src/org/apache/axis2/wsdl/codegen/extension/TypeMapperExtension.java
index 037b1bd555..a3ea30b0ec 100644
--- 
a/modules/codegen/src/org/apache/axis2/wsdl/codegen/extension/TypeMapperExtension.java
+++ 
b/modules/codegen/src/org/apache/axis2/wsdl/codegen/extension/TypeMapperExtension.java
@@ -25,6 +25,7 @@ import org.apache.axis2.wsdl.databinding.DefaultTypeMapper;
 import org.apache.axis2.wsdl.databinding.TypeMapper;
 import org.apache.axis2.wsdl.databinding.CTypeMapper;
 import org.apache.axis2.wsdl.i18n.CodegenMessages;
+import org.apache.axis2.util.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -134,8 +135,7 @@ public class TypeMapperExtension implements 
CodeGenExtension {
             throws CodeGenerationException {
         try {
             DocumentBuilderFactory documentBuilderFactory
-                    = DocumentBuilderFactory.newInstance();
-            documentBuilderFactory.setNamespaceAware(true);
+                    = XMLUtils.newSecureDocumentBuilderFactory();
             DocumentBuilder documentBuilder =
                     documentBuilderFactory.newDocumentBuilder();
             return documentBuilder.parse(configuration.getTypeMappingFile());
diff --git 
a/modules/jaxws/src/org/apache/axis2/datasource/SourceDataSource.java 
b/modules/jaxws/src/org/apache/axis2/datasource/SourceDataSource.java
index f69ba8ffc8..ac0ce33624 100644
--- a/modules/jaxws/src/org/apache/axis2/datasource/SourceDataSource.java
+++ b/modules/jaxws/src/org/apache/axis2/datasource/SourceDataSource.java
@@ -22,6 +22,7 @@ package org.apache.axis2.datasource;
 import org.apache.axiom.om.OMException;
 import org.apache.axiom.om.ds.AbstractPullOMDataSource;
 import org.apache.axiom.om.util.StAXUtils;
+import org.apache.axis2.util.XMLUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
@@ -30,7 +31,6 @@ import javax.xml.stream.XMLStreamReader;
 import javax.xml.transform.Result;
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.stream.StreamResult;
 import javax.xml.transform.stream.StreamSource;
 import java.io.ByteArrayInputStream;
@@ -82,7 +82,7 @@ public class SourceDataSource extends 
AbstractPullOMDataSource {
             } else {
                 ByteArrayOutputStream out = new ByteArrayOutputStream();
                 Result result = new StreamResult(out);
-                Transformer transformer = 
TransformerFactory.newInstance().newTransformer();
+                Transformer transformer = 
XMLUtils.newSecureTransformerFactory().newTransformer();
                 transformer.transform(data, result);
                 bytes = out.toByteArray();
             }            
diff --git 
a/modules/jaxws/src/org/apache/axis2/jaxws/handler/LogicalMessageImpl.java 
b/modules/jaxws/src/org/apache/axis2/jaxws/handler/LogicalMessageImpl.java
index 023ce9102c..3bf6d49a88 100644
--- a/modules/jaxws/src/org/apache/axis2/jaxws/handler/LogicalMessageImpl.java
+++ b/modules/jaxws/src/org/apache/axis2/jaxws/handler/LogicalMessageImpl.java
@@ -47,7 +47,6 @@ import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerConfigurationException;
 import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
@@ -192,7 +191,7 @@ public class LogicalMessageImpl implements LogicalMessage {
                 
         if (Source.class.isAssignableFrom(content.getClass())) {
             try {
-                Transformer trans = 
TransformerFactory.newInstance().newTransformer();
+                Transformer trans = 
XMLUtils.newSecureTransformerFactory().newTransformer();
                         
                 // First we have to get the content out of the original
                 // Source object so we can build the cache from there.
diff --git a/modules/jaxws/src/org/apache/axis2/jaxws/utility/ConvertUtils.java 
b/modules/jaxws/src/org/apache/axis2/jaxws/utility/ConvertUtils.java
index 71992f5830..694d7e408b 100644
--- a/modules/jaxws/src/org/apache/axis2/jaxws/utility/ConvertUtils.java
+++ b/modules/jaxws/src/org/apache/axis2/jaxws/utility/ConvertUtils.java
@@ -21,6 +21,7 @@ package org.apache.axis2.jaxws.utility;
 
 import org.apache.axis2.jaxws.ExceptionFactory;
 import org.apache.axis2.jaxws.i18n.Messages;
+import org.apache.axis2.util.XMLUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
@@ -29,7 +30,6 @@ import javax.imageio.ImageIO;
 import javax.xml.transform.Result;
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.stream.StreamResult;
 import javax.xml.transform.stream.StreamSource;
 import jakarta.xml.ws.WebServiceException;
@@ -221,7 +221,7 @@ public class ConvertUtils {
                 }
                 ByteArrayOutputStream out = new ByteArrayOutputStream();
                 Result result = new StreamResult(out);
-                Transformer transformer = 
TransformerFactory.newInstance().newTransformer();
+                Transformer transformer = 
XMLUtils.newSecureTransformerFactory().newTransformer();
                 transformer.transform((Source) arg, result);
                 byte[] bytes = out.toByteArray();
                 return bytes;
diff --git 
a/modules/kernel/src/org/apache/axis2/description/java2wsdl/DefaultSchemaGenerator.java
 
b/modules/kernel/src/org/apache/axis2/description/java2wsdl/DefaultSchemaGenerator.java
index 979d69e823..92155d6e9f 100644
--- 
a/modules/kernel/src/org/apache/axis2/description/java2wsdl/DefaultSchemaGenerator.java
+++ 
b/modules/kernel/src/org/apache/axis2/description/java2wsdl/DefaultSchemaGenerator.java
@@ -32,6 +32,7 @@ import org.apache.axis2.jaxrs.JAXRSModel;
 import org.apache.axis2.jaxrs.JAXRSUtils;
 import org.apache.axis2.util.JavaUtils;
 import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.axis2.util.XMLUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.ws.commons.schema.XmlSchema;
@@ -228,8 +229,7 @@ public class DefaultSchemaGenerator implements 
Java2WSDLConstants, SchemaGenerat
     private void loadCustomSchemaFile() {
         if (customSchemaLocation != null) {
             try {
-                DocumentBuilderFactory documentBuilderFactory = 
DocumentBuilderFactory.newInstance();
-                documentBuilderFactory.setNamespaceAware(true);
+                DocumentBuilderFactory documentBuilderFactory = 
XMLUtils.newSecureDocumentBuilderFactory();
                 Document doc = 
documentBuilderFactory.newDocumentBuilder().parse(new 
File(customSchemaLocation));
                 XmlSchema schema = xmlSchemaCollection.read(doc, null);
                 schemaMap.put(schema.getTargetNamespace(), schema);
diff --git a/modules/kernel/src/org/apache/axis2/util/XMLUtils.java 
b/modules/kernel/src/org/apache/axis2/util/XMLUtils.java
index b30ace36c3..961265ee68 100644
--- a/modules/kernel/src/org/apache/axis2/util/XMLUtils.java
+++ b/modules/kernel/src/org/apache/axis2/util/XMLUtils.java
@@ -36,15 +36,16 @@ import org.xml.sax.ErrorHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException;
-import org.xml.sax.XMLReader;
 
+import javax.xml.XMLConstants;
 import javax.xml.namespace.QName;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.stream.XMLStreamException;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerFactory;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -56,65 +57,26 @@ import java.net.MalformedURLException;
 import java.net.ProtocolException;
 import java.net.URL;
 import java.net.URLConnection;
-import java.util.Stack;
 
 
 public class XMLUtils {
     public static final String charEncoding = "ISO-8859-1";
-    private static final String saxParserFactoryProperty =
-            "javax.xml.parsers.SAXParserFactory";
 
     private static DocumentBuilderFactory dbf = getDOMFactory();
-    private static SAXParserFactory saxFactory;
-    private static Stack saxParsers = new Stack();
 
     private static String empty = "";
     private static ByteArrayInputStream bais = new 
ByteArrayInputStream(empty.getBytes());
 
-    static {
-        // Initialize SAX Parser factory defaults
-        initSAXFactory(null, true, false);
-    }
-
     /**
-     * Initializes the SAX parser factory.
+     * Formerly configured a pooled SAX parser factory that nothing in Axis2 
ever
+     * handed out.
      *
-     * @param factoryClassName The (optional) class name of the desired
-     *                         SAXParserFactory implementation. Will be
-     *                         assigned to the system property
-     *                         <b>javax.xml.parsers.SAXParserFactory</b>
-     *                         unless this property is already set.
-     *                         If <code>null</code>, leaves current setting
-     *                         alone.
-     * @param namespaceAware   true if we want a namespace-aware parser
-     * @param validating       true if we want a validating parser
+     * @deprecated has no effect; use a hardened parser at the point of use 
instead
      */
+    @Deprecated
     public static void initSAXFactory(String factoryClassName,
                                       boolean namespaceAware,
                                       boolean validating) {
-        if (factoryClassName != null) {
-            try {
-                saxFactory = (SAXParserFactory) 
Loader.loadClass(factoryClassName).
-                        newInstance();
-                /*
-                 * Set the system property only if it is not already set to
-                 * avoid corrupting environments in which Axis is embedded.
-                 */
-                if (System.getProperty(saxParserFactoryProperty) == null) {
-                    System.setProperty(saxParserFactoryProperty,
-                                       factoryClassName);
-                }
-            } catch (Exception e) {
-                saxFactory = SAXParserFactory.newInstance();
-            }
-        } else {
-            saxFactory = SAXParserFactory.newInstance();
-        }
-        saxFactory.setNamespaceAware(namespaceAware);
-        saxFactory.setValidating(validating);
-
-        // Discard existing parsers
-        saxParsers.clear();
     }
 
     /**
@@ -142,6 +104,39 @@ public class XMLUtils {
         return dbf;
     }
 
+    /**
+     * A TransformerFactory that refuses external DTDs, external entities and
+     * external stylesheets.
+     * <p>
+     * Use this for any transform whose Source may come from outside Axis2. An
+     * identity transform parses a StreamSource, or a SAXSource without its own
+     * XMLReader, with the transformer's internal parser, which ignores every
+     * parser hardening applied elsewhere. Implementations that do not 
recognise
+     * a restriction keep the rest rather than fail, since the JAXP 1.5 access
+     * attributes are optional for third-party processors.
+     *
+     * @return a TransformerFactory with secure processing and no external 
access
+     */
+    public static TransformerFactory newSecureTransformerFactory() {
+        TransformerFactory tf = TransformerFactory.newInstance();
+        try {
+            tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+        } catch (TransformerConfigurationException e) {
+            // Not supported by this processor; the access attributes still 
apply.
+        }
+        setAttributeIfSupported(tf, XMLConstants.ACCESS_EXTERNAL_DTD, "");
+        setAttributeIfSupported(tf, XMLConstants.ACCESS_EXTERNAL_STYLESHEET, 
"");
+        return tf;
+    }
+
+    private static void setAttributeIfSupported(TransformerFactory tf, String 
name, String value) {
+        try {
+            tf.setAttribute(name, value);
+        } catch (IllegalArgumentException e) {
+            // Not recognised by this processor.
+        }
+    }
+
     private static DocumentBuilderFactory getDOMFactory() {
         DocumentBuilderFactory dbf;
         try {
@@ -164,31 +159,14 @@ public class XMLUtils {
         return (dbf);
     }
 
-    private static boolean tryReset = true;
-
     /**
-     * Returns a SAX parser for reuse.
+     * Formerly returned a parser to a pool that was never drawn from, so every
+     * released parser was retained for the life of the class.
      *
-     * @param parser A SAX parser that is available for reuse
+     * @deprecated has no effect
      */
+    @Deprecated
     public static void releaseSAXParser(SAXParser parser) {
-        if (!tryReset) {
-            return;
-        }
-
-        //Free up possible ref. held by past contenthandler.
-        try {
-            XMLReader xmlReader = parser.getXMLReader();
-            if (null != xmlReader) {
-                synchronized (XMLUtils.class) {
-                    saxParsers.push(parser);
-                }
-            } else {
-                tryReset = false;
-            }
-        } catch (org.xml.sax.SAXException e) {
-            tryReset = false;
-        }
     }
 
     /**
diff --git 
a/modules/kernel/test/org/apache/axis2/util/XMLUtilsSecureTransformerTest.java 
b/modules/kernel/test/org/apache/axis2/util/XMLUtilsSecureTransformerTest.java
new file mode 100644
index 0000000000..f57f1552cb
--- /dev/null
+++ 
b/modules/kernel/test/org/apache/axis2/util/XMLUtilsSecureTransformerTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import junit.framework.TestCase;
+
+/**
+ * An identity transform of a StreamSource parses it with the transformer's own
+ * parser, so the factory is the only place an external entity can be refused.
+ */
+public class XMLUtilsSecureTransformerTest extends TestCase {
+
+    private static final String MARKER = "axis2-secret-marker";
+
+    private File secret;
+
+    @Override
+    protected void setUp() throws Exception {
+        secret = File.createTempFile("axis2-secure-transformer", ".txt");
+        FileOutputStream out = new FileOutputStream(secret);
+        try {
+            out.write(MARKER.getBytes(StandardCharsets.UTF_8));
+        } finally {
+            out.close();
+        }
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        secret.delete();
+    }
+
+    private static StreamSource source(String xml) {
+        return new StreamSource(new 
ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
+    }
+
+    private static String transform(StreamSource source) throws 
TransformerException {
+        javax.xml.transform.Transformer transformer =
+                XMLUtils.newSecureTransformerFactory().newTransformer();
+        // Keep the expected refusal out of the build log.
+        transformer.setErrorListener(new ErrorListener() {
+            public void warning(TransformerException e) {
+            }
+
+            public void error(TransformerException e) throws 
TransformerException {
+                throw e;
+            }
+
+            public void fatalError(TransformerException e) throws 
TransformerException {
+                throw e;
+            }
+        });
+        StringWriter out = new StringWriter();
+        transformer.transform(source, new StreamResult(out));
+        return out.toString();
+    }
+
+    public void testPlainDocumentIsCopied() throws Exception {
+        String out = transform(source("<a xmlns='urn:test'><b>text</b></a>"));
+        assertTrue(out, out.contains("<b>text</b>"));
+    }
+
+    public void testExternalEntityIsNotResolved() throws Exception {
+        String xml = "<?xml version='1.0'?>"
+                + "<!DOCTYPE a [<!ENTITY xxe SYSTEM '" + secret.toURI() + 
"'>]>"
+                + "<a>&xxe;</a>";
+        try {
+            String out = transform(source(xml));
+            assertFalse("external entity was resolved: " + out, 
out.contains(MARKER));
+        } catch (TransformerException expected) {
+            // Refusing the document outright is equally acceptable.
+        }
+    }
+}
diff --git a/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java 
b/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java
index fe472ca89d..22ca10bcdd 100644
--- a/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java
+++ b/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java
@@ -30,6 +30,7 @@ import org.apache.axiom.soap.SOAPModelBuilder;
 import org.apache.axis2.saaj.util.IDGenerator;
 import org.apache.axis2.saaj.util.SAAJUtil;
 import org.apache.axis2.kernel.http.HTTPConstants;
+import org.apache.axis2.util.XMLUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.w3c.dom.Attr;
@@ -61,7 +62,6 @@ import javax.xml.stream.XMLStreamReader;
 import javax.xml.transform.Result;
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
@@ -331,7 +331,7 @@ public class SOAPPartImpl extends SOAPPart {
                 reader = inputFactory.createXMLStreamReader(source);
             } else {
                 Result result = new StreamResult(baos);
-                Transformer xformer = 
TransformerFactory.newInstance().newTransformer();
+                Transformer xformer = 
XMLUtils.newSecureTransformerFactory().newTransformer();
                 xformer.transform(source, result);
                 InputStream is = new ByteArrayInputStream(baos.toByteArray());
                 reader = inputFactory.createXMLStreamReader(is);

Reply via email to