...
Returning references to an object's internal mutable components provides an attacker with the opportunity to corrupt the state of the object. Consequently, accessor methods must return defensive copies of internal mutable objects (see rule OBJ05-J. Defensively copy private mutable class members before returning their references for more information).
Noncompliant Code Example
...
This compliant solution demonstrates correct use both of a shallow copy (for the array of int
) and of a deep copy (for the array of cookies).
Code Block | ||
---|---|---|
| ||
public void deepCopy(int[] ints, HttpCookie[] cookies) { if (ints == null || cookies == null) { throw new NullPointerException(); } // Shallow copy int[] intsCopy = ints.clone(); // Deep copy HttpCookie[] cookiesCopy = new HttpCookie[cookies.length]; for (int i = 0; i < cookies.length; i++) { // Manually create copy of each element in array cookiesCopy[i] = (HttpCookie)cookies[i].clone(); } doLogic(intsCopy, cookiesCopy); } |
...
Code Block | ||
---|---|---|
| ||
// java.util.Collection is an interface public void copyInterfaceInput(Collection<String> collection) { doLogic(collection.clone()); } |
Compliant Solution
This compliant solution protects against potential malicious overriding by creating a new instance of the nonfinal mutable input, using the expected class rather than the class of the potentially malicious provided objectargument. The newly created instance can be forwarded to any code capable of modifying it.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f48824d7dfae517e-51dbd665-49da4451-9df5aacd-49459fa8b4e488038c9d6671"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 39. Make defensive copies when needed | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="12b3b8229783ace7-db660d72-4b854b7c-ae8eae20-2164a55fab3875ad366dd532"><ac:plain-text-body><![CDATA[ | [[Pugh 2009 | AA. Bibliography#Pugh 09]] | Returning References to Internal Mutable State | ]]></ac:plain-text-body></ac:structured-macro> |
...