Skip to content

Commit 266804f

Browse files
markt-asfclaude
andcommitted
Close the AJP connection after a request has ended in error
recycle() resets the error state so service() carried on reading messages after a request had been rejected. A body packet that had already been sent but not read was then processed as the start of a new AJP request. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 2cc7351 commit 266804f

3 files changed

Lines changed: 142 additions & 1 deletion

File tree

‎java/org/apache/coyote/ajp/AjpProcessor.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,8 @@ public SocketState service(SocketWrapperBase<?> socket) throws IOException {
342342
// Expected to block on the first read as there should be at least one
343343
// AJP message to read.
344344
boolean firstRead = true;
345+
// recycle() resets the error state so track separately if the connection must be closed
346+
boolean closeConnection = false;
345347

346348
while (!getErrorState().isError() && !protocol.isPaused()) {
347349
// Parsing the request header
@@ -468,12 +470,21 @@ public SocketState service(SocketWrapperBase<?> socket) throws IOException {
468470
// Set keep alive timeout for next request
469471
socketWrapper.setReadTimeout(protocol.getKeepAliveTimeout());
470472

473+
/*
474+
* Recycling resets the error state. If the request ended in error, the connection must be closed without
475+
* reading any further messages. Any unread body packet is still on the connection and must not be parsed
476+
* as the start of the next request.
477+
*/
478+
closeConnection = getErrorState().isError();
471479
recycle();
480+
if (closeConnection) {
481+
break;
482+
}
472483
}
473484

474485
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
475486

476-
if (getErrorState().isError() || protocol.isPaused()) {
487+
if (closeConnection || getErrorState().isError() || protocol.isPaused()) {
477488
return SocketState.CLOSED;
478489
} else {
479490
if (isAsync()) {
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.coyote.ajp;
18+
19+
import java.io.IOException;
20+
import java.util.List;
21+
import java.util.concurrent.CopyOnWriteArrayList;
22+
23+
import jakarta.servlet.http.HttpServlet;
24+
import jakarta.servlet.http.HttpServletRequest;
25+
import jakarta.servlet.http.HttpServletResponse;
26+
27+
import org.junit.Assert;
28+
import org.junit.Test;
29+
30+
import org.apache.catalina.Context;
31+
import org.apache.catalina.startup.Tomcat;
32+
33+
public class TestAjpProcessor extends AjpBaseTest {
34+
35+
/*
36+
* When a request is rejected before the request body is read, the body packet that the proxy has already sent must
37+
* not be processed as the start of a new AJP request.
38+
*/
39+
@Test
40+
public void testUnreadBodyPacketAfterRejectedRequest() throws Exception {
41+
42+
Tomcat tomcat = getTomcatInstance();
43+
44+
// No file system docBase required
45+
Context ctx = getProgrammaticRootContext();
46+
47+
RecordingServlet servlet = new RecordingServlet();
48+
Tomcat.addServlet(ctx, "recording", servlet);
49+
ctx.addServletMapping("/", "recording");
50+
51+
tomcat.start();
52+
53+
SimpleAjpClient ajpClient = new SimpleAjpClient();
54+
ajpClient.setPort(getPort());
55+
ajpClient.connect();
56+
57+
/*
58+
* Build the body of the first body packet so that, if it is read as the next AJP message, it is a valid forward
59+
* request for /injected. The two byte chunk length (514 = 0x0202) is read as the message type (FORWARD_REQUEST)
60+
* and the method (GET) and the data that follows is read as the remainder of the forward request.
61+
*/
62+
int bodyLength = 514;
63+
ajpClient.setMethod("GET");
64+
ajpClient.setUri("/injected");
65+
TesterAjpMessage injectedMessage = ajpClient.createForwardMessage();
66+
injectedMessage.end();
67+
byte[] injectedBuffer = injectedMessage.getBuffer();
68+
// Skip the 4 byte header, the message type and the method
69+
int injectedLength = injectedMessage.getLen() - 6;
70+
Assert.assertTrue(injectedLength <= bodyLength);
71+
byte[] body = new byte[bodyLength];
72+
System.arraycopy(injectedBuffer, 6, body, 0, injectedLength);
73+
74+
// The request is rejected because of the invalid host name
75+
ajpClient.setMethod("POST");
76+
ajpClient.setUri("/rejected");
77+
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
78+
forwardMessage.addHeader("Host", "invalid_host");
79+
forwardMessage.addHeader("Content-Length", Integer.toString(bodyLength));
80+
forwardMessage.end();
81+
82+
TesterAjpMessage responseHeaders = ajpClient.sendMessage(forwardMessage, ajpClient.createBodyMessage(body));
83+
TestAbstractAjpProcessor.validateResponseHeaders(responseHeaders, 400, "400");
84+
// Response body
85+
ajpClient.readMessage();
86+
// End of response. The connection is not to be re-used.
87+
TesterAjpMessage endMessage = ajpClient.readMessage();
88+
Assert.assertEquals(0x05, endMessage.getByte());
89+
Assert.assertEquals(0x00, endMessage.getByte());
90+
91+
// The connection should now be closed without any further messages
92+
try {
93+
ajpClient.readMessage();
94+
Assert.fail("Unexpected message received. The connection should have been closed");
95+
} catch (IOException expected) {
96+
// Expected
97+
}
98+
99+
Assert.assertFalse("The unread body packet was processed as a request: " + servlet.getUris(),
100+
servlet.getUris().contains("/injected"));
101+
102+
ajpClient.disconnect();
103+
}
104+
105+
106+
static final class RecordingServlet extends HttpServlet {
107+
108+
private static final long serialVersionUID = 1L;
109+
110+
private final List<String> uris = new CopyOnWriteArrayList<>();
111+
112+
@Override
113+
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
114+
uris.add(req.getRequestURI());
115+
resp.setContentType("text/plain");
116+
resp.getWriter().print("OK");
117+
}
118+
119+
List<String> getUris() {
120+
return uris;
121+
}
122+
}
123+
124+
}

‎webapps/docs/changelog.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,12 @@
260260
get body chunk message or flush message so that the messages cannot be
261261
written part way through a response body message. (markt)
262262
</fix>
263+
<fix>
264+
Fix the AJP connector so that it closes the connection, rather than
265+
reading further messages, once a request has ended in error.
266+
Previously, a body packet that had not been read could be processed as
267+
the start of a new AJP request. (markt)
268+
</fix>
263269
</changelog>
264270
</subsection>
265271
<subsection name="Jasper">

0 commit comments

Comments
 (0)