Skip to content

Commit cfae709

Browse files
markt-asfclaude
andcommitted
Fix AsyncContext.dispatch() when the request URI contains dot segments
getContextPathEncoded() returned the first prefix of the request URI that matched the context path. If the remainder of the URI then climbed out of the context (e.g. /examples/../examples/async/async0 or /examples/a/b/c/../../../../examples/async/async0) the dispatch path was rejected, an UnsupportedOperationException was thrown and, if the caller was not a container thread, the request stayed in the async state until it timed out. Keep extending the candidate until the remainder stays within the context and fall back to the first match if there is no such candidate. Also check that there is a dispatcher before updating the async attributes so a failed dispatch does not modify the request. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> (cherry picked from commit 721d23f)
1 parent 675815f commit cfae709

6 files changed

Lines changed: 691 additions & 45 deletions

File tree

‎java/org/apache/catalina/core/ApplicationContext.java‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,15 @@ public RequestDispatcher getRequestDispatcher(final String path) {
379379
if (path == null) {
380380
return null;
381381
}
382-
if (!path.startsWith("/")) {
382+
/*
383+
* The path must start with a '/'. The exception is a path from AsyncContext.dispatch(). That is a substring of
384+
* the request URI and, as the connector may treat an encoded solidus (%2f) or an encoded reverse solidus (%5c)
385+
* as a path separator, it may start with one. Whether such a path is valid depends on the configuration of the
386+
* Context so that is checked once the path has been decoded.
387+
*/
388+
boolean startsWithEncodedSeparator = AsyncContextImpl.uriEncoded.get().booleanValue() &&
389+
(path.regionMatches(true, 0, "%2f", 0, 3) || path.regionMatches(true, 0, "%5c", 0, 3));
390+
if (!path.startsWith("/") && !startsWithEncodedSeparator) {
383391
throw new IllegalArgumentException(sm.getString("applicationContext.requestDispatcher.iae", path));
384392
}
385393

@@ -409,6 +417,12 @@ public RequestDispatcher getRequestDispatcher(final String path) {
409417
context.getEncodedReverseSolidusHandlingEnum());
410418
}
411419

420+
if (startsWithEncodedSeparator && !uriToMap.startsWith("/") && !uriToMap.startsWith("\\")) {
421+
// The encoded separator at the start of the path was not decoded (it is being passed through) so the path
422+
// does not start with a '/'
423+
throw new IllegalArgumentException(sm.getString("applicationContext.requestDispatcher.iae", path));
424+
}
425+
412426
// Then normalize
413427
uriToMap = RequestUtil.normalize(uriToMap);
414428
if (uriToMap == null) {

‎java/org/apache/catalina/core/AsyncContextImpl.java‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -271,18 +271,20 @@ public void dispatch(ServletContext servletContext, String path) {
271271
if (dispatch != null) {
272272
throw new IllegalStateException(sm.getString("asyncContextImpl.dispatchingStarted"));
273273
}
274+
final RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(path);
275+
if (!(requestDispatcher instanceof AsyncDispatcher)) {
276+
// Fail before changing the state of the request so the caller can recover (e.g. complete() or
277+
// dispatch to a different path)
278+
throw new UnsupportedOperationException(sm.getString("asyncContextImpl.noAsyncDispatcher"));
279+
}
280+
final AsyncDispatcher applicationDispatcher = (AsyncDispatcher) requestDispatcher;
274281
if (request.getAttribute(ASYNC_REQUEST_URI) == null) {
275282
request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
276283
request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
277284
request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
278285
request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
279286
request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString());
280287
}
281-
final RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(path);
282-
if (!(requestDispatcher instanceof AsyncDispatcher)) {
283-
throw new UnsupportedOperationException(sm.getString("asyncContextImpl.noAsyncDispatcher"));
284-
}
285-
final AsyncDispatcher applicationDispatcher = (AsyncDispatcher) requestDispatcher;
286288
final ServletRequest servletRequest = getRequest();
287289
final ServletResponse servletResponse = getResponse();
288290
this.dispatch = new AsyncRunnable(request, applicationDispatcher, servletRequest, servletResponse);

‎java/org/apache/catalina/util/RequestUtil.java‎

Lines changed: 99 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ public final class RequestUtil {
3636

3737
private static final StringManager sm = StringManager.getManager(RequestUtil.class);
3838

39+
// Marker for 'no candidate has matched the context path yet'. -1 is used to represent the end of the URI.
40+
private static final int NO_MATCH = -2;
41+
3942
/**
4043
* Default constructor.
4144
*/
@@ -221,6 +224,7 @@ public static String getContextPathEncoded(Request request) {
221224
String canonicalContextPath = request.getServletContext().getContextPath();
222225
Connector connector = request.getConnector();
223226
EncodedSolidusHandling encodedSolidusHandling = connector.getEncodedSolidusHandlingInternal();
227+
EncodedSolidusHandling encodedReverseSolidusHandling = connector.getEncodedReverseSolidusHandlingInternal();
224228

225229
int pos = 0;
226230
if (!context.getAllowMultipleLeadingForwardSlashInPath()) {
@@ -237,49 +241,89 @@ public static String getContextPathEncoded(Request request) {
237241
char[] uriChars = uri.toCharArray();
238242
// Need at least the number of slashes in the context path
239243
while (lastSlash > 0) {
240-
pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling);
244+
pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling, encodedReverseSolidusHandling);
241245
if (pos == -1) {
242246
break;
243247
}
244248
lastSlash--;
245249
}
246-
// Now allow for path parameters, normalization and/or encoding.
247-
// Essentially, keep extending the candidate path up to the next slash
248-
// until the decoded and normalized candidate path (with the path
249-
// parameters removed) is the same as the canonical path.
250-
String candidate;
251-
if (pos == -1) {
252-
candidate = uri;
253-
} else {
254-
candidate = uri.substring(0, pos);
255-
}
256-
candidate = removePathParameters(candidate);
257-
candidate = UDecoder.URLDecode(candidate, connector.getURICharset());
258-
candidate = org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
259-
boolean match = canonicalContextPath.equals(candidate);
260-
while (!match && pos != -1) {
261-
pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling);
262-
if (pos == -1) {
263-
candidate = uri;
264-
} else {
265-
candidate = uri.substring(0, pos);
266-
}
250+
/*
251+
* Now allow for path parameters, normalization and/or encoding. Essentially, keep extending the candidate path
252+
* up to the next slash until the decoded and normalized candidate path (with the path parameters removed) is
253+
* the same as the canonical path.
254+
*
255+
* There may be more than one candidate that matches. For example, /examples/../examples matches the context
256+
* path /examples as does /examples. If the remainder of the URI after the first candidate climbs out of the
257+
* context (e.g. /../examples/foo or /a/b/../../../examples/foo) then the context path in the URI must be
258+
* longer. Keep going until a candidate that matches is followed by a remainder that stays within the
259+
* context. If there isn't one, fall back to the first match, which is what was returned before the remainder
260+
* was considered. That should only be possible for a URI that the connector would not have mapped to this
261+
* context in which case no candidate can be used for a dispatch.
262+
*/
263+
int firstMatchPos = NO_MATCH;
264+
while (true) {
265+
String candidate = pos == -1 ? uri : uri.substring(0, pos);
267266
candidate = removePathParameters(candidate);
268-
candidate = UDecoder.URLDecode(candidate, connector.getURICharset());
269-
candidate = org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
270-
match = canonicalContextPath.equals(candidate);
271-
}
272-
if (match) {
267+
try {
268+
candidate = decode(candidate, connector);
269+
candidate = org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
270+
} catch (IllegalArgumentException iae) {
271+
// Invalid or rejected encoding. This candidate can't match.
272+
candidate = null;
273+
}
274+
if (canonicalContextPath.equals(candidate)) {
275+
if (firstMatchPos == NO_MATCH) {
276+
firstMatchPos = pos;
277+
}
278+
if (pos == -1 || isRemainderWithinContext(uri.substring(pos), connector)) {
279+
return pos == -1 ? uri : uri.substring(0, pos);
280+
}
281+
}
273282
if (pos == -1) {
274-
return uri;
275-
} else {
276-
return uri.substring(0, pos);
283+
break;
277284
}
278-
} else {
279-
// Should never happen
280-
throw new IllegalStateException(
281-
sm.getString("requestUtil.getContextPath.ise", canonicalContextPath, uri));
285+
pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling, encodedReverseSolidusHandling);
282286
}
287+
288+
if (firstMatchPos != NO_MATCH) {
289+
return firstMatchPos == -1 ? uri : uri.substring(0, firstMatchPos);
290+
}
291+
292+
// Should never happen
293+
throw new IllegalStateException(sm.getString("requestUtil.getContextPath.ise", canonicalContextPath, uri));
294+
}
295+
296+
297+
/**
298+
* Does the remainder of the URI, after the context path, stay within the context once path parameters have been
299+
* removed, it has been decoded and normalized? This is the same processing that is applied to the path of a
300+
* dispatch so a remainder that fails this test could not be used for one. The decoding must follow the connector's
301+
* configuration for encoded solidus and reverse solidus. If, for example, they are passed through, an encoded
302+
* solidus is part of a path segment and not a separator so it can not be part of a '..' that leaves the context.
303+
*/
304+
private static boolean isRemainderWithinContext(String remainder, Connector connector) {
305+
String path = removePathParameters(remainder);
306+
try {
307+
path = decode(path, connector);
308+
} catch (IllegalArgumentException iae) {
309+
/*
310+
* Invalid or, more likely, rejected encoding. A request with such a URI would have been rejected before
311+
* it was processed. Don't look for a longer context path.
312+
*/
313+
return true;
314+
}
315+
return org.apache.tomcat.util.http.RequestUtil.normalize(path) != null;
316+
}
317+
318+
319+
/**
320+
* Decode part of a request URI using the connector's configuration for encoded solidus and reverse solidus. These
321+
* must be handled in the same way as when the connector processed the request URI. If, for example, they are
322+
* passed through, an encoded solidus is part of a path segment and not a separator.
323+
*/
324+
private static String decode(String input, Connector connector) {
325+
return UDecoder.URLDecode(input, connector.getURICharset(), connector.getEncodedSolidusHandlingInternal(),
326+
connector.getEncodedReverseSolidusHandlingInternal());
283327
}
284328

285329

@@ -309,16 +353,32 @@ private static String removePathParameters(String input) {
309353
}
310354

311355

312-
private static int nextSlash(char[] uri, int startPos, EncodedSolidusHandling encodedSolidusHandling) {
356+
private static int nextSlash(char[] uri, int startPos, EncodedSolidusHandling encodedSolidusHandling,
357+
EncodedSolidusHandling encodedReverseSolidusHandling) {
313358
int len = uri.length;
314359
int pos = startPos;
315360
while (pos < len) {
316361
if (uri[pos] == '/') {
317362
return pos;
318-
} else if (encodedSolidusHandling == EncodedSolidusHandling.DECODE &&
319-
uri[pos] == '%' && pos + 2 < len && uri[pos + 1] == '2' &&
320-
(uri[pos + 2] == 'f' || uri[pos + 2] == 'F')) {
321-
return pos;
363+
} else if (uri[pos] == ';') {
364+
/*
365+
* Path parameters are removed before the URI is decoded so anything that looks like an encoded solidus
366+
* (or reverse solidus) within them is not a separator. Skip to the end of the path parameters which is
367+
* the next solidus.
368+
*/
369+
do {
370+
pos++;
371+
} while (pos < len && uri[pos] != '/');
372+
return pos < len ? pos : -1;
373+
} else if (uri[pos] == '%' && pos + 2 < len) {
374+
// An encoded solidus (or reverse solidus) is a separator if the connector decodes it
375+
if (encodedSolidusHandling == EncodedSolidusHandling.DECODE && uri[pos + 1] == '2' &&
376+
(uri[pos + 2] == 'f' || uri[pos + 2] == 'F')) {
377+
return pos;
378+
} else if (encodedReverseSolidusHandling == EncodedSolidusHandling.DECODE && uri[pos + 1] == '5' &&
379+
(uri[pos + 2] == 'c' || uri[pos + 2] == 'C')) {
380+
return pos;
381+
}
322382
}
323383
pos++;
324384
}

0 commit comments

Comments
 (0)