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

markt-asf pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/9.0.x by this push:
     new 3e30ef210d Limit the properties a WebDAV PROPFIND request may request
3e30ef210d is described below

commit 3e30ef210d6ff564e4ef9e8ffac2e0aa571efd94
Author: Mark Thomas <[email protected]>
AuthorDate: Thu Nov 26 14:44:08 2026 +0000

    Limit the properties a WebDAV PROPFIND request may request
    
    A PROPFIND request names the properties the client wants. Each property that
    can't be found is echoed back in a 404 propstat and, for a property outside
    the DAV: namespace, the full namespace URI was written inline with every
    echoed element. A small request could therefore generate a very large
    response, multiplied by the number of resources in scope.
    
    Limit the number of distinct properties that may be requested to 100, with 
the
    new maxPropfindProperties init-param to change the limit, and ignore
    properties that are requested more than once. Declare the namespace of each
    requested property once on the multistatus element and refer to it using a
    prefix rather than repeating the namespace URI for every echoed property.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../apache/catalina/servlets/WebdavServlet.java    |  79 +++++++++--
 java/org/apache/catalina/util/XMLWriter.java       |  27 ++++
 .../catalina/servlets/TestWebdavServlet.java       | 156 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |   9 ++
 4 files changed, 263 insertions(+), 8 deletions(-)

diff --git a/java/org/apache/catalina/servlets/WebdavServlet.java 
b/java/org/apache/catalina/servlets/WebdavServlet.java
index 978d09f950..2f57deac67 100644
--- a/java/org/apache/catalina/servlets/WebdavServlet.java
+++ b/java/org/apache/catalina/servlets/WebdavServlet.java
@@ -32,11 +32,14 @@ import java.util.Collection;
 import java.util.Date;
 import java.util.Deque;
 import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Set;
 import java.util.TimeZone;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
@@ -175,6 +178,10 @@ import org.xml.sax.SAXException;
  * <p>
  * By default, WebDAV request bodies for LOCK and PROPFIND are limited to 4096 
bytes. To change this limit, set the
  * <code>maxRequestBodySize</code> <code>init-param</code> for the WebDAV 
servlet.
+ * <p>
+ * By default, a PROPFIND request may request at most 100 distinct properties. 
Repeats of the same property are ignored
+ * and do not count towards this limit. A request that exceeds the limit is 
rejected. To change the limit, set the
+ * <code>maxPropfindProperties</code> <code>init-param</code> for the WebDAV 
servlet.
  *
  * @see <a href="https://tools.ietf.org/html/rfc4918";>RFC 4918</a>
  */
@@ -213,6 +220,12 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
     private static final int DEFAULT_MAX_REQUEST_BODY_SIZE = 4096;
 
 
+    /*
+     * Default maximum number of distinct properties that may be requested in 
a PROPFIND request.
+     */
+    private static final int DEFAULT_MAX_PROPFIND_PROPERTIES = 100;
+
+
     /**
      * Default namespace.
      */
@@ -270,6 +283,10 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
     private int maxRequestBodySize = DEFAULT_MAX_REQUEST_BODY_SIZE;
 
 
+    /** The maximum number of distinct properties that may be requested in a 
PROPFIND request. */
+    private int maxPropfindProperties = DEFAULT_MAX_PROPFIND_PROPERTIES;
+
+
     /**
      * Is access allowed via WebDAV to the special paths (/WEB-INF and 
/META-INF)?
      */
@@ -320,6 +337,10 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
             maxRequestBodySize = 
Integer.parseInt(getServletConfig().getInitParameter("maxRequestBodySize"));
         }
 
+        if (getServletConfig().getInitParameter("maxPropfindProperties") != 
null) {
+            maxPropfindProperties = 
Integer.parseInt(getServletConfig().getInitParameter("maxPropfindProperties"));
+        }
+
         if (getServletConfig().getInitParameter("allowSpecialPaths") != null) {
             allowSpecialPaths = 
Boolean.parseBoolean(getServletConfig().getInitParameter("allowSpecialPaths"));
         }
@@ -867,6 +888,8 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
 
         // Properties which are to be displayed.
         List<Node> properties = new ArrayList<>();
+        // Used to ignore properties that have been requested more than once
+        Set<String> propertyKeys = new HashSet<>();
         // Propfind depth
         int depth;
         // Propfind type
@@ -928,7 +951,13 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
                                         case Node.TEXT_NODE:
                                             break;
                                         case Node.ELEMENT_NODE:
-                                            properties.add(currentNode2);
+                                            if 
(propertyKeys.add(getPropertyKey(currentNode2))) {
+                                                if (properties.size() >= 
maxPropfindProperties) {
+                                                    
resp.sendError(WebdavStatus.SC_REQUEST_TOO_LONG);
+                                                    return;
+                                                }
+                                                properties.add(currentNode2);
+                                            }
                                             break;
                                     }
                                 }
