Wednesday, June 15, 2011

Twelve rules for developing more secure Java code-Rule 10


Rule 10: Make your classes nondeserializeable

This rule is even more important than the previous one. Even if your class isn't serializeable, it may still be deserializeable. An adversary can create a sequence of bytes that happens to deserialize to an instance of your class. This is dangerous, since you do not have control over what state the deserialized object is in. You can think of deserialization as another kind of public constructor for your object; unfortunately it's a kind of constructor that is difficult for you to control.
You can prevent this kind of attack by making it impossible to deserialize a byte stream into an instance of your class. You can do this by declaring the readObject method:

private final void readObject(ObjectInputStream in)

throws java.io.IOException {
        throw new java.io.IOException("Class cannot be deserialized");
}
  
As above, this method is declared final to prevent the adversary from overriding it.

No comments: