Rule 8: Make your classes noncloneable
Java's object cloning mechanism can allow an attacker to manufacture new instances of classes you define, without executing any of your constructors. If your class isn't cloneable, the attacker can define a subclass of your class, and make the subclass implement java.lang.Cloneable. This lets an attacker create new instances of your class. The new instances are made by copying the memory images of existing objects; though this is sometimes an acceptable way to make a new object, it often is not.
Rather than worry about this, you're better off making your objects noncloneable. You can do this by defining the following method in each of your classes:
public final void clone() throws java.lang.CloneNotSupportedException {
throw new java.lang.CloneNotSupportedException();
}
If you want your class to be cloneable, and you've considered the
consequences of that choice, then you can still protect yourself. If you're
defining a clone method yourself, make it final. If you're relying on a
nonfinal clone method in one of your superclasses, then define this
method:
public final void clone() throws java.lang.CloneNotSupportedException {
super.clone();
}
This prevents an attacker from redefining your clone method.
No comments:
Post a Comment