@@ -985,11 +1014,28 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
         XMLWriter generatedXML = new XMLWriter(resp.getWriter());
         generatedXML.writeXMLHeader();
 
-        generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", 
XMLWriter.OPENING);
+        /*
+         * Properties that are not in the DAV: namespace and that can't be 
found are written to the response using the
+         * namespace of the property. Declare each of those namespaces once, 
on the root element, so that the URI is not
+         * repeated for every property of every resource.
+         */
+        Map<String,String> prefixToNamespace = new LinkedHashMap<>();
+        Map<String,String> namespaceToPrefix = new HashMap<>();
+        for (Node property : properties) {
+            String namespace = property.getNamespaceURI();
+            if (namespace != null && !namespace.isEmpty() && 
!DEFAULT_NAMESPACE.equals(namespace) &&
+                    !namespaceToPrefix.containsKey(namespace)) {
+                String prefix = "ns" + namespaceToPrefix.size();
+                namespaceToPrefix.put(namespace, prefix);
+                prefixToNamespace.put(prefix, namespace);
+            }
+        }
+
+        generatedXML.writeOpeningElement("D", DEFAULT_NAMESPACE, 
prefixToNamespace, "multistatus");
 
         if (depth == 0) {
             propfindResource(generatedXML, getEncodedPath(path, resource, 
req), path, type, properties,
-                    resource.isFile(), resource.getCreation(), 
resource.getLastModified(), resource.getContentLength(),
+                    namespaceToPrefix, resource.isFile(), 
resource.getCreation(), resource.getLastModified(), resource.getContentLength(),
                     getServletContext().getMimeType(resource.getName()), 
generateETag(resource));
         } else {
             // The stack always contains the object of the current level
@@ -1013,7 +1059,7 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
                 // Broken symlink or odd permission settings?
                 if (resource.exists()) {
                     propfindResource(generatedXML, getEncodedPath(currentPath, 
resource, req), currentPath, type,
-                            properties, resource.isFile(), 
resource.getCreation(), resource.getLastModified(),
+                            properties, namespaceToPrefix, resource.isFile(), 
resource.getCreation(), resource.getLastModified(),
                             resource.getContentLength(), 
getServletContext().getMimeType(resource.getName()),
                             generateETag(resource));
                 }
@@ -2598,8 +2644,8 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
 
 
     private void propfindResource(XMLWriter generatedXML, String rewrittenUrl, 
String path, PropfindType propFindType,
-            List<Node> properties, boolean isFile, long created, long 
lastModified, long contentLength,
-            String contentType, String eTag) {
+            List<Node> properties, Map<String,String> namespaceToPrefix, 
boolean isFile, long created,
+            long lastModified, long contentLength, String contentType, String 
eTag) {
 
         generatedXML.writeElement("D", "response", XMLWriter.OPENING);
         String status = "HTTP/1.1 " + WebdavStatus.SC_OK + " ";
@@ -2750,8 +2796,15 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
                         if (propertyNotFound != null) {
                             generatedXML.writeElement("D", propertyNotFound, 
XMLWriter.NO_CONTENT);
                         } else {
-                            generatedXML.writeElement(null, 
propertyNotFoundNode.getNamespaceURI(),
-                                    propertyNotFoundNode.getLocalName(), 
XMLWriter.NO_CONTENT);
+                            String prefix = 
namespaceToPrefix.get(propertyNotFoundNode.getNamespaceURI());
+                            if (prefix != null) {
+                                // The namespace is declared on the root 
element
+                                generatedXML.writeElement(prefix, null, 
propertyNotFoundNode.getLocalName(),
+                                        XMLWriter.NO_CONTENT);
+                            } else {
+                                generatedXML.writeElement(null, 
propertyNotFoundNode.getNamespaceURI(),
+                                        propertyNotFoundNode.getLocalName(), 
XMLWriter.NO_CONTENT);
+                            }
                         }
                     }
 
@@ -2836,6 +2889,16 @@ public class WebdavServlet extends DefaultServlet 
implements PeriodicEventListen
     }
 
 
