Some classes contain data that must not be copied; these classes can be considered to be sensitiveClasses containing private, confidential, or otherwise sensitive data are best not copied. If a class is not meant to be copied, then failing to define copy mechanisms, such as a copy constructor, is insufficient to prevent copying.
Java's object cloning mechanism allows an attacker to manufacture new instances of a class by copying the memory images of existing objects rather than by executing the class's constructor. Often this is not an acceptable unacceptable way of creating new objects. An attacker can misuse the clone feature to manufacture multiple instances of a singleton class, create serious thread-safety issues by subclassing and cloning the subclass, bypass security checks within the constructor and violate the invariants of critical data.
...
This noncompliant code example defines class SensitiveClass
which contains a character array used to internally hold a filenamefile name, along with a Boolean
shared variable, initialized to false
. This data is not meant to be copied; consequently, SensitiveClass
lacks a copy constructor.
...
When a client requests a String
instance by invoking the get()
method, the shared
flag is set. Operations that can modify the array are subsequently prohibited, to maintain the array's consistency with the returned String
object. Consequently, the replace()
method designed to replace all elements of the array with an 'x', cannot execute normally when the flag is set. Java's cloning feature provides a way to illegally work around circumvent this constraint even though SensitiveClass
does not implement the Cloneable
interface.
...
The easiest way to prevent malicious subclasses is to declare SensitiveClass
as final.
Code Block | ||
---|---|---|
| ||
final class SensitiveClass { // ... } |
...
Code Block | ||
---|---|---|
| ||
class SensitiveClass { // ... public final SensitiveClass clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } |
This class fails to prevent malicious subclasses, but does protect the data in SensitiveClass
. Its methods are protected by being declared final
. For more information on how to handle malicious subclasses, see OBJ10-J. Provide mutable classes with copy functionality to allow passing instances to untrusted code safely.
...