...
| Code Block |
|---|
|
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = openPasswordFile(password_file); // call the privileged method here
}catch(FileNotFoundException cnf) {
System.err.println("Error: Operation could not be performed");
}
return null;
}
});
// other operations
|
Noncompliant Code Example
Sometimes code needs to take into account the privileges of another context while performing a security critical action. If such code is granted the privileges of the currently executing thread, a vulnerability is exposed. This noncompliant code example shows a library method that allows all callers to perform a privileged operation (such as a read or write to a file) by using the wrapper method performActionOnFile(). The corresponding code is granted the permissions to both read and write the file. However, the caller wants only read access to the file to prevent any misuse. This code violates the principle of least privilege by also providing the caller with write access.
| Code Block |
|---|
|
private void openFile() {
final FileInputStream f[] = {null};
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("file");
} catch(FileNotFoundException cnf) {
System.err.println("Error: Operation could not be performed");
}
return null;
}
});
}
// wrapper method
public void performActionOnFile() {
openFile();
}
|
Compliant Solution
The two argument form of doPrivileged() accepts an AccessControlContext object from the caller and restricts the privileges of the contained code to the intersection of the permissions of the current execution context's domains and those of the context passed as the second argument. Consequently, a caller that requires only read permission to the file can pass a context that has only the file read permission.
| Code Block |
|---|
|
private void openFile(AccessControlContext context) {
final FileInputStream f[] = {null};
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("file");
} catch(FileNotFoundException cnf) {
System.err.println("Error: Operation could not be performed");
}
return null;
}
},context); // restrict the privileges by passing the context argument
}
// wrapper method
public void performActionOnFile(AccessControlContext acc) {
openFile(acc); // caller's AccessControlContext
}
|
Risk Assessment
Failure to follow the principle of least privilege can lead to privilege escalation attacks when a vulnerability is exploited.
...