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

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

commit cc5121e306ee85853289d77305c280dd95012120
Author: Mark Thomas <[email protected]>
AuthorDate: Tue Nov 24 11:42:38 2026 +0000

    Harden the RequestFilterValve
    
    Deny the request if mis-configured with an authenticator that does not
    support preemptive authentication.
---
 java/org/apache/catalina/Globals.java              |   7 ++
 .../catalina/authenticator/AuthenticatorBase.java  |  19 ++++
 .../catalina/authenticator/BasicAuthenticator.java |   5 +-
 .../authenticator/DigestAuthenticator.java         |   5 +-
 .../catalina/authenticator/SSLAuthenticator.java   |   5 +-
 .../authenticator/SpnegoAuthenticator.java         |   5 +-
 .../apache/catalina/valves/RequestFilterValve.java |   2 +
 .../catalina/valves/TestRequestFilterValve.java    | 106 ++++++++++++++++++++-
 webapps/docs/changelog.xml                         |   7 ++
 webapps/docs/config/valve.xml                      |  21 ++--
 10 files changed, 170 insertions(+), 12 deletions(-)

diff --git a/java/org/apache/catalina/Globals.java 
b/java/org/apache/catalina/Globals.java
index 135aed7e04..25fd186066 100644
--- a/java/org/apache/catalina/Globals.java
+++ b/java/org/apache/catalina/Globals.java
@@ -155,6 +155,13 @@ public final class Globals {
     public static final String SSL_SESSION_MGR_ATTR = 
"jakarta.servlet.request.ssl_session_mgr";
 
 
+    /**
+     * The request attribute used to force preemptive authentication 
irrespective of whether the authorization header
+     * is correct for the currently configured authentication mechanism.
+     */
+    public static final String FORCE_PREEMPTIVE_AUTHENTICATION = 
"org.apache.catalina.authenticator.force_preemptive";
+
+
     // ------------------------------------------ ServletContext attribute 
names
 
     /**
diff --git a/java/org/apache/catalina/authenticator/AuthenticatorBase.java 
b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
index a2def933a3..4465d10ed8 100644
--- a/java/org/apache/catalina/authenticator/AuthenticatorBase.java
+++ b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
@@ -578,6 +578,11 @@ public abstract class AuthenticatorBase extends ValveBase 
implements Authenticat
             authRequired = true;
         }
 
+        if (!authRequired && isPreemptiveAuthRequired(request)) {
+            response.sendError(HttpServletResponse.SC_FORBIDDEN);
+            return;
+        }
+
         if ((authRequired || constraints != null) && 
allowCorsPreflightBypass(request)) {
             if (log.isDebugEnabled()) {
                 log.debug(sm.getString("authenticator.corsBypass"));
@@ -1411,6 +1416,20 @@ public abstract class AuthenticatorBase extends 
ValveBase implements Authenticat
     }
 
 
+    /**
+     * Is preemptive authentication required for this request. Typically 
triggered by a component earlier in the
+     * processing chain.
+     *
+     * @param request The request to check
+     *
+     * @return {@code true} if preemptive authentication is required, 
otherwise {@code false}
+     */
+    protected boolean isPreemptiveAuthRequired(Request request) {
+        Object flag = 
request.getAttribute(Globals.FORCE_PREEMPTIVE_AUTHENTICATION);
+        return Boolean.TRUE.equals(flag);
+    }
+
+
     @Override
     public void notify(String layer, String appContext) {
         jaspicLock.writeLock().lock();
diff --git a/java/org/apache/catalina/authenticator/BasicAuthenticator.java 
b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
index afcb7c817b..335675510b 100644
--- a/java/org/apache/catalina/authenticator/BasicAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
@@ -136,7 +136,10 @@ public class BasicAuthenticator extends AuthenticatorBase {
     @Override
     protected boolean isPreemptiveAuthPossible(Request request) {
         MessageBytes authorizationHeader = 
request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
-        return authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("basic ", 0);
+        if (authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("basic ", 0)) {
+            return true;
+        }
+        return isPreemptiveAuthRequired(request);
     }
 
 
diff --git a/java/org/apache/catalina/authenticator/DigestAuthenticator.java 
b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
index e9fc4e9ef0..c02b1392b8 100644
--- a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
@@ -470,7 +470,10 @@ public class DigestAuthenticator extends AuthenticatorBase 
{
     @Override
     protected boolean isPreemptiveAuthPossible(Request request) {
         MessageBytes authorizationHeader = 
request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
-        return authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("digest ", 0);
+        if (authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("digest ", 0)) {
+            return true;
+        }
+        return isPreemptiveAuthRequired(request);
     }
 
 
diff --git a/java/org/apache/catalina/authenticator/SSLAuthenticator.java 
b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
index 5eb7b47d74..13d9c80b99 100644
--- a/java/org/apache/catalina/authenticator/SSLAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
@@ -122,7 +122,10 @@ public class SSLAuthenticator extends AuthenticatorBase {
     @Override
     protected boolean isPreemptiveAuthPossible(Request request) {
         X509Certificate[] certs = getRequestCertificates(request);
-        return certs != null && certs.length > 0;
+        if (certs != null && certs.length > 0) {
+            return true;
+        }
+        return isPreemptiveAuthRequired(request);
     }
 
 
diff --git a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java 
b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
index 786c08becc..e3fa2ea654 100644
--- a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
@@ -340,6 +340,9 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
     @Override
     protected boolean isPreemptiveAuthPossible(Request request) {
         MessageBytes authorizationHeader = 
request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
-        return authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("negotiate ", 0);
+        if (authorizationHeader != null && 
authorizationHeader.startsWithIgnoreCase("negotiate ", 0)) {
+            return true;
+        }
+        return isPreemptiveAuthRequired(request);
     }
 }
diff --git a/java/org/apache/catalina/valves/RequestFilterValve.java 
b/java/org/apache/catalina/valves/RequestFilterValve.java
index 3336df886b..74d47e28ea 100644
--- a/java/org/apache/catalina/valves/RequestFilterValve.java
+++ b/java/org/apache/catalina/valves/RequestFilterValve.java
@@ -24,6 +24,7 @@ import jakarta.servlet.ServletException;
 import jakarta.servlet.http.HttpServletResponse;
 
 import org.apache.catalina.Context;
+import org.apache.catalina.Globals;
 import org.apache.catalina.LifecycleException;
 import org.apache.catalina.connector.Request;
 import org.apache.catalina.connector.Response;
@@ -395,6 +396,7 @@ public abstract class RequestFilterValve extends ValveBase {
                 if 
(request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) 
{
                     
request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
                 }
+                request.setAttribute(Globals.FORCE_PREEMPTIVE_AUTHENTICATION, 
Boolean.TRUE);
                 getNext().invoke(request, response);
                 return;
             }
diff --git a/test/org/apache/catalina/valves/TestRequestFilterValve.java 
b/test/org/apache/catalina/valves/TestRequestFilterValve.java
index bec069bac0..f41cec4f2b 100644
--- a/test/org/apache/catalina/valves/TestRequestFilterValve.java
+++ b/test/org/apache/catalina/valves/TestRequestFilterValve.java
@@ -17,22 +17,35 @@
 package org.apache.catalina.valves;
 
 import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.junit.Assert;
 import org.junit.Test;
 
 import org.apache.catalina.Context;
+import org.apache.catalina.authenticator.BasicAuthenticator;
 import org.apache.catalina.connector.Connector;
 import org.apache.catalina.connector.Request;
 import org.apache.catalina.connector.Response;
 import org.apache.catalina.core.StandardContext;
+import org.apache.catalina.realm.NullRealm;
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.descriptor.web.LoginConfig;
 
 /**
  * {@link RequestFilterValve} Tests
  */
-public class TestRequestFilterValve {
+public class TestRequestFilterValve extends TomcatBaseTest {
 
     private static final int OK = 200;
     private static final int FORBIDDEN = 403;
@@ -366,4 +379,95 @@ public class TestRequestFilterValve {
         standardTests(CIDR6_ALLOW_PROP, CIDR6_DENY_PROP, CIDR6_ONLY_ALLOW, 
CIDR6_ONLY_DENY, CIDR6_ALLOW_AND_DENY,
                 CIDR6_NO_ALLOW_NO_DENY, true, "CIDR");
     }
+
+
+    // Matches the loopback address however the client connects
+    private static final String DENY_LOOPBACK = "127.0.0.0/8,::1/128";
+    private static final String DENY_OTHER = "192.0.2.0/24";
+
+
+    @Test
+    public void testDeniedNoAuthorizationHeader() throws Exception {
+        CountingServlet servlet = doTest(DENY_LOOPBACK, null);
+        Assert.assertEquals("Denied client must have been challenged", 401, 
getLastStatus());
+        Assert.assertEquals("Denied client must not reach the resource", 0, 
servlet.getCount());
+    }
+
+
+    @Test
+    public void testDeniedNonBasicAuthorizationHeader() throws Exception {
+        CountingServlet servlet = doTest(DENY_LOOPBACK, "Bearer abc");
+        Assert.assertEquals("Denied client must have been challenged", 401, 
getLastStatus());
+        Assert.assertEquals("Denied client must not reach the resource", 0, 
servlet.getCount());
+    }
+
+
+    @Test
+    public void testAllowed() throws Exception {
+        CountingServlet servlet = doTest(DENY_OTHER, null);
+        Assert.assertEquals(200, getLastStatus());
+        Assert.assertEquals(1, servlet.getCount());
+    }
+
+
+    private int lastStatus;
+
+    private int getLastStatus() {
+        return lastStatus;
+    }
+
+
+    private CountingServlet doTest(String deny, String authorizationHeader) 
throws Exception {
+        Tomcat tomcat = getTomcatInstance();
+
+        // No file system docBase required
+        Context ctx = getProgrammaticRootContext();
+        ctx.setPreemptiveAuthentication(true);
+        ctx.setRealm(new NullRealm());
+
+        LoginConfig loginConfig = new LoginConfig();
+        loginConfig.setAuthMethod("BASIC");
+        ctx.setLoginConfig(loginConfig);
+
+        RemoteCIDRValve valve = new RemoteCIDRValve();
+        valve.setDeny(deny);
+        valve.setInvalidAuthenticationWhenDeny(true);
+        ctx.getPipeline().addValve(valve);
+        ctx.getPipeline().addValve(new BasicAuthenticator());
+
+        // Deliberately no security constraint
+        CountingServlet servlet = new CountingServlet();
+        Tomcat.addServlet(ctx, "counting", servlet);
+        ctx.addServletMapping("/", "counting");
+
+        tomcat.start();
+
+        Map<String,List<String>> reqHead = null;
+        if (authorizationHeader != null) {
+            reqHead = Collections.singletonMap("Authorization", 
Collections.singletonList(authorizationHeader));
+        }
+        ByteChunk bc = new ByteChunk();
+        lastStatus = getUrl("http://localhost:"; + getPort() + "/", bc, 
reqHead, null);
+
+        return servlet;
+    }
+
+
+    private static final class CountingServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final AtomicInteger count = new AtomicInteger();
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
+            count.incrementAndGet();
+            resp.setContentType("text/plain");
+            resp.getWriter().print("OK");
+        }
+
+        int getCount() {
+            return count.get();
+        }
+    }
 }
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index d8ca54f432..f0d04f8c55 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -241,6 +241,13 @@
         Expand the user name normalisation options available in the
         <code>LockOutRealm</code>. (markt)
       </fix>
+      <fix>
+        Harden the <code>RequestFilterValve</code>. If
+        <code>invalidAuthenticationWhenDeny</code> is configured and allows a
+        request through to be authenticated but the authenticator that 
processes
+        the request does not support preemptive authentication, then the 
request
+        is denied. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">
diff --git a/webapps/docs/config/valve.xml b/webapps/docs/config/valve.xml
index 914f2e7988..68196cbe86 100644
--- a/webapps/docs/config/valve.xml
+++ b/webapps/docs/config/valve.xml
@@ -707,13 +707,20 @@
 
       <attribute name="invalidAuthenticationWhenDeny" required="false">
         <p>When a request should be denied, do not deny but instead
-        set an invalid <code>authentication</code> header. This only works
-        if the context has the attribute 
<code>preemptiveAuthentication="true"</code>
-        set. An already existing <code>authentication</code> header will not be
-        overwritten. In effect this will trigger authentication instead of deny
-        even if the application does not have a security constraint 
configured.</p>
-        <p>This can be combined with <code>addConnectorPort</code> to trigger 
authentication
-        depending on the client and the connector that is used to access an 
application.</p>
+        set an invalid <code>authorization</code> header that triggers
+        pre-emptive authentication. An already existing
+        <code>authorization</code> header will not be overwritten. This feature
+        triggers authentication instead of deny even if the application does 
not
+        have a security constraint configured.</p>
+        <p>This feature requires that the context has the attribute
+        <code>preemptiveAuthentication="true"</code> set and is configured with
+        an authentication mechanism (BASIC, DIGEST, SPNEGO or CLIENT-CERT) that
+        supports pre-emptive authentication. If this is not the case, the 
Tomcat
+        provided authenticators will deny the request. Custom authenticators 
may
+        allow the request.</p>
+        <p>This feature can be combined with <code>addConnectorPort</code> to
+        trigger authentication depending on the client and the connector that 
is
+        used to access an application.</p>
       </attribute>
 
     </attributes>


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

Reply via email to