import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDirectoryTraversalDefender {
public static String cleanPath(String filePath) throws IllegalArgumentException {
return cleanPath(filePath, false);
}
public static String cleanPath(String filePath, boolean useOsFileSeparatorOnResult) throws IllegalArgumentException {
if(filePath == null || filePath.trim().isEmpty()) {
return filePath;
}
filePath = filePath.trim();
String sanitizedPath = filePath.replaceAll("\\\\+", "/");
sanitizedPath = sanitizedPath.replaceAll("\\.\\.", "");
sanitizedPath = sanitizedPath.replaceAll("/\\./", "/");
sanitizedPath = sanitizedPath.replaceAll("&", "");
sanitizedPath = sanitizedPath.replaceAll("/{2,}", "/");
checkRootPathUsage(filePath, sanitizedPath);
checkUrlLikePathUsage(filePath, sanitizedPath);
return useOsFileSeparatorOnResult ?
changeFileSeparatorDependOnOs(sanitizedPath) : sanitizedPath;
}
private static void checkRootPathUsage(String filePath, String sanitizedPath) {
if (sanitizedPath.equals("/") || sanitizedPath.matches("[A-Za-z]:/$")) {
throw new IllegalArgumentException("Invalid path: " + filePath);
}
}
private static void checkUrlLikePathUsage(String filePath, String sanitizedPath) throws IllegalArgumentException {
Path path = Paths.get(sanitizedPath);
URI uri = path.toUri();
if (uri.getScheme() != null && uri.getHost() != null) {
throw new IllegalArgumentException("Path resembles a URL-like path. Error Occurred Path => " + filePath);
}
}
public static String changeFileSeparatorDependOnOs(String path) {
String osName = System.getProperty("os.name").toLowerCase();
return osName.toLowerCase().contains("win") ? path.replace("/", File.separator) : path;
}
public static File cleanPath(File file) {
String path = file.getPath();
return new File(cleanPath(path));
}
public static Path cleanPath(Path file) {
String path = file.toFile().getPath();
return Paths.get(cleanPath(path));
}
public static void main(String[] args) {
String filePath1 = "../../myfile.txt";
String filePath2 = "C:\\platform\\..\\user1\\myfile.txt";
String filePath3 = "C:\\11";
String sanitizedPath1 = cleanPath(filePath1);
String sanitizedPath2 = cleanPath(filePath3);
String sanitizedPath3 = cleanPath(filePath4);
System.out.println("Sanitized Path 1: " + sanitizedPath1);
System.out.println("Sanitized Path 2: " + sanitizedPath2);
System.out.println("Sanitized Path 3: " + sanitizedPath3);
}
}