+    /*
+     * A key that identifies a property by namespace and local name. The local 
name can't contain '}' so the key is
+     * unambiguous.
+     */
+    private static String getPropertyKey(Node node) {
+        String namespace = node.getNamespaceURI();
+        return "{" + (namespace == null ? "" : namespace) + "}" + 
node.getLocalName();
+    }
+
+
     private static boolean propertyEquals(Node node1, Node node2) {
         return node1.getLocalName().equals(node2.getLocalName()) &&
                 ((node1.getNamespaceURI() == null && node2.getNamespaceURI() 
== null) ||
diff --git a/java/org/apache/catalina/util/XMLWriter.java 
b/java/org/apache/catalina/util/XMLWriter.java
index ca83a76836..4448bba082 100644
--- a/java/org/apache/catalina/util/XMLWriter.java
+++ b/java/org/apache/catalina/util/XMLWriter.java
@@ -18,6 +18,7 @@ package org.apache.catalina.util;
 
 import java.io.IOException;
 import java.io.Writer;
+import java.util.Map;
 
 import org.apache.tomcat.util.security.Escape;
 
@@ -115,6 +116,32 @@ public class XMLWriter {
     }
 
 
+    /**
+     * Write an opening element that, in addition to the namespace of the 
element, declares further namespaces. Elements
+     * that follow can then refer to those namespaces using their prefix 
rather than repeating the namespace URI.
+     *
+     * @param namespace             Namespace abbreviation of the element
+     * @param namespaceInfo         Namespace URI of the element
+     * @param additionalNamespaces  The additional namespaces to declare. The 
key is the prefix and the value is the
+     *                                  namespace URI.
+     * @param name                  Element name
+     */
+    public void writeOpeningElement(String namespace, String namespaceInfo, 
Map<String,String> additionalNamespaces,
+            String name) {
+        if (lastWriteWasOpen) {
+            buffer.append('\n');
+        }
+        buffer.append('<').append(namespace).append(':').append(name).append(" 
xmlns:").append(namespace).append("=\"")
+                .append(Escape.xml(namespaceInfo)).append('"');
+        for (Map.Entry<String,String> entry : additionalNamespaces.entrySet()) 
{
+            buffer.append(" 
xmlns:").append(entry.getKey()).append("=\"").append(Escape.xml(entry.getValue()))
+                    .append('"');
+        }
+        buffer.append('>');
+        lastWriteWasOpen = true;
+    }
+
+
     /**
      * Write an element.
      *
diff --git a/test/org/apache/catalina/servlets/TestWebdavServlet.java 
b/test/org/apache/catalina/servlets/TestWebdavServlet.java
index 9d1116b7f6..04c197d2a6 100644
--- a/test/org/apache/catalina/servlets/TestWebdavServlet.java
+++ b/test/org/apache/catalina/servlets/TestWebdavServlet.java
@@ -1923,6 +1923,162 @@ public class TestWebdavServlet extends TomcatBaseTest {
         Assert.fail("The response has no content type");
     }
 
+    /*
+     * Properties that are requested more than once are only processed once.
+     */
+    @Test
+    public void testPropfindDuplicateProperties() throws Exception {
+        String body = propfindBody("urn:test:a", "p", "p", "q", "p");
+        Client client = doTestPropfind(null, "0", body, 1);
+
+        Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, 
client.getStatusCode());
+        Assert.assertEquals(1, count(client.getResponseBody(), "<ns0:p/>"));
+        Assert.assertEquals(1, count(client.getResponseBody(), "<ns0:q/>"));
+    }
+
+
+    /*
+     * The namespace of a property that can't be found is declared once on the 
root element rather than for every
+     * property of every resource.
+     */
+    @Test
+    public void testPropfindNamespaceDeclaredOnce() throws Exception {
+        String body = propfindBody("urn:test:a", "p", "q");
+        Client client = doTestPropfind(null, "1", body, 3);
+
+        Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, 
client.getStatusCode());
+        String responseBody = client.getResponseBody();
+        // Collection plus 3 files
+        Assert.assertEquals(4, count(responseBody, "<D:response>"));
+        Assert.assertEquals(1, count(responseBody, "urn:test:a"));
+        Assert.assertEquals(1, count(responseBody, "<D:multistatus 
xmlns:D=\"DAV:\" xmlns:ns0=\"urn:test:a\">"));
+        Assert.assertEquals(4, count(responseBody, "<ns0:p/>"));
+        Assert.assertEquals(4, count(responseBody, "<ns0:q/>"));
+    }
+
+
+    @Test
+    public void testPropfindNamespacesDeclaredOnce() throws Exception {
+        String body = "<D:propfind xmlns:D=\"DAV:\" xmlns:A=\"urn:test:a\" 
xmlns:B=\"urn:test:b\"><D:prop>" +
+                "<A:p/><B:p/><A:q/><D:unknown/></D:prop></D:propfind>";
+        Client client = doTestPropfind(null, "0", body, 1);
+
+        Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, 
client.getStatusCode());
+        String responseBody = client.getResponseBody();
+        Assert.assertEquals(1, count(responseBody, 
"xmlns:ns0=\"urn:test:a\""));
+        Assert.assertEquals(1, count(responseBody, 
"xmlns:ns1=\"urn:test:b\""));
+        Assert.assertEquals(1, count(responseBody, "<ns0:p/>"));
+        Assert.assertEquals(1, count(responseBody, "<ns1:p/>"));
+        Assert.assertEquals(1, count(responseBody, "<ns0:q/>"));
+        Assert.assertEquals(1, count(responseBody, "<D:unknown/>"));
+    }
+
+
+    @Test
+    public void testPropfindMaxPropertiesDefault() throws Exception {
+        String[] names = new String[100];
+        for (int i = 0; i < names.length; i++) {
+            names[i] = "p" + i;
+        }
+        startPropfind(null, 1);
+        Client client = sendPropfind("0", propfindBody("urn:test:a", names));
+        Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, 
client.getStatusCode());
+
+        String[] tooMany = new String[101];
+        for (int i = 0; i < tooMany.length; i++) {
+            tooMany[i] = "p" + i;
+        }
+        client = sendPropfind("0", propfindBody("urn:test:a", tooMany));
+        Assert.assertEquals(WebdavStatus.SC_REQUEST_TOO_LONG, 
client.getStatusCode());
+    }
+
+
+    /*
+     * Properties that are requested more than once do not count towards the 
limit.
+     */
+    @Test
+    public void testPropfindMaxPropertiesConfigured() throws Exception {
+        startPropfind("2", 1);
+        Client client = sendPropfind("0", propfindBody("urn:test:a", "p", "q", 
"p", "q", "p"));
+        Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, 
client.getStatusCode());
+
+        client = sendPropfind("0", propfindBody("urn:test:a", "p", "q", "r"));
+        Assert.assertEquals(WebdavStatus.SC_REQUEST_TOO_LONG, 
client.getStatusCode());
+    }
+
+
+    private static String propfindBody(String namespace, String... names) {
+        StringBuilder sb = new StringBuilder("<D:propfind xmlns:D=\"DAV:\" 
xmlns:T=\"");
+        sb.append(namespace);
+        sb.append("\"><D:prop>");
+        for (String name : names) {
+            sb.append("<T:").append(name).append("/>");
+        }
+        sb.append("</D:prop></D:propfind>");
+        return sb.toString();
+    }
+
+
+    private static int count(String text, String search) {
+        int count = 0;
+        int index = 0;
+        while ((index = text.indexOf(search, index)) != -1) {
+            count++;
+            index += search.length();
+        }
+        return count;
+    }
+
+
+    private Client doTestPropfind(String maxPropfindProperties, String depth, 
String body, int files)
+            throws Exception {
+        startPropfind(maxPropfindProperties, files);
+        return sendPropfind(depth, body);
+    }
+
+
+    private void startPropfind(String maxPropfindProperties, int files) throws 
Exception {
+        Tomcat tomcat = getTomcatInstance();
+
+        File tempWebapp = new File(getTemporaryDirectory(), "webdav-propfind" 
+ UUID.randomUUID());
+        tempWebapp.deleteOnExit();
+        Assert.assertTrue(tempWebapp.mkdirs());
+        for (int i = 0; i < files; i++) {
+            File file = new File(tempWebapp, "file" + i + ".txt");
+            Assert.assertTrue(file.createNewFile());
+            file.deleteOnExit();
+        }
+        Context ctxt = tomcat.addContext("", tempWebapp.getAbsolutePath());
+        Wrapper webdavServlet = Tomcat.addServlet(ctxt, "webdav", new 
WebdavServlet());
+        webdavServlet.addInitParameter("listings", "true");
+        if (maxPropfindProperties != null) {
+            webdavServlet.addInitParameter("maxPropfindProperties", 
maxPropfindProperties);
+        }
+        ctxt.addServletMapping("/*", "webdav");
+        tomcat.start();
+    }
+
+
+    private Client sendPropfind(String depth, String body) throws Exception {
+        Client client = new Client();
+        client.setPort(getPort());
+        // @formatter:off
+        client.setRequest(new String[] {
+                "PROPFIND / HTTP/1.1" + CRLF +
+                    "Host: localhost:" + getPort() + CRLF +
+                    "Depth: " + depth + CRLF +
+                    "Content-Length: " + body.length() + CRLF +
+                    "Connection: Close" + CRLF +
+                    CRLF +
+                    body
+                });
+        // @formatter:on
+        client.connect();
+        client.processRequest(true);
+        return client;
+    }
+
+
     private static final class Client extends SimpleHttpClient {
 
         @Override
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index e9632f5291..d2608a8074 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -197,6 +197,15 @@
         bound when <code>AsyncListener.onError()</code> is called for a failed
         asynchronous dispatch. (markt)
       </fix>
+      <fix>
+        Limit the number of distinct properties that a WebDAV
+        <code>PROPFIND</code> request may request to 100. The limit is
+        configurable using the new <code>maxPropfindProperties</code>
+        <code>init-param</code>. Properties that are requested more than once
+        are ignored. The namespace of a requested property that is not found is
+        now declared once on the root element of the response rather than being
+        repeated for every property of every resource. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to