Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/ImageSharp/Formats/Ani/AniDecoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,10 @@ private void ParseContainer(BufferedReadStream stream)

// RIFF size excludes the initial identifier and size field. Some real-world ANI files incorrectly
// include those eight bytes, so the physical stream length remains the hard read boundary.
long declaredEnd = checked(containerStart + 8 + declaredSize);
long containerEnd = Math.Min(declaredEnd, stream.Length);
// The full header read puts containerStart + 8 inside the stream. Thus the remaining length cannot be negative, and the
// declared end is added only when it is less than the stream length.
long remaining = stream.Length - containerStart - 8;
long containerEnd = declaredSize < remaining ? containerStart + 8 + declaredSize : stream.Length;
bool headerFound = false;

while (stream.Position + AniConstants.ChunkHeaderSize <= containerEnd)
Expand Down Expand Up @@ -808,13 +810,15 @@ private AniRiffChunkHeader ReadChunkHeader(BufferedReadStream stream)
/// <returns>The exclusive payload boundary.</returns>
private static long GetChunkDataEnd(BufferedReadStream stream, uint size, long containerEnd)
{
long end = checked(stream.Position + size);
if (end > containerEnd)
// The caller reads the chunk header inside the container, so the position is not after the container end.
// Thus the subtraction cannot overflow, and the sum is calculated only when it is inside the container.
long position = stream.Position;
if (size > containerEnd - position)
{
throw new InvalidImageContentException("An ANI RIFF chunk extends beyond its containing list.");
}

return end;
return position + size;
}

/// <summary>
Expand Down
9 changes: 8 additions & 1 deletion src/ImageSharp/Formats/Ani/AniEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,14 @@ private void EndChunk(Stream stream, long sizePosition)
long endPosition = stream.Position;

// sizePosition addresses the size DWORD itself; subtracting its four bytes yields payload length.
uint dataSize = checked((uint)(endPosition - sizePosition - sizeof(uint)));
// The RIFF chunk size field is 32 bits. Thus the writer cannot write a larger chunk with a correct size.
long dataLength = endPosition - sizePosition - sizeof(uint);
if (dataLength > uint.MaxValue)
{
throw new ImageFormatException($"The RIFF chunk size {dataLength} is larger than the 32-bit size field allows.");
}

uint dataSize = (uint)dataLength;

// RIFF chunk sizes exclude the optional padding byte used to align the next chunk to a WORD boundary.
if ((dataSize & 1) is 1)
Expand Down
12 changes: 10 additions & 2 deletions src/ImageSharp/Formats/Icon/IconEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ internal void Encode<TPixel, TProvider>(Image<TPixel> image, Stream stream, int
}

long imageStart = stream.Position;
entries[i].Entry.ImageOffset = checked((uint)(imageStart - basePosition));

// The directory is less than 1 MiB and the end check below bounds each earlier payload, so this offset fits in uint.
entries[i].Entry.ImageOffset = (uint)(imageStart - basePosition);
ref EncodingFrameMetadata encodingMetadata = ref entries[i];
Image<TPixel>? encodingImage = null;

Expand Down Expand Up @@ -203,7 +205,13 @@ internal void Encode<TPixel, TProvider>(Image<TPixel> image, Stream stream, int
encodingImage?.Dispose();
}

encodingMetadata.Entry.BytesInRes = checked((uint)(stream.Position - imageStart));
// ImageOffset and BytesInRes are 32-bit fields. If the payload ends inside that range, its length and the next offset fit too.
if (stream.Position - basePosition > uint.MaxValue)
{
throw new ImageFormatException("ICO and CUR resources cannot be larger than 4294967295 bytes.");
}

encodingMetadata.Entry.BytesInRes = (uint)(stream.Position - imageStart);
}

// Backpatch the reserved directory after every relative offset and payload length has been measured.
Expand Down
43 changes: 27 additions & 16 deletions src/ImageSharp/Formats/Png/PngEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,14 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
PngMetadata pngMetadata = metadata.ClonePngMetadata();
this.SanitizeAndSetEncoderOptions<TPixel>(this.encoder, pngMetadata, out this.use16Bit, out this.bytesPerPixel);

// The encoder holds a scanline and its filter type byte in one buffer, so their length must fit in an int.
// An Adam7 pass is not wider than the image, so this check bounds each pass too.
long scanlineLength = this.CalculateScanlineLength(this.width);
if (scanlineLength >= int.MaxValue)
{
InvalidMemoryOperationException.ThrowAllocationOverLimitException((ulong)scanlineLength + 1, int.MaxValue);
}

