EN
Java - resolve path and prevent access above parent directory
3 points
In this article, we would like to show simple way how to resolve path and prevent access above parent directory in Java.
It is common to resolve paths on server side in web applications. Simetimes it is necessary to send path as a API parameter what may be dangerous. In that case we need to control the parameter that contains ..
, ../..
, ../../..
, etc. The solution for the problem is to use resolve()
, normalize()
and startsWith()
methods what was show in the next section.
In this section you will find reusable tool that may be used to resolve paths preventing access above parent directory.
Program.java
file:
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.file.Paths;
3
4
public class Program {
5
6
public static void main(String[] args) throws IOException {
7
8
var publicPath = Paths.get("/home/john/public"); // We allow to resolve paths only under this location.
9
10
// Correct paths:
11
//
12
var picturesPath = PathUtils.resolvePath(publicPath, "pictures"); // ✅ /home/john/public/pictures
13
var moviesPath = PathUtils.resolvePath(publicPath, "movies"); // ✅ /home/john/public/movies
14
var musicPath = PathUtils.resolvePath(publicPath, "music"); // ✅ /home/john/public/music
15
16
// Forbidden paths (they throw IOException: "Access to indicated directory is forbidden."):
17
//
18
var forbiddenPath1 = PathUtils.resolvePath(publicPath, ".."); // ❌ /home/john
19
var forbiddenPath2 = PathUtils.resolvePath(publicPath, "../Desktop"); // ❌ /home/john/Desktop
20
var forbiddenPath3 = PathUtils.resolvePath(publicPath, "../../.."); // ❌ /
21
var forbiddenPath4 = PathUtils.resolvePath(publicPath, "../../../etc"); // ❌ /etc
22
}
23
}
PathUtils.java
file:
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.file.Path;
3
4
public final class PathUtils {
5
6
public static Path resolvePath(Path parent, String path) throws IOException {
7
var master = parent.normalize();
8
var result = master.resolve(path)
9
.normalize();
10
if (result.startsWith(master)) {
11
return result;
12
}
13
throw new IOException("Access to indicated directory is forbidden.");
14
}
15
16
public static Path resolvePath(Path parent, Path path) throws IOException {
17
var master = parent.normalize();
18
var result = master.resolve(path)
19
.normalize();
20
if (result.startsWith(master)) {
21
return result;
22
}
23
throw new IOException("Access to indicated directory is forbidden.");
24
}
25
}
Alternative titles
- Java - resolve path and protect access above parent directory
- Java - resolve path and block access above parent directory
- Java - resolve path and prevent access over parent directory
- Java - resolve path and protect access over parent directory
- Java - resolve path and block access over parent directory
- Java - resolve path and prevent access above base directory