Avoiding Directory Traversal in Java
Publish date: Jan 28, 2022
Directory traversal attacks are one of the most common form of security issues in Java when handling untrusted paths/filenames provided by users. In general, these files/paths are expected to lie within a document root directory. When an attacker provides a relative path such as ../../etc/shadow
, the resulting file read/write operation could affect a sensitive file in another location on the server. A simple check like presence of ..
may not be enough to prevent such attacks due to presence of symlinks, string encoding issues, file name containing such strings etc.
Below is a function that prevents directory traversal attacks by handling encoding issues, symlinks, file names etc, and provides a safe path always within the document root directory provided as first argument by developer and throws a proper exception if user provided path is invalid or malicious.
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
...
public static Path safePathJoin(Path basePath, Path unsafeRelativePath) {
Path absBasePath = basePath.normalize().toAbsolutePath();
Path absunsafeRelativePath = unsafeRelativePath.normalize().toAbsolutePath();
if (! absunsafeRelativePath.startsWith(absBasePath)) throw new InvalidPathException("Invalid Path", "");
return absunsafeRelativePath;
}