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

coheigea pushed a commit to branch coheigea/normalize-servlet-paths
in repository https://gitbox.apache.org/repos/asf/cxf.git

commit bfa370b72f9978a618212332fcb134735ade8793
Author: Colm O hEigeartaigh <[email protected]>
AuthorDate: Mon Nov 30 10:16:09 2026 +0000

    Normalize servlet paths before the WEB-INF/META-INF check
---
 .../java/org/apache/cxf/common/util/UrlUtils.java  | 27 ++++++++++++
 .../org/apache/cxf/common/util/UrlUtilsTest.java   | 17 +++++++-
 .../jaxrs/swagger/ui/SwaggerUiResourceLocator.java | 14 ++-----
 .../cxf/transport/servlet/AbstractHTTPServlet.java | 11 +++--
 .../transport/servlet/AbstractHTTPServletTest.java | 48 ++++++++++++++++++++++
 5 files changed, 101 insertions(+), 16 deletions(-)

diff --git a/core/src/main/java/org/apache/cxf/common/util/UrlUtils.java 
b/core/src/main/java/org/apache/cxf/common/util/UrlUtils.java
index 452f78bb685..9dbcd07b40e 100644
--- a/core/src/main/java/org/apache/cxf/common/util/UrlUtils.java
+++ b/core/src/main/java/org/apache/cxf/common/util/UrlUtils.java
@@ -131,6 +131,33 @@ public final class UrlUtils {
     }
 
 
