I have a security manager I'm writing for a Java program, and within the checkRead method, I wish to only allow reads to files within a given directory.
The basis of it is that it will get a canonical file for the input (which is actually a string as per the method contract). It will then begin taking the file's parent repeatedly until it either matches one of the trusted directories, or becomes null
(from trying to take the parent of the root directory). This check should be secure both on Unix/linux and Windows environments and styles of filenames. I don't need 100% certainty that a valid and allowed, but mangled or non-standard path would pass, but I certainly cannot rework the program's API to open files in a different, more secure manner, as my application's classloader needs to use this method to check its reads.
Are there any glaring issues (security or style) that anyone might see here?
File tested;
try {
tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
throw new SecurityException(
"The basedir resolution failed to resolve.");
}
File parentFile = tested;
while (parentFile != null) {
if (basedir.equals(parentFile) || classDir.equals(parentFile)) {
return;
}
parentFile = parentFile.getParentFile();
}
logger.warn("MosstestSecurityManager stopped an attempt to read a file from non-core code"
+ file);
throw new SecurityException(
"MosstestSecurityManager stopped an attempt to read a file from non-core code");