Public read only array fields can be modified

Rule ND1908 Immutability

Violated when a publicly visible read-only field holds an array: the reference cannot change, but the array elements can. Code relying on the elements of a publicly accessible read-only array might contain an exploitable security vulnerability.

How to fix

Don't rely on the contents of a publicly accessible read-only array. Either:

- Replace the array with an unchangeable strongly typed collection, e.g. System.Collections.Generic.IReadOnlyList<T> ; System.Collections.Generic.IReadOnlyCollection<T> ; System.Collections.ReadOnlyCollectionBase

- Or replace the public field with a method returning a clone of a private array: modified clone elements are harmless.

Severity is Low: more an advice than a problem.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Public read only array fields can be modified</Name>
// <Id>ND1908:ArrayFieldsShouldNotBeReadOnly</Id>

warnif count > 0 
from f in Application.Fields where 
   f.IsInitOnly && 
   f.IsPubliclyVisible &&
   f.FieldType != null &&
   f.FieldType.FullName == "System.Array"
select new { 
   f, 
   FieldVisibility = f.Visibility,
   Debt = 3.ToMinutes().ToDebt(),
   Severity = Severity.Low
}

//<Expl>
// The *public {0}* is declared as readonly and holds an array.
// The slots within the array can be assigned by malicious client code
// potentially exposing a security vulnerability.
//</Expl>

//<Desc>
// Violated when a publicly visible read-only field holds an array: the
// reference cannot change, but the array elements can. Code relying on the
// elements of a publicly accessible read-only array might contain an
// exploitable *security vulnerability*.
//</Desc>

//<HowToFix>
// Don't rely on the contents of a publicly accessible read-only array.
// Either:
//
// - Replace the array with an unchangeable strongly typed collection, e.g.
// *System.Collections.Generic.IReadOnlyList<T>* ;
// *System.Collections.Generic.IReadOnlyCollection<T>* ;
// *System.Collections.ReadOnlyCollectionBase*
//
// - Or replace the public field with a method returning a clone of a
// private array: modified clone elements are harmless.
//
// Severity is **Low**: more an advice than a problem.
//</HowToFix>

Immutability: all 15 items