Calling overridable methods from the clone() method is insecure. First, a malicious subclass could override the method and affect the behavior of the clone() method. Second, a trusted subclass could observe (and potentially modify) the cloned object in a partially initialized state before its construction has concluded. In either case, the subclass could leave the clone, the object being cloned, or both in an inconsistent state. Consequently, clone() methods may invoke only methods that are final or private.
...
Alternative solutions that prevent invocation of overridden methods include declaring these methods private or final or declaring the class containing these methods final.
Exceptions
MET06-J-EX0: It is permitted to call a superclass's method via super.method(...), since such calls will not be dynamically dispatched to methods defined by a subclass. In fact, calling super.clone() is expected behavior.
...
Calling overridable methods on the clone under construction can expose class internals to malicious code or violate class invariants by exposing the clone to trusted code in a partially initialized state, affording the opportunity to corrupt the state of the clone, the object being cloned, or both.
Rule | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
MET06-J | Medium | Probable | Yes |
No |
P8 |
L2 |
Automated Detection
Automated detection is straightforward.
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Parasoft Jtest |
| CERT.MET06.CLONE | Make your 'clone()' method "final" for security | ||||||
| SpotBugs |
| MC_OVERRIDABLE_METHOD_CALL_IN_CLONE | Implemented (since 4.5.0) |
Bibliography
Item 11, "Override | |
...
...