Skip to content

Commit 634f554

Browse files
Merge pull request #3091 from SixLabors/af/backport-3075-to-3.1
[3.1] Backport #3075 - Add check, if Offset is greater then stream length when reading bitmap colorMapSize
2 parents 152fa9e + e114f00 commit 634f554

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1445,6 +1445,12 @@ private int ReadImageHeaders(BufferedReadStream stream, out bool inverted, out b
14451445
switch (this.fileMarkerType)
14461446
{
14471447
case BmpFileMarkerType.Bitmap:
1448+
if (this.fileHeader.Offset > stream.Length)
1449+
{
1450+
BmpThrowHelper.ThrowInvalidImageContentException(
1451+
$"Pixel data offset {this.fileHeader.Offset} exceeds file size {stream.Length}.");
1452+
}
1453+
14481454
colorMapSizeBytes = this.fileHeader.Offset - BmpFileHeader.Size - this.infoHeader.HeaderSize;
14491455
int colorCountForBitDepth = ColorNumerics.GetColorCountForBitDepth(this.infoHeader.BitsPerPixel);
14501456
bytesPerColorMapEntry = colorMapSizeBytes / colorCountForBitDepth;

tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,34 @@ public void BmpDecoder_ThrowsException_Issue2696<TPixel>(TestImageProvider<TPixe
571571
Assert.IsType<InvalidMemoryOperationException>(ex.InnerException);
572572
}
573573

574+
// https://github.com/SixLabors/ImageSharp/issues/3074
575+
[Fact]
576+
public void BmpDecoder_ThrowsException_Issue3074()
577+
{
578+
// Crafted BMP: pixel data offset = 0x7FFFFFFF, actual file = 35 bytes
579+
byte[] data =
580+
[
581+
0x42, 0x4D, // "BM" signature
582+
0x3A, 0x00, 0x00, 0x00, // file size: 58
583+
0x00, 0x00, 0x00, 0x00, // reserved
584+
0xFF, 0xFF, 0xFF, 0x7F, // pixel offset: 0x7FFFFFFF (2,147,483,647)
585+
0x28, 0x00, 0x00, 0x00, // DIB header size: 40
586+
0x01, 0x00, 0x00, 0x00, // width: 1
587+
0x01, 0xFF, 0x00, 0x00, // height: 65281
588+
0x01, 0x00, // color planes: 1
589+
0x08, 0x00, // bits per pixel: 8
590+
0x00, 0x00, 0x00, 0x00, // compression: RGB
591+
0x00, 0x00, 0x00 // (truncated)
592+
];
593+
594+
using MemoryStream stream = new(data);
595+
596+
Assert.Throws<InvalidImageContentException>(() =>
597+
{
598+
using Image<Rgba32> image = Image.Load<Rgba32>(stream);
599+
});
600+
}
601+
574602
[Fact]
575603
public void BmpDecoder_ThrowsException_Issue3067()
576604
{

0 commit comments

Comments
 (0)