...
Consequently, the hashcode of an object need not remain consistent across different executions of the application. Similarly, if an object is serialized, its hashcode may not stay consistent with the original value. This introduces several hurdles; for example, upon deserialization it is impossible to retrieve the object because its corresponding key value could have changed.
Noncompliant Code Example
Wiki Markup |
---|
This noncompliant code example uses the {{Key}} class as the key index for the {{Hashtable}}. According to the Java API \[[API 06|AA. Java References#API 06]\] class {{Hashtable}} documentation: |
...
Code Block | ||
---|---|---|
| ||
class Key implements Serializable { // Overrides hashcode and equals methods } class HashSer { public static void main(String[] args) throws IOException, ClassNotFoundException { Hashtable<Key,String> ht = new Hashtable<Key, String>(); Key key = new Key(); ht.put(key, "Value"); System.out.println("Entry: " + ht.get(key)); // Retrieve using the key, works // Serialize the Hashtable object FileOutputStream fos = new FileOutputStream("hashdata.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ht); oos.close(); // Deserialize the Hashtable object FileInputStream fis = new FileInputStream("hashdata.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Hashtable<Key, String> ht_in = (Hashtable<Key, String>)(ois.readObject()); ois.close(); if(ht_in.contains("Value")) // Check if the object actually exists in the Hashtable System.out.println("Value was found in deserialized object."); if (ht_in.get(key) == null) // Gets printed System.out.println("Object was not found when retrieved using the key."); } } |
Compliant Solution
One solution is to change the type of the key value so that it remains consistent across different runs of the program and a multitude of JVMs. This can be achieved by using an Integer
object, for example, to hold the key values.
...
This problem can also be avoided by overriding the equals()
and the hashcode()
method in the Key
class, though it is best to avoid employing hash tables that are known to use implementation defined parameters.
Risk Assessment
Serializing objects with implementation defined characteristics can corrupt the state of the object.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SER36- J | low | probable | high | P2 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class {{Object}}, Class {{Hashtable}} \[[Bloch 08|AA. Java References#Bloch 08]\] Item 75: "Consider using a custom serialized form" |
...