Skip to content

Commit

Permalink
Sandbox the file handler path handling for security
Browse files Browse the repository at this point in the history
The file handler was susceptible to serving resources from outside it's base
directory by using relative paths such as "../../../private.txt".
  • Loading branch information
gitblit committed Feb 20, 2015
1 parent 942696a commit f89ab72
Showing 1 changed file with 13 additions and 5 deletions.
Expand Up @@ -21,6 +21,8 @@
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
* Serves file resources.
Expand All @@ -31,11 +33,11 @@ public class FileResourceHandler extends StaticResourceHandler {

private static final Logger log = LoggerFactory.getLogger(FileResourceHandler.class);

final File directory;
final String directory;

public FileResourceHandler(String urlPath, File directory) {
super(urlPath);
this.directory = directory.getAbsoluteFile();
this.directory = directory.getAbsolutePath();
}

public FileResourceHandler(String urlPath, String directory) {
Expand All @@ -47,11 +49,17 @@ public URL getResourceUrl(String resourcePath) {
URL url = null;

try {
File file = new File(directory, resourcePath).getAbsoluteFile();
Path requestedPath = Paths.get(directory, resourcePath).normalize().toAbsolutePath();
if (!requestedPath.startsWith(directory)) {
log.warn("Request for '{}' which is not located in '{}'", requestedPath, directory);
return null;
}

File file = requestedPath.toFile();
if (file.exists() && file.isFile()) {
url = file.toURI().toURL();
url = requestedPath.toUri().toURL();
} else {
log.error("File '{}' not found", file);
log.warn("File '{}' not found", resourcePath);
}
} catch (MalformedURLException e) {
log.error(e.getMessage(), e);
Expand Down

0 comments on commit f89ab72

Please sign in to comment.