What does it mean that the Instant.readObject method "Protect [s] from malicious threads"?

Reading the source code for the Instant class, I came across 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"); } 

I became interested. What is a malicious thread? And how does this method protect it?

+8
java stream java-8 java-time
source share
2 answers

Instant and other java.time classes java.time serialized using the limited package delegate - java.time.Ser . See the writeReplace method for how a delegate is created.

Thus, the only way the readObject method can be called is by passing a malicious stream (created for the sole purpose of creating an invalid object). An exception blocks such malicious streams.

In general, whenever a serialization delegate is used, you should consider locking readObject as follows.

+6
source share

Joshua Bloch, author of Effective Java, introduced his idea of a proxy serialization pattern. Very interesting background to your question.

Using this writeReplace method, the serialization system will never generate a serialized instance of the surrounding class, and the attacker can fabricate one in an attempt to violate the class' invariants. To ensure that such an attack fails, just add this readObject for the surrounding class ...

 // readObject method for the serialization proxy pattern private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } 
+4
source share

All Articles