Skip to content

WriteStateInfoBase.EnsureSpaceInBuffer infinite loop via integer overflow #131823

Description

@bolverk

Description

WriteStateInfoBase.EnsureSpaceInBuffer() doubles the buffer size in a loop without overflow checking:

// WriteStateInfoBase.cs:55-71
private void EnsureSpaceInBuffer(int moreBytes)
{
    int newsize = Buffer.Length;
    while (_currentBufferUsed + moreBytes >= newsize)
    {
        newsize *= 2;  // Can overflow to negative int
    }
    if (newsize > Buffer.Length)
    {
        byte[] tempBuffer = new byte[newsize];
        _buffer.CopyTo(tempBuffer, 0);
        _buffer = tempBuffer;
    }
}

If Buffer.Length is sufficiently large (>= ~1 billion), newsize *= 2 overflows into a negative value. Once newsize becomes negative, the condition _currentBufferUsed + moreBytes >= newsize is always true (positive >= negative), creating an infinite loop.

Impact

  • Denial of service via infinite loop (CPU exhaustion)
  • Requires a buffer size of ~1GB to trigger, which may be difficult in practice but is theoretically reachable through large email attachments or MIME parts

Suggested Fix

Add an overflow check or upper-bound limit:

private void EnsureSpaceInBuffer(int moreBytes)
{
    int newsize = Buffer.Length;
    while (_currentBufferUsed + moreBytes >= newsize)
    {
        if (newsize > int.MaxValue / 2)
            throw new InvalidOperationException("Buffer size overflow");
        newsize *= 2;
    }
    // ...
}

Affected Versions

All supported .NET versions (8, 9, 10).

Metadata

Metadata

Assignees

Labels

area-System.NetuntriagedNew issue has not been triaged by the area owner

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions