Skip to content

Commit

Permalink
RouterFunctions resource handling improvements
Browse files Browse the repository at this point in the history
Cherry pick of :
a) Use encoded resource path instead of input path validation in spring-webflux spring-projects#33568
b) Updates to resource handling for functional endpoints spring-projects#33434

This Addresses CVE-2024-38819 and CVE-2024-38816
  • Loading branch information
abhinaynagpal committed Jan 7, 2025
1 parent bda04f0 commit 27f031d
Show file tree
Hide file tree
Showing 2 changed files with 199 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;

Expand All @@ -30,6 +32,7 @@
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

Expand Down Expand Up @@ -63,13 +66,17 @@ public Mono<Resource> apply(ServerRequest request) {

pathContainer = this.pattern.extractPathWithinPattern(pathContainer);
String path = processPath(pathContainer.value());
if (path.contains("%")) {
path = StringUtils.uriDecode(path, StandardCharsets.UTF_8);
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
return Mono.empty();
}
if (!StringUtils.hasLength(path) || isInvalidPath(path)) {
if (isInvalidEncodedInputPath(path)) {
return Mono.empty();
}

if (!(this.location instanceof UrlResource)) {
path = UriUtils.decode(path, StandardCharsets.UTF_8);
}

try {
Resource resource = this.location.createRelative(path);
if (resource.isReadable() && isResourceUnderLocation(resource)) {
Expand All @@ -84,7 +91,47 @@ public Mono<Resource> apply(ServerRequest request) {
}
}

/**
* Process the given resource path.
* <p>The default implementation replaces:
* <ul>
* <li>Backslash with forward slash.
* <li>Duplicate occurrences of slash with a single slash.
* <li>Any combination of leading slash and control characters (00-1F and 7F)
* with a single "/" or "". For example {@code " / // foo/bar"}
* becomes {@code "/foo/bar"}.
* </ul>
*/
private String processPath(String path) {
path = StringUtils.replace(path, "\\", "/");
path = cleanDuplicateSlashes(path);
return cleanLeadingSlash(path);
}

private String cleanDuplicateSlashes(String path) {
StringBuilder sb = null;
char prev = 0;
for (int i = 0; i < path.length(); i++) {
char curr = path.charAt(i);
try {
if (curr == '/' && prev == '/') {
if (sb == null) {
sb = new StringBuilder(path.substring(0, i));
}
continue;
}
if (sb != null) {
sb.append(path.charAt(i));
}
}
finally {
prev = curr;
}
}
return (sb != null ? sb.toString() : path);
}

private String cleanLeadingSlash(String path) {
boolean slash = false;
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '/') {
Expand All @@ -94,8 +141,7 @@ else if (path.charAt(i) > ' ' && path.charAt(i) != 127) {
if (i == 0 || (i == 1 && slash)) {
return path;
}
path = slash ? "/" + path.substring(i) : path.substring(i);
return path;
return (slash ? "/" + path.substring(i) : path.substring(i));
}
}
return (slash ? "/" : "");
Expand All @@ -111,8 +157,33 @@ private boolean isInvalidPath(String path) {
return true;
}
}
if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
return true;
return path.contains("..") && StringUtils.cleanPath(path).contains("../");
}

/**
* Check whether the given path contains invalid escape sequences.
* @param path the path to validate
* @return {@code true} if the path is invalid, {@code false} otherwise
*/
private boolean isInvalidEncodedInputPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// May not be possible to decode...
}
}
return false;
}
Expand Down Expand Up @@ -142,15 +213,27 @@ else if (resource instanceof ClassPathResource) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
if (!resourcePath.startsWith(locationPath)) {
return false;
}
if (resourcePath.contains("%") && StringUtils.uriDecode(resourcePath, StandardCharsets.UTF_8).contains("../")) {
return false;
}
return true;
return (resourcePath.startsWith(locationPath) && !isInvalidEncodedResourcePath(resourcePath));
}

private boolean isInvalidEncodedResourcePath(String resourcePath) {
if (resourcePath.contains("%")) {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
try {
String decodedPath = URLDecoder.decode(resourcePath, StandardCharsets.UTF_8.name());
if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// May not be possible to decode...
}
}
return false;
}

