Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

Commit

Permalink
Cap allocation size in XmlBufferReader.TryEnsureBytes
Browse files Browse the repository at this point in the history
Do not allow the untrusted payload to dictate the initial capacity of the read buffer.
  • Loading branch information
GrabYourPitchforks committed Apr 14, 2020
1 parent b7971bc commit b1319e7
Showing 1 changed file with 29 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -213,28 +213,36 @@ private bool TryEnsureBytes(int count)
{
if (_stream == null)
return false;
DiagnosticUtility.DebugAssert(_offset <= int.MaxValue - count, "");
int newOffsetMax = _offset + count;
if (newOffsetMax < _offsetMax)
return true;
DiagnosticUtility.DebugAssert(newOffsetMax <= _windowOffsetMax, "");
if (newOffsetMax > _buffer.Length)
{
byte[] newBuffer = new byte[Math.Max(newOffsetMax, _buffer.Length * 2)];
System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax);
_buffer = newBuffer;
_streamBuffer = newBuffer;
}
int needed = newOffsetMax - _offsetMax;
while (needed > 0)

// The data could be coming from an untrusted source, so we use a standard
// "multiply by 2" growth algorithm to avoid overly large memory utilization.
// Constant value of 256 comes from MemoryStream implementation.

do
{
int actual = _stream.Read(_buffer, _offsetMax, needed);
if (actual == 0)
return false;
_offsetMax += actual;
needed -= actual;
}
return true;
DiagnosticUtility.DebugAssert(_offset <= int.MaxValue - count, "");
int newOffsetMax = _offset + count;
if (newOffsetMax <= _offsetMax)
return true;
DiagnosticUtility.DebugAssert(newOffsetMax <= _windowOffsetMax, "");
if (newOffsetMax > _buffer.Length)
{
byte[] newBuffer = new byte[Math.Max(256, _buffer.Length * 2)];
System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax);
newOffsetMax = Math.Min(newOffsetMax, newBuffer.Length);
_buffer = newBuffer;
_streamBuffer = newBuffer;
}
int needed = newOffsetMax - _offsetMax;
while (needed > 0)
{
int actual = _stream.Read(_buffer, _offsetMax, needed);
if (actual == 0)
return false;
_offsetMax += actual;
needed -= actual;
}
} while (true);
}

public void Advance(int count)
Expand Down

0 comments on commit b1319e7

Please sign in to comment.