...
Code Block | ||
---|---|---|
| ||
public class BigInteger { public BigInteger(String str) { this(str, check()); } private BigInteger(String str, boolean dummy) { // regular construction goes here } private static boolean check() { securityManagerCheck(); return true; } } |
Noncompliant Code Example (Data-Driven Execution)
Code in privileged blocks should be as simple as possible, both to improve reliability and to simplify security audits. Invocation of overridable methods permits modification of the code that is executed in the privileged context without modification of previously audited classes. Furthermore, calling overridable methods disperses the code over multiple classes, making it harder to determine which code must be audited. Malicious subclasses cannot directly exploit this issue because privileges are dropped as soon as unprivileged code is executed. Nevertheless, maintainers of the subclasses might unintentionally violate the requirements of the base class. For example, even when the base class's overridable method is thread-safe, a subclass might provide an implementation that lacks this property, leading to security vulnerabilities.
This noncompliant code example invokes an overridable getMethodName()
method in the privileged block using the reflection mechanism.
Code Block | ||
---|---|---|
| ||
public class MethodInvoker {
public void invokeMethod() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Class<?> thisClass = MethodInvoker.class;
String methodName = getMethodName();
Method method = thisClass.getMethod(methodName, null);
method.invoke(new MethodInvoker(), null);
} catch (Throwable t) {
// Forward to handler
}
return null;
}
}
);
}
String getMethodName() {
return "someMethod";
}
public void someMethod() {
// ...
}
// Other methods
}
|
A subclass can override getMethodName()
to return a string other than "someMethod"
. If an object of such a subclass runs invokeMethod()
, control flow will divert to a method other than someMethod()
.
Compliant Solution (Final)
This compliant solution declares the getMethodName()
method final so that it cannot be overridden.
Code Block | ||
---|---|---|
| ||
final String getMethodName() {
// ...
}
|
Alternative approaches that prevent overriding of the getMethodName()
method include declaring it as private or declaring the enclosing class as final.
Risk Assessment
Permitting a nonfinal class or method to be inherited without checking the class instance allows a malicious subclass to misuse the privileges of the class.
...