Skip to content

Commit

Permalink
Merge pull request #2719 from SixLabors/backport/v2-check-palette-ind…
Browse files Browse the repository at this point in the history
…ices

V2 - Limit Read Palette Indices
  • Loading branch information
JimBobSquarePants authored Apr 9, 2024
2 parents fa7d712 + e620914 commit a78ce27
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/ImageSharp/Formats/Png/PngScanlineProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ public static void ProcessPaletteScanline<TPixel>(
ref TPixel rowSpanRef = ref MemoryMarshal.GetReference(rowSpan);
ReadOnlySpan<Rgb24> palettePixels = MemoryMarshal.Cast<byte, Rgb24>(palette);
ref Rgb24 palettePixelsRef = ref MemoryMarshal.GetReference(palettePixels);
int maxIndex = palettePixels.Length - 1;

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

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

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

pixel.FromRgb24(rgb);
Unsafe.Add(ref rowSpanRef, x) = pixel;
Expand Down
8 changes: 8 additions & 0 deletions tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -526,5 +526,13 @@ static void RunTest(string providerDump, string nonContiguousBuffersStr)
"Disco")
.Dispose();
}

[Theory]
[InlineData(TestImages.Png.Bad.Issue2714BadPalette)]
public void Decode_BadPalette(string file)
{
string path = Path.GetFullPath(Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, file));
using Image image = Image.Load(path);
}
}
}
2 changes: 2 additions & 0 deletions tests/ImageSharp.Tests/TestImages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ public static class Bad
// Invalid color type.
public const string ColorTypeOne = "Png/xc1n0g08.png";
public const string ColorTypeNine = "Png/xc9n2c08.png";

public const string Issue2714BadPalette = "Png/issues/Issue_2714.png";
}
}

Expand Down
3 changes: 3 additions & 0 deletions tests/Images/Input/Png/issues/Issue_2714.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit a78ce27

Please sign in to comment.