SV.SERIAL.NOFINAL

Methods readObject() and writeObject() in serializable classes should be final

SV.SERIAL.NOFINAL is reported for a class when this class directly or indirectly implements the 'java.io.Serializable' interface, but the declared method 'readObject' or 'writeObject' is not declared as final.

Vulnerability and risk

If a class does not declare the 'readObject' and 'writeObject' methods as final, then attackers can modify objects or data that were assumed to be safe from modification.

Vulnerable code example 1

1  class SV_SERIAL_NOFINAL_Sample implements Serializable 
2  {
3      private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException
4      {
5          ...
6      }
7 }
   

Klocwork reports an SV.SERIAL.NOFINAL defect on line 3, indicating, "private void readObject(ObjectInputStream aInputStream): Class 'SV_SERIAL_NOFINAL_Sample' implements 'java.io.serializable', but method 'readObject' is not final."

Fixed code example 1

1  class SV_SERIAL_NOFINAL_Sample implements Serializable 
2  {
3      private final void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException
4      {
5          ...
6      }
7 }

In this example, Klocwork no longer reports an SV.SERIAL.NOFINAL defect on line 3 because the method 'readObject' is declared as final.

Vulnerable code example 2

1  class SV_SERIAL_NOFINAL_Sample_1 implements Serializable 
2  {     
3      private void writeObject(ObjectInputStream aInputStream) throws IOException
4      {
5          ...
6     }
7 }

In this example, Klocwork report a SV.SERIAL.NOFINAL defect on line 3, indicating, "private void writeObject(ObjectInputStream aInputStream): Class 'SV_SERIAL_NOFINAL_Sample' implements 'java.io.serializable' , but method 'writeObject' is not final."

Fixed code example 2

1  class SV_SERIAL_NOFINAL_Sample_1 implements Serializable 
2  {     
3      private final void writeObject(ObjectInputStream aInputStream) throws IOException
4      {
5          ...
6     }
7 }

Klocwork no longer reports an SV.SERIAL.NOFINAL defect on line 3 because the method 'readObject' is declared as final.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.