Skip to content

Commit

Permalink
Extract shared resource handling utility methods
Browse files Browse the repository at this point in the history
Closes: gh-33574
  • Loading branch information
rstoyanchev committed Sep 20, 2024
1 parent df5489b commit c6fa180
Show file tree
Hide file tree
Showing 8 changed files with 493 additions and 657 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,14 @@

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

import reactor.core.publisher.Mono;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.server.PathContainer;
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.reactive.resource.ResourceHandlerUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

Expand Down Expand Up @@ -64,21 +58,14 @@ public Mono<Resource> apply(ServerRequest request) {
}

pathContainer = this.pattern.extractPathWithinPattern(pathContainer);
String path = processPath(pathContainer.value());
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
String path = ResourceHandlerUtils.normalizeInputPath(pathContainer.value());
if (ResourceHandlerUtils.shouldIgnoreInputPath(path)) {
return Mono.empty();
}
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)) {
Resource resource = ResourceHandlerUtils.createRelativeResource(this.location, path);
if (resource.isReadable() && ResourceHandlerUtils.isResourceUnderLocation(this.location, resource)) {
return Mono.just(resource);
}
else {
Expand All @@ -90,147 +77,6 @@ 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>
*/
protected 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) == '/') {
slash = true;
}
else if (path.charAt(i) > ' ' && path.charAt(i) != 127) {
if (i == 0 || (i == 1 && slash)) {
return path;
}
return (slash ? "/" + path.substring(i) : path.substring(i));
}
}
return (slash ? "/" : "");
}

private boolean isInvalidPath(String path) {
if (path.contains("WEB-INF") || path.contains("META-INF")) {
return true;
}
if (path.contains(":/")) {
String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
return true;
}
}
if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
return true;
}
return false;
}

/**
* 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);
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
}
return false;
}

private boolean isResourceUnderLocation(Resource resource) throws IOException {
if (resource.getClass() != this.location.getClass()) {
return false;
}

String resourcePath;
String locationPath;

if (resource instanceof UrlResource) {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(this.location.getURL().toString());
}
else if (resource instanceof ClassPathResource classPathResource) {
resourcePath = classPathResource.getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(this.location.getURL().getPath());
}

if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
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);
if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
}
return false;
}

@Override
public String toString() {
return this.pattern + " -> " + this.location;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -17,22 +17,17 @@
package org.springframework.web.reactive.resource;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriUtils;

/**
* A simple {@code ResourceResolver} that tries to find a resource under the given
Expand Down Expand Up @@ -111,10 +106,7 @@ private Mono<Resource> getResource(String resourcePath, List<? extends Resource>
*/
protected Mono<Resource> getResource(String resourcePath, Resource location) {
try {
if (!(location instanceof UrlResource)) {
resourcePath = UriUtils.decode(resourcePath, StandardCharsets.UTF_8);
}
Resource resource = location.createRelative(resourcePath);
Resource resource = ResourceHandlerUtils.createRelativeResource(location, resourcePath);
if (resource.isReadable()) {
if (checkResource(resource, location)) {
return Mono.just(resource);
Expand Down Expand Up @@ -154,61 +146,15 @@ else if (logger.isWarnEnabled()) {
* @return "true" if resource is in a valid location, "false" otherwise
*/
protected boolean checkResource(Resource resource, Resource location) throws IOException {
if (isResourceUnderLocation(resource, location)) {
if (ResourceHandlerUtils.isResourceUnderLocation(location, resource)) {
return true;
}
if (getAllowedLocations() != null) {
for (Resource current : getAllowedLocations()) {
if (isResourceUnderLocation(resource, current)) {
return true;
}
}
}
return false;
}

private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException {
if (resource.getClass() != location.getClass()) {
return false;
}

String resourcePath;
String locationPath;

if (resource instanceof UrlResource) {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(location.getURL().toString());
}
else if (resource instanceof ClassPathResource classPathResource) {
resourcePath = classPathResource.getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(location.getURL().getPath());
}

if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
return (resourcePath.startsWith(locationPath) && !isInvalidEncodedPath(resourcePath));
}

private boolean isInvalidEncodedPath(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);
if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
logger.warn(LogFormatUtils.formatValue(
"Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath, -1, true));
if (ResourceHandlerUtils.isResourceUnderLocation(current, resource)) {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
}
return false;
}
Expand Down
Loading

0 comments on commit c6fa180

Please sign in to comment.