@Override
public String toString() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.function.Function;
Expand All @@ -29,6 +31,8 @@
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

Expand Down Expand Up @@ -62,12 +66,15 @@ public Optional<Resource> apply(ServerRequest request) {

pathContainer = this.pattern.extractPathWithinPattern(pathContainer);
String path = processPath(pathContainer.value());
if (path.contains("%")) {
path = StringUtils.uriDecode(path, StandardCharsets.UTF_8);
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
return Optional.empty();
}
if (!StringUtils.hasLength(path) || isInvalidPath(path)) {
if (isInvalidEncodedInputPath(path)) {
return Optional.empty();
}
if (!(this.location instanceof UrlResource)) {
path = UriUtils.decode(path, StandardCharsets.UTF_8);
}

try {
Resource resource = this.location.createRelative(path);
Expand All @@ -83,7 +90,47 @@ public Optional<Resource> apply(ServerRequest request) {
}
}

/**
* Process the given resource path.
* <p>The default implementation replaces:
* <ul>
* <li>Backslash with forward slash.
* <li>Duplicate occurrences of slash with a single slash.
* <li>Any combination of leading slash and control characters (00-1F and 7F)
* with a single "/" or "". For example {@code " / // foo/bar"}
* becomes {@code "/foo/bar"}.
* </ul>
*/
private String processPath(String path) {
path = StringUtils.replace(path, "\\", "/");
path = cleanDuplicateSlashes(path);
return cleanLeadingSlash(path);
}

private String cleanDuplicateSlashes(String path) {
StringBuilder sb = null;
char prev = 0;
for (int i = 0; i < path.length(); i++) {
char curr = path.charAt(i);
try {
if (curr == '/' && prev == '/') {
if (sb == null) {
sb = new StringBuilder(path.substring(0, i));
}
continue;
}
if (sb != null) {
sb.append(path.charAt(i));
}
}
finally {
prev = curr;
}
}
return (sb != null ? sb.toString() : path);
}

private String cleanLeadingSlash(String path) {
boolean slash = false;
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '/') {
Expand All @@ -93,8 +140,7 @@ else if (path.charAt(i) > ' ' && path.charAt(i) != 127) {
if (i == 0 || (i == 1 && slash)) {
return path;
}
path = slash ? "/" + path.substring(i) : path.substring(i);
return path;
return (slash ? "/" + path.substring(i) : path.substring(i));
}
}
return (slash ? "/" : "");
Expand All @@ -113,6 +159,34 @@ private boolean isInvalidPath(String path) {
return path.contains("..") && StringUtils.cleanPath(path).contains("../");
}

/**
* Check whether the given path contains invalid escape sequences.
* @param path the path to validate
* @return {@code true} if the path is invalid, {@code false} otherwise
*/
private boolean isInvalidEncodedInputPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// May not be possible to decode...
}
}
return false;
}

private boolean isResourceUnderLocation(Resource resource) throws IOException {
if (resource.getClass() != this.location.getClass()) {
return false;
Expand All @@ -129,6 +203,10 @@ else if (resource instanceof ClassPathResource) {
resourcePath = ((ClassPathResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
}
else if (resource instanceof ServletContextResource) {
resourcePath = ((ServletContextResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ServletContextResource) this.location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(this.location.getURL().getPath());
Expand All @@ -138,13 +216,27 @@ else if (resource instanceof ClassPathResource) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
if (!resourcePath.startsWith(locationPath)) {
return false;
}
return !resourcePath.contains("%") ||
!StringUtils.uriDecode(resourcePath, StandardCharsets.UTF_8).contains("../");
return (resourcePath.startsWith(locationPath) && !isInvalidEncodedResourcePath(resourcePath));
}

private boolean isInvalidEncodedResourcePath(String resourcePath) {
if (resourcePath.contains("%")) {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
try {
String decodedPath = URLDecoder.decode(resourcePath, StandardCharsets.UTF_8.name());
if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// May not be possible to decode...
}
}
return false;
}

@Override
public String toString() {
Expand Down

0 comments on commit 27f031d

Please sign in to comment.