|
1 | 1 | <p>This rule raises an issue on a non-transient and non-serializable field within a serializable class, if said class does not have
|
2 | 2 | <code>writeObject</code> and <code>readObject</code> methods defined.</p>
|
3 | 3 | <h2>Why is this an issue?</h2>
|
4 |
| -<p>By contract, fields in a <code>Serializable</code> class must themselves be either <code>Serializable</code> or <code>transient</code>. Even if the |
5 |
| -class is never explicitly serialized or deserialized, it is not safe to assume that this cannot happen. For instance, under load, most J2EE |
6 |
| -application frameworks flush objects to disk.</p> |
| 4 | +<p>By contract, non-static fields in a <code>Serializable</code> class must themselves be either <code>Serializable</code> or <code>transient</code>. |
| 5 | +Even if the class is never explicitly serialized or deserialized, it is not safe to assume that this cannot happen. For instance, under load, most |
| 6 | +J2EE application frameworks flush objects to disk.</p> |
7 | 7 | <p>An object that implements <code>Serializable</code> but contains non-transient, non-serializable data members (and thus violates the contract)
|
8 | 8 | could cause application crashes and open the door to attackers. In general, a <code>Serializable</code> class is expected to fulfil its contract and
|
9 | 9 | not exhibit unexpected behaviour when an instance is serialized.</p>
|
@@ -84,6 +84,16 @@ <h2>How to fix it</h2>
|
84 | 84 | }
|
85 | 85 | }
|
86 | 86 | </pre>
|
| 87 | +<p>Finally, static fields are out of scope for serialization, so making a field static prevents issues from being raised.</p> |
| 88 | +<pre> |
| 89 | +public class Person implements Serializable { |
| 90 | + private static final long serialVersionUID = 1905122041950251207L; |
| 91 | + |
| 92 | + private String name; |
| 93 | + |
| 94 | + private static Logger log = getLogger(); // Compliant, static fields are not serialized |
| 95 | +} |
| 96 | +</pre> |
87 | 97 | <h2>Resources</h2>
|
88 | 98 | <ul>
|
89 | 99 | <li> CWE - <a href="https://cwe.mitre.org/data/definitions/594">CWE-594 - Saving Unserializable Objects to Disk</a> </li>
|
|
0 commit comments