Returning a Mutable Object to an Untrusted Caller

Draft Base
Structure: Simple
Description

This vulnerability occurs when a method directly returns a reference to its internal mutable data, allowing untrusted calling code to modify that data unexpectedly.

Extended Description

When a function returns a reference to an object like an array, collection, or custom data structure without making a defensive copy, the caller gains the power to change the object's contents. Since both the class and the caller hold references to the same underlying data, any modifications made by the caller directly alter the class's internal state. This breaks a core principle of encapsulation, as the class can no longer control or guarantee the integrity of its own data. To prevent this, methods should never return direct references to mutable internal fields. Instead, return a deep copy of the data or an immutable view (like an unmodifiable wrapper). This practice ensures the calling code can use the returned data without being able to corrupt the original object's state, preserving the class's invariants and security.

Common Consequences 1
Scope: Access ControlIntegrity

Impact: Modify Memory

Potentially data could be tampered with by another function which should not have been tampered with.

Potential Mitigations 2
Phase: Implementation
Declare returned data which should not be altered as constant or immutable.
Phase: Implementation
Clone all mutable data before returning references to it. This is the preferred mitigation. This way, regardless of what changes are made to the data, a valid copy is retained for use by the class.
Demonstrative Examples 1
This class has a private list of patients, but provides a way to see the list :

Code Example:

Bad
Java
java
While this code only means to allow reading of the patient list, the getPatients() method returns a reference to the class's original patient list instead of a reference to a copy of the list. Any caller of this method can arbitrarily modify the contents of the patient list even though it is a private member of the class.
References 1
The CLASP Application Security Process
Secure Software, Inc.
2005
ID: REF-18
Likelihood of Exploit

Medium

Applicable Platforms
Languages:
C : UndeterminedC++ : UndeterminedJava : UndeterminedC# : Undetermined
Modes of Introduction
Implementation
Taxonomy Mapping
  • CLASP
  • The CERT Oracle Secure Coding Standard for Java (2011)
  • The CERT Oracle Secure Coding Standard for Java (2011)
  • SEI CERT Perl Coding Standard
  • Software Fault Patterns