Skip to content

Commit a78ce27

Browse files
Merge pull request #2719 from SixLabors/backport/v2-check-palette-indices
V2 - Limit Read Palette Indices
2 parents fa7d712 + e620914 commit a78ce27

File tree

4 files changed

+17
-3
lines changed

4 files changed

+17
-3
lines changed

src/ImageSharp/Formats/Png/PngScanlineProcessor.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ public static void ProcessPaletteScanline<TPixel>(
250250
ref TPixel rowSpanRef = ref MemoryMarshal.GetReference(rowSpan);
251251
ReadOnlySpan<Rgb24> palettePixels = MemoryMarshal.Cast<byte, Rgb24>(palette);
252252
ref Rgb24 palettePixelsRef = ref MemoryMarshal.GetReference(palettePixels);
253+
int maxIndex = palettePixels.Length - 1;
253254

254255
if (paletteAlpha?.Length > 0)
255256
{
@@ -260,7 +261,7 @@ public static void ProcessPaletteScanline<TPixel>(
260261

261262
for (int x = 0; x < header.Width; x++)
262263
{
263-
int index = Unsafe.Add(ref scanlineSpanRef, x);
264+
int index = Numerics.Clamp(Unsafe.Add(ref scanlineSpanRef, x), 0, maxIndex);
264265
rgba.Rgb = Unsafe.Add(ref palettePixelsRef, index);
265266
rgba.A = paletteAlpha.Length > index ? Unsafe.Add(ref paletteAlphaRef, index) : byte.MaxValue;
266267

@@ -272,8 +273,8 @@ public static void ProcessPaletteScanline<TPixel>(
272273
{
273274
for (int x = 0; x < header.Width; x++)
274275
{
275-
int index = Unsafe.Add(ref scanlineSpanRef, x);
276-
Rgb24 rgb = Unsafe.Add(ref palettePixelsRef, index);
276+
uint index = Unsafe.Add(ref scanlineSpanRef, x);
277+
Rgb24 rgb = Unsafe.Add(ref palettePixelsRef, (int)Math.Min(index, maxIndex));
277278

278279
pixel.FromRgb24(rgb);
279280
Unsafe.Add(ref rowSpanRef, x) = pixel;

tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,5 +526,13 @@ static void RunTest(string providerDump, string nonContiguousBuffersStr)
526526
"Disco")
527527
.Dispose();
528528
}
529+
530+
[Theory]
531+
[InlineData(TestImages.Png.Bad.Issue2714BadPalette)]
532+
public void Decode_BadPalette(string file)
533+
{
534+
string path = Path.GetFullPath(Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, file));
535+
using Image image = Image.Load(path);
536+
}
529537
}
530538
}

tests/ImageSharp.Tests/TestImages.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ public static class Bad
156156
// Invalid color type.
157157
public const string ColorTypeOne = "Png/xc1n0g08.png";
158158
public const string ColorTypeNine = "Png/xc9n2c08.png";
159+
160+
public const string Issue2714BadPalette = "Png/issues/Issue_2714.png";
159161
}
160162
}
161163

Lines changed: 3 additions & 0 deletions
Loading

0 commit comments

Comments
 (0)