...
This noncompliant code example accepts a tainted path or file name as an argument. An attacker can access a protected file by supplying its path name as an argument to this method.
Code Block | ||
---|---|---|
| ||
private void privilegedMethod(final String filename)
throws FileNotFoundException {
try {
FileInputStream fis =
(FileInputStream) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(filename);
}
}
);
// do something with the file and then close it
} catch (PrivilegedActionException e) {
// forward to handler
}
}
|
...
This compliant solution invokes the cleanAFilenameAndPath()
method to sanitize malicious inputs. Successful completion of the sanitization method indicates that the input is acceptable and the doPrivileged()
block can be executed.
Code Block | ||
---|---|---|
| ||
private void privilegedMethod(final String filename)
throws FileNotFoundException {
final String cleanFilename;
try {
cleanFilename = cleanAFilenameAndPath(filename);
} catch (/* exception as per spec of cleanAFileNameAndPath */) {
// log or forward to handler as appropriate based on specification
// of cleanAFilenameAndPath
}
try {
FileInputStream fis =
(FileInputStream) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(cleanFilename);
}
}
);
// do something with the file and then close it
} catch (PrivilegedActionException e) {
// forward to handler
}
}
|
...
This compliant solution both explicitly hard codes the name of the file and declares the variable as static final
to prevent it from being modified. This ensures that no malicious file can be loaded by exploiting the privileged method.
Code Block | ||
---|---|---|
| ||
static final String FILEPATH = "/path/to/protected/file/fn.ext";
private void privilegedMethod() throws FileNotFoundException {
try {
FileInputStream fis =
(FileInputStream) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(FILEPATH);
}
}
);
// do something with the file and then close it
} catch (PrivilegedActionException e) {
// forward to handler and log
}
}
|
...
CWE-266. Incorrect privilege assignment | |
| CWE-272. Least privilege violation |
| CWE-732. Incorrect permission assignment for critical resource |
Secure Coding Guidelines for the Java Programming Language, Version 3.0 | Guideline 6-2. Safely invoke |
Android Implementation Details
The code examples using the java.security
package are not applicable to Android but the principle of the rule is applicable to Android apps.
Bibliography
[API 2006] | |
Sections 6.4, | |
Pixy: A Static Analysis Tool for Detecting Web Application Vulnerabilities |