...
This guideline is an instance of 17. Minimize privileged code.
Noncompliant Code Example
This noncompliant code example uses a UserLookupCallBack class that implements the CallBack interface to look up a user's name given the user's ID. This lookup code assumes that this information lives in the /etc/passwd file, which requires elevated privileges to open. Consequently, the Client class invokes all callbacks with elevated privileges (within a doPrivileged block).
...
| Code Block |
|---|
class MaliciousCallBack implements CallBack {
public void callMethod() {
// Code here gets executed with elevated privileges
}
}
public static void main(String[] args) {
CallBack callBack = new MaliciousCallBack();
CallBackAction action = new CallBackAction(callBack);
action.perform(); // Executes malicious code
} |
Compliant Solution
According to Oracle's secure coding guidelines [SCG 2010]:
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
public interface CallBack {
void callMethod();
}
class UserLookupCallBack implements CallBack {
private int uid;
private String name;
public UserLookupCallBack(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void callMethod() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try (InputStream fis = new FileInputStream("/etc/passwd")) {
// Look up userid & assign to UserLookupCallBack.this.name
} catch (IOException x) {
UserLookupCallBack.this.name = null;
}
return null;
}
});
}
}
class CallBackAction {
private CallBack callback;
public CallBackAction(CallBack callback) {
this.callback = callback;
}
public void perform() {
callback.callMethod();
}
} |
Applicability
Exposing sensitive methods through callbacks can result in misuse of privileges and arbitrary code execution.
Bibliography
[API 2011] | |
[SCG 2010] | Guideline 9-3: Safely invoke |
...