Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean that Instant.readObject method "Defend[s] against malicious streams"?

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?

like image 551
Luigi Cortese Avatar asked Dec 11 '15 11:12

Luigi Cortese


2 Answers

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.

like image 150
JodaStephen Avatar answered Oct 18 '22 18:10

JodaStephen


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");
}
like image 29
Meno Hochschild Avatar answered Oct 18 '22 17:10

Meno Hochschild