A user can submit a subfolder/filename to download.
The subfolder/filename will then be used to serve a file from a predertemined folder.
In the end, I am doing new File(folder, "subfolder/filename")
.
But before I do that, I also check that !"subfolder/filename".contains("..")
But is this enough? Is there possibly a scenario where two dots (..) may not come after each other, but still be interpreted as two dots when passed to new File(...) ?
Are there any other way a user can navigate back and reach content outside this folder?
Do you need to do something else to secure such a subfolder/filename access from folder?
One can get the absolute paths, from the OS, so a bit slow.
String folderPath = folder.getCanonicalPath() + File.separator;
File file = new File(folder, "subfolder/filename");
String path = file.getCanonicalPath();
if (!path.startsWith(folderPath)) {
log(Level.ERROR, "Security breach attempt: ...");
return;
}
A simple check would probably do too:
Pattern BREACH = Pattern.compile("\\.[\\\\]*\\.");
if (BREACH.matcher(path).find()) { ... }
Mind when you use version control or other "protected" files/folders, then names of files or folders starting with a dot are illegal too.