stream.Write(PngConstants.HeaderBytes);

ImageFrame<TPixel>? clonedFrame = null;
Expand Down Expand Up @@ -968,12 +976,19 @@ private static string BuildRawProfileText(string header, ReadOnlySpan<byte> payl
// Use 64 bytes per line (128 hex chars) to keep the chunk readable.
const int bytesPerLine = 64;

int hexChars = payload.Length * 2;
int lineCount = (payload.Length + (bytesPerLine - 1)) / bytesPerLine;
int newlineCount = 2 + lineCount; // header line + length line + hex lines
int capacity = header.Length + 32 + hexChars + newlineCount;
// The text has 2 hex characters for each byte and one line break for each line. .NET limits a string to 0x3FFFFFDF
// characters, so a large payload is rejected before the text is built.
const int maxStringLength = 0x3FFFFFDF;
long hexChars = (long)payload.Length * 2;
long lineCount = (payload.Length + (bytesPerLine - 1L)) / bytesPerLine;
long newlineCount = 2 + lineCount; // header line + length line + hex lines
long capacity = header.Length + 32 + hexChars + newlineCount;
if (capacity > maxStringLength)
{
InvalidMemoryOperationException.ThrowAllocationOverLimitException((ulong)capacity, maxStringLength);
}

StringBuilder sb = new(capacity);
StringBuilder sb = new((int)capacity);
sb.Append(header).Append('\n');
sb.Append(payload.Length).Append('\n');

Expand Down Expand Up @@ -1365,7 +1380,7 @@ private void AllocateScanlineBuffers(int bytesPerScanline)
private void EncodePixels<TPixel>(in Buffer2DRegion<TPixel> pixels, IndexedImageFrame<TPixel>? quantized, ZlibDeflateStream deflateStream)
where TPixel : unmanaged, IPixel<TPixel>
{
int bytesPerScanline = this.CalculateScanlineLength(pixels.Width);
int bytesPerScanline = (int)this.CalculateScanlineLength(pixels.Width);
int filterLength = bytesPerScanline + 1;
this.AllocateScanlineBuffers(bytesPerScanline);

Expand Down Expand Up @@ -1398,9 +1413,7 @@ private void EncodeAdam7Pixels<TPixel>(in Buffer2DRegion<TPixel> pixels, ZlibDef
int startCol = Adam7.FirstColumn[pass];
int blockWidth = Adam7.ComputeBlockWidth(pixels.Width, pass);

int bytesPerScanline = this.bytesPerPixel <= 1
? ((blockWidth * this.bitDepth) + 7) / 8
: blockWidth * this.bytesPerPixel;
int bytesPerScanline = (int)this.CalculateScanlineLength(blockWidth);

int filterLength = bytesPerScanline + 1;
this.AllocateScanlineBuffers(bytesPerScanline);
Expand Down Expand Up @@ -1449,9 +1462,7 @@ private void EncodeAdam7IndexedPixels<TPixel>(IndexedImageFrame<TPixel> quantize
int startCol = Adam7.FirstColumn[pass];
int blockWidth = Adam7.ComputeBlockWidth(quantized.Width, pass);

int bytesPerScanline = this.bytesPerPixel <= 1
? ((blockWidth * this.bitDepth) + 7) / 8
: blockWidth * this.bytesPerPixel;
int bytesPerScanline = (int)this.CalculateScanlineLength(blockWidth);

int filterLength = bytesPerScanline + 1;

Expand Down Expand Up @@ -1568,14 +1579,14 @@ private void WriteFrameDataChunk(Stream stream, uint sequenceNumber, Span<byte>
/// </summary>
/// <param name="width">The width of the row.</param>
/// <returns>
/// The <see cref="int"/> representing the length.
/// The length in bytes. The calculation uses 64-bit values, so a large width cannot wrap.
/// </returns>
private int CalculateScanlineLength(int width)
private long CalculateScanlineLength(int width)
{
int mod = this.bitDepth is 16 ? 16 : 8;
int scanlineLength = width * this.bitDepth * this.bytesPerPixel;
long scanlineLength = (long)width * this.bitDepth * this.bytesPerPixel;

int amount = scanlineLength % mod;
long amount = scanlineLength % mod;
if (amount != 0)
{
scanlineLength += mod - amount;
Expand Down
25 changes: 21 additions & 4 deletions src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,19 @@ private long WriteIfd(TiffStreamWriter writer, List<IExifValue> entries, long if

if (entries.Count > ushort.MaxValue)
{
TiffThrowHelper.ThrowArgumentException("The TIFF directory contains too many entries.");
TiffThrowHelper.ThrowImageFormatException("The TIFF directory contains too many entries.");
}

// Classic TIFF stores offsets in four bytes. If the end of the directory fits, its start fits too.
long directoryOffset = writer.Position;
int directoryLength = 6 + (entries.Count * 12);
uint dataOffset = checked((uint)(directoryOffset + directoryLength));
long directoryEnd = directoryOffset + directoryLength;
if (directoryEnd > uint.MaxValue)
{
TiffThrowHelper.ThrowImageFormatException("The TIFF data exceeds the 4 GB offset range of classic TIFF.");
}

uint dataOffset = (uint)directoryEnd;
this.frameMarkers.Add((ifdOffsetMarker, (uint)directoryOffset));

List<byte[]> largeDataBlocks = [];
Expand All @@ -354,15 +360,26 @@ private long WriteIfd(TiffStreamWriter writer, List<IExifValue> entries, long if
}
else
{
// A numeric array can encode to more bytes than a byte array can hold, so the length is checked first.
if (length > Array.MaxLength)
{
InvalidMemoryOperationException.ThrowAllocationOverLimitException(length, Array.MaxLength);
}

byte[] raw = new byte[length];
int sz = ExifWriter.WriteValue(entry, raw, 0);
DebugGuard.IsTrue(sz == raw.Length, "Incorrect number of bytes written");
largeDataBlocks.Add(raw);
writer.Write(dataOffset, buffer);

// The next value must start on an even byte offset that fits in four bytes.
uint paddedLength = (uint)raw.Length + ((uint)raw.Length & 1);
dataOffset = checked(dataOffset + paddedLength);
ulong nextOffset = dataOffset + (ulong)raw.Length + ((uint)raw.Length & 1);
if (nextOffset > uint.MaxValue)
{
TiffThrowHelper.ThrowImageFormatException("The TIFF data exceeds the 4 GB offset range of classic TIFF.");
}

dataOffset = (uint)nextOffset;
}
}

Expand Down
44 changes: 18 additions & 26 deletions src/ImageSharp/Formats/Webp/RiffHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,9 @@ public static void WriteRiffFile(Stream stream, string formType, Action<Stream>

public static void WriteChunk(Stream stream, uint fourCc, Action<Stream> func)
{
Span<byte> buffer = stackalloc byte[4];

// write the fourCC
BinaryPrimitives.WriteUInt32BigEndian(buffer, fourCc);
stream.Write(buffer);

long sizePosition = stream.Position;
stream.Position += 4;

long sizePosition = BeginWriteChunk(stream, fourCc);
func(stream);

long position = stream.Position;

uint dataSize = (uint)(position - sizePosition - 4);

// padding
if (dataSize % 2 == 1)
{
stream.WriteByte(0);
position++;
}

BinaryPrimitives.WriteUInt32LittleEndian(buffer, dataSize);
stream.Position = sizePosition;
stream.Write(buffer);
stream.Position = position;
EndWriteChunk(stream, sizePosition);
}

public static void WriteChunk(Stream stream, uint fourCc, ReadOnlySpan<byte> data)
Expand Down Expand Up @@ -99,7 +76,14 @@ public static void EndWriteChunk(Stream stream, long sizePosition)

long position = stream.Position;

uint dataSize = (uint)(position - sizePosition - 4);
// The RIFF chunk size field is 32 bits. Thus the writer cannot write a larger chunk with a correct size.
long size = position - sizePosition - 4;
if (size > uint.MaxValue)
{
WebpThrowHelper.ThrowChunkTooLarge(size);
}

uint dataSize = (uint)size;

// padding
if (dataSize % 2 is 1)
Expand All @@ -124,6 +108,14 @@ public static long BeginWriteRiffFile(Stream stream, string formType)

public static void EndWriteRiffFile(Stream stream, in WebpVp8X vp8x, bool updateVp8x, long sizePosition)
{
// The WebP Container Specification, section "RIFF Header", limits the File Size field to 2^32 - 10.
// This limit is less than the generic RIFF limit of EndWriteChunk.
long fileSize = stream.Position - sizePosition - 8;
if (fileSize > uint.MaxValue - 9)
{
WebpThrowHelper.ThrowFileTooLarge(fileSize);
}

EndWriteChunk(stream, sizePosition + 4);

// Write the VP8X chunk if necessary.
Expand Down
16 changes: 16 additions & 0 deletions src/ImageSharp/Formats/Webp/WebpThrowHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,20 @@ internal static class WebpThrowHelper

[DoesNotReturn]
public static void ThrowDimensionsTooLarge(int width, int height) => throw new ImageFormatException($"Image is too large to encode at {width}x{height} for WEBP format.");

/// <summary>
/// Throws an <see cref="ImageFormatException"/> for a RIFF chunk that does not fit in the 32-bit size field.
/// </summary>
/// <param name="size">The size of the chunk data in bytes.</param>
[DoesNotReturn]
public static void ThrowChunkTooLarge(long size)
=> throw new ImageFormatException($"The RIFF chunk size {size} is larger than the 32-bit size field allows.");

/// <summary>
/// Throws an <see cref="ImageFormatException"/> for a WebP file that is larger than the WebP container allows.
/// </summary>
/// <param name="size">The value of the File Size field in bytes.</param>
[DoesNotReturn]
public static void ThrowFileTooLarge(long size)
=> throw new ImageFormatException($"The WebP file size {size} is larger than the WebP container allows.");
}
2 changes: 1 addition & 1 deletion src/ImageSharp/Image.LoadPixelData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public static Image<TPixel> LoadPixelData<TPixel>(
{
Guard.NotNull(configuration, nameof(configuration));

int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, rowStrideInBytes, nameof(rowStrideInBytes));
int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, height, rowStrideInBytes, nameof(rowStrideInBytes));
return LoadPixelData(configuration, MemoryMarshal.Cast<byte, TPixel>(data), width, height, rowStride);
}

Expand Down
10 changes: 6 additions & 4 deletions src/ImageSharp/Image.WrapMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ public static Image<TPixel> WrapMemory<TPixel>(
Guard.NotNull(configuration, nameof(configuration));
Guard.NotNull(metadata, nameof(metadata));

int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, rowStrideInBytes, nameof(rowStrideInBytes));
int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, height, rowStrideInBytes, nameof(rowStrideInBytes));
long requiredLength = GetRequiredLength(width, height, rowStride);

ByteMemoryManager<TPixel> memoryManager = new(byteMemory);
Expand Down Expand Up @@ -468,7 +468,7 @@ public static Image<TPixel> WrapMemory<TPixel>(
Guard.NotNull(configuration, nameof(configuration));
Guard.NotNull(metadata, nameof(metadata));

int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, rowStrideInBytes, nameof(rowStrideInBytes));
int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, height, rowStrideInBytes, nameof(rowStrideInBytes));

ByteMemoryOwner<TPixel> pixelMemoryOwner = new(byteMemoryOwner);
long requiredLength = GetRequiredLength(width, height, rowStride);
Expand Down Expand Up @@ -613,7 +613,7 @@ public static unsafe Image<TPixel> WrapMemory<TPixel>(
Guard.NotNull(configuration, nameof(configuration));
Guard.NotNull(metadata, nameof(metadata));

int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, rowStrideInBytes, nameof(rowStrideInBytes));
int rowStride = GetPixelRowStrideFromByteStride<TPixel>(width, height, rowStrideInBytes, nameof(rowStrideInBytes));
long requiredLength = GetRequiredLength(width, height, rowStride);

Guard.MustBeLessThanOrEqualTo(requiredLength, int.MaxValue, nameof(requiredLength));
Expand Down Expand Up @@ -671,12 +671,14 @@ private static void ValidateWrapMemoryStride(int width, int height, int rowStrid
Guard.MustBeGreaterThanOrEqualTo(rowStride, width, rowStrideParamName);
}

private static int GetPixelRowStrideFromByteStride<TPixel>(int width, int rowStrideInBytes, string rowStrideParamName)
private static int GetPixelRowStrideFromByteStride<TPixel>(int width, int height, int rowStrideInBytes, string rowStrideParamName)
where TPixel : unmanaged, IPixel<TPixel>
{
int pixelSizeInBytes = Unsafe.SizeOf<TPixel>();

// The callers compute the required length from height - 1, so a height that is not positive must stop here.
Guard.MustBeGreaterThan(width, 0, nameof(width));
Guard.MustBeGreaterThan(height, 0, nameof(height));
Guard.MustBeGreaterThan(rowStrideInBytes, 0, rowStrideParamName);
Guard.IsTrue(
rowStrideInBytes % pixelSizeInBytes == 0,
Expand Down
Loading
Loading