+    /**
+     * Normalizes an already decoded URL path: empty and "." segments are 
collapsed and a
+     * trailing '/' is kept. A path that has a ".." segment, a backslash or a 
NUL character
+     * could resolve outside the location it names, so null is returned for it 
instead.
+     * @param path decoded path, for example HttpServletRequest.getPathInfo()
+     * @return the normalized path, always starting with '/', or null
+     */
+    public static String normalizePath(String path) {
+        if (path == null || path.indexOf('\\') >= 0 || path.indexOf('\0') >= 
0) {
+            return null;
+        }
+        StringBuilder sb = new StringBuilder(path.length());
+        for (String segment : path.split("/")) {
+            if (segment.isEmpty() || ".".equals(segment)) {
+                continue;
+            }
+            if ("..".equals(segment)) {
+                return null;
+            }
+            sb.append('/').append(segment);
+        }
+        if (sb.length() == 0 || path.endsWith("/")) {
+            sb.append('/');
+        }
+        return sb.toString();
+    }
+
     /**
      * Create a map from String to String that represents the contents of the 
query
      * portion of a URL. For each x=y, x is the key and y is the value.
diff --git a/core/src/test/java/org/apache/cxf/common/util/UrlUtilsTest.java 
b/core/src/test/java/org/apache/cxf/common/util/UrlUtilsTest.java
index a91a4ef5593..2965466cf8c 100644
--- a/core/src/test/java/org/apache/cxf/common/util/UrlUtilsTest.java
+++ b/core/src/test/java/org/apache/cxf/common/util/UrlUtilsTest.java
@@ -22,6 +22,7 @@ package org.apache.cxf.common.util;
 import org.junit.Test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -91,4 +92,18 @@ public class UrlUtilsTest {
     public void testPathDecode() {
         assertEquals("+++", UrlUtils.pathDecode("+%2B+"));
     }
-}
\ No newline at end of file
+
+    @Test
+    public void testNormalizePath() {
+        assertEquals("/", UrlUtils.normalizePath("/"));
+        assertEquals("/", UrlUtils.normalizePath(""));
+        assertEquals("/a/b", UrlUtils.normalizePath("//a/./b"));
+        assertEquals("/a/b/", UrlUtils.normalizePath("/a//b//"));
+        assertEquals("/a/b", UrlUtils.normalizePath("a/b"));
+        assertNull(UrlUtils.normalizePath(null));
+        assertNull(UrlUtils.normalizePath("/a/../b"));
+        assertNull(UrlUtils.normalizePath(".."));
+        assertNull(UrlUtils.normalizePath("/a\\b"));
+        assertNull(UrlUtils.normalizePath("/a\0b"));
+    }
+}
diff --git 
a/rt/rs/description-swagger-ui/src/main/java/org/apache/cxf/jaxrs/swagger/ui/SwaggerUiResourceLocator.java
 
b/rt/rs/description-swagger-ui/src/main/java/org/apache/cxf/jaxrs/swagger/ui/SwaggerUiResourceLocator.java
index e2b298acb62..d85e006e7f7 100644
--- 
a/rt/rs/description-swagger-ui/src/main/java/org/apache/cxf/jaxrs/swagger/ui/SwaggerUiResourceLocator.java
+++ 
b/rt/rs/description-swagger-ui/src/main/java/org/apache/cxf/jaxrs/swagger/ui/SwaggerUiResourceLocator.java
@@ -68,8 +68,8 @@ public class SwaggerUiResourceLocator {
 
     /**
      * Checks whether the resource path could escape the Swagger UI root: 
whether it contains a ".."
-     * segment or a backslash once percent-decoded. The path is decoded until 
it no longer changes,
-     * as the URL handler (e.g. for file: URLs) may decode it again.
+     * segment, a backslash or a NUL once percent-decoded (see 
UrlUtils.normalizePath). The path is
+     * decoded until it no longer changes, as the URL handler (e.g. for file: 
URLs) may decode it again.
      */
     private static boolean isTraversal(String resourcePath) {
         String decoded = resourcePath;
@@ -84,15 +84,7 @@ public class SwaggerUiResourceLocator {
             // invalid percent-encoding
             return true;
         }
-        if (!stable || decoded.indexOf('\\') != -1) {
-            return true;
-        }
-        for (String segment : decoded.split("/")) {
-            if ("..".equals(segment)) {
-                return true;
-            }
-        }
-        return false;
+        return !stable || UrlUtils.normalizePath(decoded) == null;
     }
 
     /**
diff --git 
a/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractHTTPServlet.java
 
b/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractHTTPServlet.java
index 7d8b5e9dbac..3d002d503ef 100644
--- 
a/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractHTTPServlet.java
+++ 
b/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractHTTPServlet.java
@@ -54,6 +54,7 @@ import org.apache.cxf.common.i18n.BundleUtils;
 import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.common.util.PropertyUtils;
 import org.apache.cxf.common.util.StringUtils;
+import org.apache.cxf.common.util.UrlUtils;
 import org.apache.cxf.helpers.FileUtils;
 import org.apache.cxf.helpers.IOUtils;
 import org.apache.cxf.resource.ResourceManager;
@@ -373,10 +374,11 @@ public abstract class AbstractHTTPServlet extends 
HttpServlet implements Filter
     protected void serveStaticContent(HttpServletRequest request,
                                       HttpServletResponse response,
                                       String pathInfo) throws ServletException 
{
-        if (isProtectedPath(pathInfo)) {
+        String path = UrlUtils.normalizePath(pathInfo);
+        if (path == null || isProtectedPath(path)) {
             throw new ServletException("Static resource " + pathInfo + " is 
not available");
         }
-        try (InputStream is = getResourceAsStream(pathInfo)) {
+        try (InputStream is = getResourceAsStream(path)) {
             if (is == null) {
                 throw new ServletException("Static resource " + pathInfo + " 
is not available");
             }
@@ -421,7 +423,8 @@ public abstract class AbstractHTTPServlet extends 
HttpServlet implements Filter
 
     protected void redirect(HttpServletRequest request, HttpServletResponse 
response, String pathInfo)
         throws ServletException {
-        if (isProtectedPath(pathInfo)) {
+        String path = UrlUtils.normalizePath(pathInfo);
+        if (path == null || isProtectedPath(path)) {
             throw new ServletException("No RequestDispatcher can be created 
for path " + pathInfo);
         }
         boolean customServletPath = dispatcherServletPath != null;
@@ -430,7 +433,7 @@ public abstract class AbstractHTTPServlet extends 
HttpServlet implements Filter
         ServletContext sc = super.getServletContext();
         RequestDispatcher rd = dispatcherServletName != null
             ? sc.getNamedDispatcher(dispatcherServletName)
-            : sc.getRequestDispatcher((theServletPath + 
pathInfo).replace("//", "/"));
+            : sc.getRequestDispatcher((theServletPath + path).replace("//", 
"/"));
         if (rd == null) {
             String errorMessage = "No RequestDispatcher can be created for 
path " + pathInfo;
             if (dispatcherServletName != null) {
diff --git 
a/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/AbstractHTTPServletTest.java
 
b/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/AbstractHTTPServletTest.java
index 108699b2fbb..3033335a72f 100644
--- 
a/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/AbstractHTTPServletTest.java
+++ 
b/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/AbstractHTTPServletTest.java
@@ -42,7 +42,9 @@ import org.junit.Test;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
@@ -124,6 +126,52 @@ public class AbstractHTTPServletTest {
         assertFalse(servlet.invoked);
     }
 
+    @Test
+    public void testRedirectToNonNormalizedWebInfIsNotForwarded() throws 
Exception {
+        ServletContext sc = mock(ServletContext.class);
+        RequestDispatcher rd = mock(RequestDispatcher.class);
+        when(sc.getRequestDispatcher(anyString())).thenReturn(rd);
+        TestServlet servlet = initServlet(sc, "redirects-list", "/.*\\.jsp");
+
+        for (String path : new String[] {"//WEB-INF/views/admin.jsp", 
"/./WEB-INF/views/admin.jsp",
+                                         "/views/../WEB-INF/views/admin.jsp", 
"/WEB-INF\\views\\admin.jsp"}) {
+            assertThrows(path, ServletException.class,
+                () -> servlet.doGet(mockRequest(path), 
mock(HttpServletResponse.class)));
+        }
+
+        verify(sc, never()).getRequestDispatcher(anyString());
+        assertFalse(servlet.invoked);
+    }
+
+    @Test
+    public void testRedirectForwardsNormalizedPath() throws Exception {
+        ServletContext sc = mock(ServletContext.class);
+        RequestDispatcher rd = mock(RequestDispatcher.class);
+        when(sc.getRequestDispatcher("/views/index.jsp")).thenReturn(rd);
+        TestServlet servlet = initServlet(sc, "redirects-list", "/.*\\.jsp");
+        HttpServletResponse response = mock(HttpServletResponse.class);
+
+        servlet.doGet(mockRequest("/views//./index.jsp"), response);
+
+        verify(rd).forward(any(HttpServletRequest.class), eq(response));
+        assertFalse(servlet.invoked);
+    }
+
+    @Test
+    public void testStaticResourceUnderNonNormalizedWebInfIsNotServed() throws 
Exception {
+        ServletContext sc = mockServletContext("/WEB-INF/web.xml", WEB_XML);
+        TestServlet servlet = initServlet(sc, "static-resources-list", 
"/.*\\.xml");
+
+        for (String path : new String[] {"//WEB-INF/web.xml", 
"/./WEB-INF/web.xml", "/a/../WEB-INF/web.xml"}) {
+            HttpServletResponse response = mock(HttpServletResponse.class);
+            ByteArrayOutputStream bos = captureOutput(response);
+            assertThrows(path, ServletException.class, () -> 
servlet.doGet(mockRequest(path), response));
+            assertEquals("", bos.toString(StandardCharsets.UTF_8));
+        }
+
+        verify(sc, never()).getResourceAsStream(anyString());
+    }
+
     private static ServletContext mockServletContext(String path, String 
content) {
         ServletContext sc = mock(ServletContext.class);
         when(sc.getResourceAsStream(path))

Reply via email to