csharp.lang.security.memory.memory-marshal-create-span.memory-marshal-create-span

profile photo of returntocorpreturntocorp
Author
unknown
Download Count*

MemoryMarshal.CreateSpan and MemoryMarshal.CreateReadOnlySpan should be used with caution, as the length argument is not checked.

Run Locally

Run in CI

Defintion

rules:
  - id: memory-marshal-create-span
    severity: WARNING
    languages:
      - C#
    metadata:
      cwe:
        - "CWE-125: Out-of-bounds Read"
      owasp:
        - A04:2021 - Insecure Design
      references:
        - https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.createspan?view=net-6.0
        - https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.createreadonlyspan?view=net-6.0
      category: security
      technology:
        - .net
      confidence: LOW
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - audit
      likelihood: LOW
      impact: MEDIUM
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    message: MemoryMarshal.CreateSpan and MemoryMarshal.CreateReadOnlySpan should be
      used with caution, as the length argument is not checked.
    pattern-either:
      - pattern: MemoryMarshal.CreateSpan(...)
      - pattern: MemoryMarshal.CreateReadOnlySpan(...)

Examples

memory-marshal-create-span.cs

namespace MemMarshalCreateSpan {
    public class MemMarshalCreateSpan {
        public void MarshalTest() {
            // ruleid: memory-marshal-create-span
            Span<T> ToSpan() => MemoryMarshal.CreateSpan(ref _e0, 1);

            // ruleid: memory-marshal-create-span
            Span<T> ToSpan() => MemoryMarshal.CreateReadOnlySpan(ref _e0, 2);

            // ruleid: memory-marshal-create-span
            Span<byte> span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(writer.Span.GetPinnableReference()), 4);

            // ruleid: memory-marshal-create-span
            Span<byte> span = MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(writer.Span.GetPinnableReference()), 8);
        }
    }
}