Reading the source code for Instant
class, I bumped into this method
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
The description got me curious. What is a "malicious stream"? And how is this method defending against it?
Instant
, and other java.time
classes, are serialized using a package scoped delegate - java.time.Ser
. See the writeReplace
method to see how the delegate is created.
As such, the only way that the readObject
method could be called is if someone was passing in a malicious stream (one created for the sole purpose of trying to create an invalid object). The exception ensures such malicious streams are blocked.
In general, any time that a serialization delegate is used, you should consider blocking readObject
like this.
Joshua Bloch the author of "Effective Java" has introduced his idea about the serialization proxy pattern. Very enlightening background to your question.
With this writeReplace method in place, the serialization system will never generate a serialized instance of the enclosing class, but an attacker might fabricate one in an attempt to violate the class' invariants. To guarantee that such an attack would fail, merely add this readObject method to the enclosing class...
// readObject method for the serialization proxy pattern
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With