Increasing the accessibility of overridden or hidden methods permits a malicious subclass to offer wider access to the restricted method than was originally intended. The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method [[JLS 2005], Section 8.4.8.3, "Requirements in Overriding and Hiding"]. The following are the allowed accesses:
Overridden/hidden method modifier |
Overriding/hiding method modifier |
---|---|
|
|
|
|
default |
default or |
|
Cannot be overridden |
Noncompliant Code Example
This noncompliant code example demonstrates how a malicious subclass Sub
can both override the doLogic()
method of the superclass and also increase the accessibility of the overriding method. Any user of Sub
can invoke the doLogic
method because the base class BadScope
defines it to be protected
. Class Sub
increases the accessibility of doLogic
by declaring its own version of the method to be public.
class BadScope { protected void doLogic() { System.out.println("Super invoked"); } } public class Sub extends BadScope { public void doLogic() { System.out.println("Sub invoked"); // Do sensitive operations } }
Compliant Solution
Override methods only when necessary. Declare methods and fields final whenever possible to avoid malicious subclassing. When methods and fields cannot be declared final, refrain from increasing the accessibility of overridden methods. (See rule SEC01-J. Minimize the accessibility of classes and their members.)
class BadScope { protected final void doLogic() { // declare as final System.out.println("Super invoked"); // Do sensitive operations } }
Exceptions
MET17-EX0: For classes that implement the java.lang.Cloneable
interface, the accessibility of the Object.clone()
method should be increased from protected to public [SCG 2007.
Risk Assessment
Subclassing allows weakening of access restrictions, which can compromise the security of a Java application.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MET17-J |
medium |
probable |
medium |
P8 |
L2 |
Automated Detection
Detecting violations of this rule is straightforward.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CWE-487 "Reliance on Package-level Scope" |
|
Guideline 1-1 Limit the accessibility of classes, interfaces, methods, and fields |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a4f0c2c8-fd75-4bb4-97ef-990a17940791"><ac:plain-text-body><![CDATA[ |
[[JLS 2005 |
AA. Bibliography#JLS 05]] |
[Section 8.4.8.3 |
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8.3], "Requirements in Overriding and Hiding" |
]]></ac:plain-text-body></ac:structured-macro> |
MET15-J. Do not use deprecated or obsolete classes or methods 05. Methods (MET) MET18-J. Do not use finalizers