Assigning an external array reference directly to a private field

Assigning an external array reference directly to a private field

Description

If a public method stores a caller-supplied list or array directly in a private field, the caller can later modify the original object and change the internal state.

Potential impact

  • External references may allow changes to validated values or permission lists.
  • Sharing internal state with callers may cause unexpected security errors.

Remediation

  • Copy Python lists with value[:], list(value) or copy.copy(value) before storing them. A shallow copy still shares mutable elements; copy those elements too or make them immutable when needed.
  • Basic slicing of a NumPy array creates a view. Use copy() when independent data is required.
  • Validate element types and permitted values before storage.

Examples

These excerpts assume a Python list whose individual elements do not require separate copies.

Before

python
def set_values(self, values):
    self.__values = values

After

python
def set_values(self, values):
    self.__values = values[:]

Explanation:

  • Before: Stores a caller-supplied list or array directly in a private field, allowing later changes to the original object to affect internal state.
  • After: Makes a shallow copy of the list so additions, removals or element replacement in the caller's list do not directly change the internal list.

References