Pointers should not be publicly visible

Rule ND3105 Security

Detects public or protected fields of type System.IntPtr or System.UIntPtr. Pointers access unmanaged memory; exposing them publicly lets malicious code read and write the application's unmanaged data — worse if the field is not read-only, since it can be changed to force the application onto arbitrary data.

Flagged Code
public class NativeBuffer {
   public IntPtr Handle;      // flagged: public, writable pointer
   protected UIntPtr Length;  // flagged: protected pointer
}
Fixed Code
public class NativeBuffer {
   private readonly SafeHandle _handle;   // pointer wrapped in a SafeHandle
   private IntPtr _buffer;                // private pointer
   public int Length { get; }
}

How to fix

Make pointers private or internal.

Estimated Debt: 15 minutes plus 10 minutes per method using the field outside its assembly. Severity: Medium, High if non read-only.

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>Pointers should not be publicly visible</Name>
// <Id>ND3105:PointersShouldNotBePubliclyVisible</Id>

warnif count > 0 
from f in Application.Fields
where 
  f.FieldType != null &&
  f.FieldType.FullNameEqualsAny("System.IntPtr","System.UIntPtr") &&
  (f.IsPubliclyVisible || f.IsProtected)
let methodsUserOutsideMyAssembly = f.MethodsUsingMe.Where(m => m.ParentAssembly != m.ParentAssembly)
select new { 
  f,
  f.FieldType,
  methodsUserOutsideMyAssembly,
  Debt = (15 + 10*methodsUserOutsideMyAssembly.Count()).ToMinutes().ToDebt(),
  Severity = f.IsInitOnly ? Severity.Medium : Severity.High
}

//<Expl>
// The *{0}* shouldn't be public because it exposes a pointer of type *{1}*.
// Publicly exposing a pointer can facilitate malicious access
// to unmanaged data.
//</Expl>

//<Desc>
// Detects public or protected fields of type *System.IntPtr* or
// *System.UIntPtr*. Pointers access unmanaged memory; exposing them publicly
// lets malicious code read and write the application's unmanaged data —
// worse if the field is not read-only, since it can be changed to force the
// application onto arbitrary data.
//
// **Flagged Code**
// ```csharp
// public class NativeBuffer {
//    public IntPtr Handle;      // flagged: public, writable pointer
//    protected UIntPtr Length;  // flagged: protected pointer
// }
// ```
//
// **Fixed Code**
// ```csharp
// public class NativeBuffer {
//    private readonly SafeHandle _handle;   // pointer wrapped in a SafeHandle
//    private IntPtr _buffer;                // private pointer
//    public int Length { get; }
// }
// ```
//</Desc>

//<HowToFix>
// Make pointers private or internal.
//
// Estimated Debt: 15 minutes plus 10 minutes per method using the field
// outside its assembly. Severity: *Medium*, *High* if non read-only.
//</HowToFix>

Security: all 39 items