Increasing the accessibility of overridden or hidden methods permits a malicious subclass to offer wider access to the restricted method than was originally intended. Consequently, programs must override methods only when necessary and must declare methods final whenever possible to prevent malicious subclassing. When methods cannot be declared final, programs should refrain from increasing the accessibility of overridden methods. See rule SEC01-J for more information.) Wiki Markup
Wiki Markup |
---|
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|AA. Bibliography#JLS 05](_Java Language Specification_, §8.4.8.3, "Requirements in Overriding and Hiding"\] \[[JLS 2005|AA. Bibliography#JLS 05]. The following are the allowed accesses: |
...
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
Super
defines it to be protected
. Class Sub
increases , consequently allowing class Sub
to increase the accessibility of doLogic()
by declaring its own version of the method to be public.
Code Block | ||
---|---|---|
| ||
class BadScopeSuper { protected void doLogic() { System.out.println("Super invoked"); } } public class Sub extends BadScopeSuper { 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 OBJ02-J. Minimize the accessibility of classes and their members.)This compliant solution declares the doLogic()
method final to prevent malicious overriding.
Code Block | ||
---|---|---|
| ||
class BadScopeSuper { protected final void doLogic() { // declare as final System.out.println("Super invoked"); // Do sensitive operations } } |
...
Related Guidelines
CWE-487, ". Reliance on Packagepackage-level Scope" scope | |
Secure Coding Guidelines for the Java Programming Language, Version 3.0 | Guideline 1-1. Limit the accessibility of classes, interfaces, methods, and fields |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f0245c16dd2d94d4-82025e52-410e4c22-a5adbd3c-d4bea40a0f5643feb4a5ee46"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§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> |
...