diff --git a/src/EPPlus.Export.Pdf.Tests/ImageDecoderSecurityTests.cs b/src/EPPlus.Export.Pdf.Tests/ImageDecoderSecurityTests.cs new file mode 100644 index 000000000..85e88fc5c --- /dev/null +++ b/src/EPPlus.Export.Pdf.Tests/ImageDecoderSecurityTests.cs @@ -0,0 +1,87 @@ +using EPPlus.Export.Pdf.Helpers; // internal PngDecoder (InternalsVisibleTo is already set) +using EPPlus.Export.Pdf.Tests; // PdfTestBase -> TestBase (license + OpenTemplatePackage) +using OfficeOpenXml; +using OfficeOpenXml.Export.PdfExport; // SaveAsPdf extension methods +using System; +using System.IO; +using System.Text; + +namespace EPPlusTest.PDF +{ + /// + /// Security regression tests for the embedded-image decoders. The attack: a tiny PNG whose + /// IHDR *declares* enormous dimensions (30000x30000) while the IDAT is a real 1x1 pixel. + /// The decoder sizes its output buffer from the header (width*height*3 in Int32), which + /// overflows to a negative length and throws, aborting the entire export. Reachable by anyone + /// who can get an image into a workbook that gets converted to PDF. + /// + [TestClass] + public class ImageDecoderSecurityTests : PdfTestBase + { + // IHDR says 30000x30000, 8-bit, colour type 6 (RGBA). IDAT is a valid zlib stream for one + // 1x1 pixel. (Exact bytes of evil_oversized_30000x30000.png.) + private static readonly byte[] OversizedRgbaPng = new byte[] + { + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, + 73, 72, 68, 82, 0, 0, 117, 48, 0, 0, 117, 48, + 8, 6, 0, 0, 0, 102, 39, 248, 186, 0, 0, 0, + 13, 73, 68, 65, 84, 120, 218, 99, 248, 207, 192, 240, + 31, 0, 5, 0, 1, 255, 86, 199, 47, 13, 0, 0, + 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, + }; + + private const int OversizedW = 30000; + private const int OversizedH = 30000; + private const int RgbaColorType = 6; + + /// The header parses as a PNG but the dimensions must be rejected by the guard. + [TestMethod] + public void PngDecoder_RejectsOversizedDimensions() + { + Assert.IsTrue(PngDecoder.IsPng(OversizedRgbaPng)); + + bool ok = PngDecoder.ReadPngHeader( + OversizedRgbaPng, out int w, out int h, out int bitDepth, out int colorType, out _); + + Assert.IsFalse(ok, "Oversized PNG header must be rejected by the ImageLimits guard."); + // Dimensions are still parsed out (the guard runs after reading them) — confirm the + // payload really is the oversized one, so this test can't pass for the wrong reason. + Assert.AreEqual(OversizedW, w); + Assert.AreEqual(OversizedH, h); + Assert.AreEqual(RgbaColorType, colorType); + } + + /// Calling the decode path directly must throw a clean, typed error — never overflow/OOM. + [TestMethod] + public void DecodePngWithAlpha_OnOversized_ThrowsInvalidData() + { + Assert.ThrowsExactly(() => + PngDecoder.DecodePngWithAlpha( + OversizedRgbaPng, OversizedW, OversizedH, + blackAndWhite: false, colorType: RgbaColorType, + out _, out _)); + } + + /// End-to-end: a workbook containing the oversized image still exports cleanly. + [TestMethod] + public void Export_WithOversizedPng_DoesNotThrow_AndProducesValidPdf() + { + using var p = OpenTemplatePackage("PDFTest.xlsx"); + var ws = p.Workbook.Worksheets[0]; + + using (var imgStream = new MemoryStream(OversizedRgbaPng)) + ws.Drawings.AddPicture("evil_oversized", imgStream); + + using var ms = new MemoryStream(); + + ws.SaveAsPdf(ms); // must NOT throw — the bad image is skipped/blanked + + byte[] bytes = ms.ToArray(); + Assert.IsTrue(bytes.Length > 8, "No PDF was produced."); + Assert.AreEqual("%PDF-", Encoding.ASCII.GetString(bytes, 0, 5), "Missing PDF header."); + + string tail = Encoding.ASCII.GetString(bytes, Math.Max(0, bytes.Length - 8), Math.Min(8, bytes.Length)); + Assert.IsTrue(tail.Contains("%%EOF"), "Missing %%EOF trailer — document is truncated."); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf.Tests/PdfLowRiskHardeningTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfLowRiskHardeningTests.cs new file mode 100644 index 000000000..3206a148e --- /dev/null +++ b/src/EPPlus.Export.Pdf.Tests/PdfLowRiskHardeningTests.cs @@ -0,0 +1,74 @@ +using EPPlus.Export.Pdf.DocumentObjects; +using EPPlus.Export.Pdf.DocumentObjects.Fonts; +using EPPlus.Export.Pdf.Helpers; + +namespace EPPlusTest.PDF +{ + [TestClass] + public class PdfLowRiskHardeningTests + { + [TestMethod] + public void FontName_EscapesPdfDelimiters() + { + var font = new PdfFont(1, "Evil) /Type /Catalog (x", PdfFontSubType.Type1); + string body = font.RenderBody(); + + Assert.IsFalse(body.Contains("Evil)"), "Unescaped ')' leaked into /BaseFont."); + StringAssert.Contains(body, "Evil#29", "')' should be escaped as #29."); + StringAssert.Contains(body, "#2F", "'/' should be escaped as #2F."); + } + + [TestMethod] + public void FontDescriptor_EscapesPdfDelimiters() + { + var fd = new PdfFontDescriptor(1, "Bad>Name) (", 0, new EPPlus.Graphics.Rect(), 0, 0, 0, 0, 0); + string body = fd.RenderBody(); + + Assert.IsFalse(body.Contains("Bad>Name"), "Unescaped '>' leaked into /FontName."); + StringAssert.Contains(body, "#3E", "'>' should be escaped as #3E."); + } + + [TestMethod] + public void LinkAnnotation_DropsJavascriptUri() + { + var evil = new PdfLinkAnnotationObject(1, 0, 0, 10, 10, "javascript:app.alert('x')", null); + string body = evil.RenderBody(); + + Assert.IsFalse(body.Contains("/URI"), "javascript: must not produce a URI action."); + Assert.IsFalse(body.Contains("javascript"), "Dangerous scheme leaked into the annotation."); + StringAssert.Contains(body, "/Subtype /Link", "The link annotation itself should still be emitted (inert)."); + } + + [TestMethod] + public void LinkAnnotation_KeepsSafeUri() + { + var safe = new PdfLinkAnnotationObject(2, 0, 0, 10, 10, "https://example.com/report", null); + string body = safe.RenderBody(); + + StringAssert.Contains(body, "/S /URI"); + StringAssert.Contains(body, "example.com"); + } + + [TestMethod] + public void LinkAnnotation_BlocksObfuscatedScheme() + { + // leading space + embedded tab must not bypass the filter + var evil = new PdfLinkAnnotationObject(3, 0, 0, 10, 10, " java\tscript:evil()", null); + string body = evil.RenderBody(); + + Assert.IsFalse(body.Contains("/URI"), "Obfuscated javascript: bypassed the scheme filter."); + } + + [TestMethod] + public void CidFont_BaseFont_EscapesPdfDelimiters() + { + // PdfCIDFont derives BaseFont from fontData.FullName — exercised via the resource layer + // in a full export; here we assert the escaping contract on the emitted token directly. + string name = "Evil) /Type /Catalog (x"; + string escaped = name.Replace(" ", "").ToPdfName(); // ToPdfName is the fix + Assert.IsFalse(escaped.Contains(")"), "')' must be hex-escaped in a PDF name."); + Assert.IsFalse(escaped.Contains("/"), "'/' must be hex-escaped in a PDF name."); + StringAssert.Contains(escaped, "#29"); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf.Tests/PdfMetadataSecurityTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfMetadataSecurityTests.cs new file mode 100644 index 000000000..69712e07b --- /dev/null +++ b/src/EPPlus.Export.Pdf.Tests/PdfMetadataSecurityTests.cs @@ -0,0 +1,44 @@ +using EPPlus.Export.Pdf.DocumentObjects; +using EPPlus.Export.Pdf.Settings; + +namespace EPPlusTest.PDF +{ + [TestClass] + public class PdfMetadataSecurityTests + { + [TestMethod] + public void InfoDictionary_EscapesMetadata_NoPdfInjection() + { + // A parenthesis breakout that tries to close the string + dictionary and inject an action. + var settings = new PdfDocumentSettings + { + Title = "Report) >> endobj /JavaScript (app.alert\\('pwn'\\)) (", + Author = "a) b ( c \\ d", + LicenseType = "Lic)Type", + LicenseHolder = "Holder) (" + }; + + string body = new PdfInfoObject(1, settings).RenderBody(); + + // Title/Author are hex strings now, not literals -> the payload cannot appear as tokens. + StringAssert.Contains(body, "/Title >", and no stray literal "()" breakout. + Assert.AreEqual(1, CountOccurrences(body, "<<"), "Info dict should open exactly once."); + Assert.AreEqual(1, CountOccurrences(body, ">>"), "Info dict should close exactly once."); + } + + private static int CountOccurrences(string s, string sub) + { + int n = 0, i = 0; + while ((i = s.IndexOf(sub, i, System.StringComparison.Ordinal)) >= 0) { n++; i += sub.Length; } + return n; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs index 73a11122f..ee8a713c6 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs @@ -85,8 +85,8 @@ private string Body() var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Font\n" + $" /Subtype /{Subtype.ToString()}\n" + - $" /BaseFont /{BaseFont}\n" + - $" /CIDSystemInfo << /Registry ({CIDInfoObject.Registry}) /Ordering ({CIDInfoObject.Ordering}) /Supplement {CIDInfoObject.Supplement} >>\n" + + $" /BaseFont /{BaseFont.ToPdfName()}\n" + + $" /CIDSystemInfo << /Registry {CIDInfoObject.Registry.ToPdfLiteral()} /Ordering {CIDInfoObject.Ordering.ToPdfLiteral()} /Supplement {CIDInfoObject.Supplement} >>\n" + $" /FontDescriptor {FontDescriptorObjectNumber.ToPdfStringF0()} 0 R"); if (DW != null) { diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs index b6905c316..000993b57 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs @@ -60,7 +60,7 @@ private string Body() var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Font\n" + $" /Subtype /{subType}\n" + - $" /BaseFont /{baseFont.Replace(" ", "")}"); + $" /BaseFont /{baseFont.Replace(" ", "").ToPdfName()}"); if (encoding == PdfFontEncoding.None) { sb.Append(" >>"); diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs index e19396f5e..b43c887f5 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs @@ -67,7 +67,7 @@ private string Body() { StringBuilder sb = new StringBuilder(); sb.AppendFormat($"<< /Type /FontDescriptor\n" + - $" /FontName /{fontName.Replace(" ", "")}\n" + + $" /FontName /{fontName.Replace(" ", "").ToPdfName()}\n" + $" /Flags {flags.ToPdfStringF0()}\n" + $" /FontBBox [{fontBBox.X.ToPdfStringF0()} {fontBBox.Y.ToPdfStringF0()} {fontBBox.Width.ToPdfStringF0()} {fontBBox.Height.ToPdfStringF0()}]\n" + $" /Ascent {ascent.ToPdfStringF0()}\n" + diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs index 485ac2f18..72d20d324 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs @@ -38,7 +38,7 @@ private string Body() var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Font\n" + $" /Subtype /Type0\n" + - $" /BaseFont /{BaseFont}\n" + + $" /BaseFont /{BaseFont.ToPdfName()}\n" + $" /Encoding /{Encoding}\n" + $" /DescendantFonts [{DescendantFontsObjectNumbers.ToPdfStringF0()} 0 R]"); if (ToUnicodeObjectNumber > 0) diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs index a6f3123a7..bf4a36b09 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs @@ -34,7 +34,7 @@ internal class PdfContentStream : PdfObject private readonly Stack<(int index, string header)> _artifactMarks = new Stack<(int, string)>(); public void BeginArtifact() => _artifactMarks.Push((commands.Count, "/Artifact BMC")); - public void BeginArtifact(string type) => _artifactMarks.Push((commands.Count, $"/Artifact << /Type /{type} >> BDC")); + public void BeginArtifact(string type) => _artifactMarks.Push((commands.Count, $"/Artifact << /Type /{type.ToPdfName()} >> BDC")); public void EndArtifact() { diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs index 9709da096..5fe1bf21a 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs @@ -10,6 +10,8 @@ Date Author Change ************************************************************************************************* 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ +using System; +using System.IO; using EPPlus.Export.Pdf.Helpers; using EPPlus.Export.Pdf.Settings; @@ -33,155 +35,171 @@ internal class PdfImageXObject : PdfObject public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, PdfCompressionLevel compressionLevel, int version = 0) : base(objectNumber, version) { - byte[] icoDib = null; - if (IcoDecoder.IsIco(imageBytes) && IcoDecoder.TryGetBestFrame(imageBytes, out byte[] icoFrame, out bool icoSelfContained)) + try { - if (icoSelfContained) imageBytes = icoFrame; - else icoDib = icoFrame; - } - if (icoDib != null && IcoDecoder.TryDecodeDib(icoDib, out int icoW, out int icoH, out byte[] icoRgb, out byte[] icoAlpha)) - { - Width = icoW; - Height = icoH; - BitsPerComponent = 8; - ColorSpace = "/DeviceRGB"; - Filter = "FlateDecode"; - if (blackAndWhite) GrayscaleRgb(icoRgb); - _bytes = PdfFlate.CompressLeaveOpen(icoRgb, compressionLevel); - if (icoAlpha != null) + byte[] icoDib = null; + if (IcoDecoder.IsIco(imageBytes) && IcoDecoder.TryGetBestFrame(imageBytes, out byte[] icoFrame, out bool icoSelfContained)) { - SoftMaskData = PdfFlate.CompressLeaveOpen(icoAlpha, compressionLevel); - HasSoftMask = true; + if (icoSelfContained) imageBytes = icoFrame; + else icoDib = icoFrame; } - } - else if (JpegDecoder.IsJpeg(imageBytes)) - { - if (blackAndWhite && JpegCmykHelper.TryDecode(imageBytes, out int gw, out int gh, out byte[] grayPixels)) + if (icoDib != null && IcoDecoder.TryDecodeDib(icoDib, out int icoW, out int icoH, out byte[] icoRgb, out byte[] icoAlpha)) { - Width = gw; - Height = gh; + Width = icoW; + Height = icoH; BitsPerComponent = 8; - ColorSpace = "/DeviceGray"; + ColorSpace = "/DeviceRGB"; Filter = "FlateDecode"; - _bytes = PdfFlate.CompressLeaveOpen(grayPixels, compressionLevel); + if (blackAndWhite) GrayscaleRgb(icoRgb); + _bytes = PdfFlate.CompressLeaveOpen(icoRgb, compressionLevel); + if (icoAlpha != null) + { + SoftMaskData = PdfFlate.CompressLeaveOpen(icoAlpha, compressionLevel); + HasSoftMask = true; + } } - else + else if (JpegDecoder.IsJpeg(imageBytes)) { - JpegDecoder.ReadJpegInfo(imageBytes, out int width, out int height, out int components, out bool adobe); - _bytes = blackAndWhite ? JpegBlackWhiteHelper.MakeGrayscale(imageBytes) : imageBytes; - Filter = "DCTDecode"; - BitsPerComponent = 8; + if (blackAndWhite && JpegCmykHelper.TryDecode(imageBytes, out int gw, out int gh, out byte[] grayPixels)) + { + Width = gw; + Height = gh; + BitsPerComponent = 8; + ColorSpace = "/DeviceGray"; + Filter = "FlateDecode"; + _bytes = PdfFlate.CompressLeaveOpen(grayPixels, compressionLevel); + } + else + { + JpegDecoder.ReadJpegInfo(imageBytes, out int width, out int height, out int components, out bool adobe); + _bytes = blackAndWhite ? JpegBlackWhiteHelper.MakeGrayscale(imageBytes) : imageBytes; + Filter = "DCTDecode"; + BitsPerComponent = 8; + Width = width; + Height = height; + if (components == 4) + { + ColorSpace = "/DeviceCMYK"; + if (adobe) Decode = "[ 1 0 1 0 1 0 1 0 ]"; + } + else + { + ColorSpace = components == 1 ? "/DeviceGray" : "/DeviceRGB"; + } + } + } + else if (PngDecoder.IsPng(imageBytes)) + { + if (!PngDecoder.ReadPngHeader(imageBytes, out int width, out int height, out int bitDepth, out int colorType, out int _)) + throw new InvalidDataException("Unsupported or oversized PNG image."); Width = width; Height = height; - if (components == 4) + Filter = "FlateDecode"; + if (colorType == 6 || colorType == 4) { - ColorSpace = "/DeviceCMYK"; - if (adobe) Decode = "[ 1 0 1 0 1 0 1 0 ]"; + BitsPerComponent = 8; + ColorSpace = colorType == 6 ? "/DeviceRGB" : "/DeviceGray"; + PngDecoder.DecodePngWithAlpha(imageBytes, width, height, blackAndWhite, colorType, out byte[] color, out byte[] alpha); + _bytes = color; + SoftMaskData = alpha; + HasSoftMask = true; + } + else if (colorType == 2 && blackAndWhite) + { + BitsPerComponent = 8; + ColorSpace = "/DeviceRGB"; + PngDecoder.DecodePngTruecolor(imageBytes, width, height, blackAndWhite, out byte[] grayRgb); + _bytes = grayRgb; } else { - ColorSpace = components == 1 ? "/DeviceGray" : "/DeviceRGB"; + BitsPerComponent = bitDepth; + _bytes = PngDecoder.ReadPngIdat(imageBytes, out byte[] palette); + int colors; + switch (colorType) + { + case 0: + ColorSpace = "/DeviceGray"; + colors = 1; + break; + case 3: + if (blackAndWhite && palette != null) + GrayscaleRgb(palette); + int hival = palette == null || palette.Length < 3 ? 0 : (palette.Length / 3) - 1; + ColorSpace = "[ /Indexed /DeviceRGB " + hival + " <" + PngDecoder.ToHex(palette) + "> ]"; + colors = 1; + if (PngDecoder.DecodeIndexedAlpha(imageBytes, width, height, bitDepth, out byte[] indexedAlpha)) + { + SoftMaskData = indexedAlpha; + HasSoftMask = true; + } + break; + default: + ColorSpace = "/DeviceRGB"; + colors = 3; + break; + } + DecodeParms = "<< /Predictor 15 /Colors " + colors + + " /BitsPerComponent " + bitDepth + + " /Columns " + width + " >>"; } } - } - else if (PngDecoder.IsPng(imageBytes)) - { - PngDecoder.ReadPngHeader(imageBytes, out int width, out int height, out int bitDepth, out int colorType, out int _); - Width = width; - Height = height; - Filter = "FlateDecode"; - if (colorType == 6 || colorType == 4) + else if (BmpDecoder.TryDecode(imageBytes, out int bmpW, out int bmpH, out byte[] bmpRgb)) { + Width = bmpW; + Height = bmpH; BitsPerComponent = 8; - ColorSpace = colorType == 6 ? "/DeviceRGB" : "/DeviceGray"; - PngDecoder.DecodePngWithAlpha(imageBytes, width, height, blackAndWhite, colorType, out byte[] color, out byte[] alpha); - _bytes = color; - SoftMaskData = alpha; - HasSoftMask = true; + ColorSpace = "/DeviceRGB"; + Filter = "FlateDecode"; + if (blackAndWhite) GrayscaleRgb(bmpRgb); + _bytes = PdfFlate.CompressLeaveOpen(bmpRgb, compressionLevel); } - else if (colorType == 2 && blackAndWhite) + else if (GifDecoder.TryDecode(imageBytes, out int gifW, out int gifH, out byte[] gifRgb, out byte[] gifAlpha)) { + Width = gifW; Height = gifH; BitsPerComponent = 8; ColorSpace = "/DeviceRGB"; - PngDecoder.DecodePngTruecolor(imageBytes, width, height, blackAndWhite, out byte[] grayRgb); - _bytes = grayRgb; + Filter = "FlateDecode"; + if (blackAndWhite) GrayscaleRgb(gifRgb); + _bytes = PdfFlate.CompressLeaveOpen(gifRgb, compressionLevel); + if (gifAlpha != null) { SoftMaskData = PdfFlate.CompressLeaveOpen(gifAlpha, compressionLevel); HasSoftMask = true; } } - else + else if (TiffDecoder.TryDecode(imageBytes, out int tifW, out int tifH, out byte[] tifRgb, out byte[] tifAlpha)) { - BitsPerComponent = bitDepth; - _bytes = PngDecoder.ReadPngIdat(imageBytes, out byte[] palette); - int colors; - switch (colorType) + Width = tifW; + Height = tifH; + BitsPerComponent = 8; + ColorSpace = "/DeviceRGB"; + Filter = "FlateDecode"; + if (blackAndWhite) GrayscaleRgb(tifRgb); + _bytes = PdfFlate.CompressLeaveOpen(tifRgb, compressionLevel); + if (tifAlpha != null) { - case 0: - ColorSpace = "/DeviceGray"; - colors = 1; - break; - case 3: - if (blackAndWhite && palette != null) - GrayscaleRgb(palette); - int hival = palette == null || palette.Length < 3 ? 0 : (palette.Length / 3) - 1; - ColorSpace = "[ /Indexed /DeviceRGB " + hival + " <" + PngDecoder.ToHex(palette) + "> ]"; - colors = 1; - if (PngDecoder.DecodeIndexedAlpha(imageBytes, width, height, bitDepth, out byte[] indexedAlpha)) - { - SoftMaskData = indexedAlpha; - HasSoftMask = true; - } - break; - default: - ColorSpace = "/DeviceRGB"; - colors = 3; - break; + SoftMaskData = PdfFlate.CompressLeaveOpen(tifAlpha, compressionLevel); + HasSoftMask = true; } - DecodeParms = "<< /Predictor 15 /Colors " + colors + - " /BitsPerComponent " + bitDepth + - " /Columns " + width + " >>"; } - } - else if (BmpDecoder.TryDecode(imageBytes, out int bmpW, out int bmpH, out byte[] bmpRgb)) - { - Width = bmpW; - Height = bmpH; - BitsPerComponent = 8; - ColorSpace = "/DeviceRGB"; - Filter = "FlateDecode"; - if (blackAndWhite) GrayscaleRgb(bmpRgb); - _bytes = PdfFlate.CompressLeaveOpen(bmpRgb, compressionLevel); - } - else if (GifDecoder.TryDecode(imageBytes, out int gifW, out int gifH, out byte[] gifRgb, out byte[] gifAlpha)) - { - Width = gifW; Height = gifH; - BitsPerComponent = 8; - ColorSpace = "/DeviceRGB"; - Filter = "FlateDecode"; - if (blackAndWhite) GrayscaleRgb(gifRgb); - _bytes = PdfFlate.CompressLeaveOpen(gifRgb, compressionLevel); - if (gifAlpha != null) { SoftMaskData = PdfFlate.CompressLeaveOpen(gifAlpha, compressionLevel); HasSoftMask = true; } - } - else if (TiffDecoder.TryDecode(imageBytes, out int tifW, out int tifH, out byte[] tifRgb, out byte[] tifAlpha)) - { - Width = tifW; - Height = tifH; - BitsPerComponent = 8; - ColorSpace = "/DeviceRGB"; - Filter = "FlateDecode"; - if (blackAndWhite) GrayscaleRgb(tifRgb); - _bytes = PdfFlate.CompressLeaveOpen(tifRgb, compressionLevel); - if (tifAlpha != null) + else { - SoftMaskData = PdfFlate.CompressLeaveOpen(tifAlpha, compressionLevel); - HasSoftMask = true; + _bytes = imageBytes; + Filter = "DCTDecode"; + BitsPerComponent = 8; + ColorSpace = "/DeviceRGB"; } } - else + catch (Exception ex) when ( ex is InvalidDataException || ex is IndexOutOfRangeException || ex is ArgumentException || ex is OverflowException) { - _bytes = imageBytes; - Filter = "DCTDecode"; + // Degrade to a 1x1 white pixel; the drawing area just renders blank. + Width = 1; + Height = 1; BitsPerComponent = 8; ColorSpace = "/DeviceRGB"; + Filter = "FlateDecode"; + Decode = null; + HasSoftMask = false; + SoftMaskData = null; + _bytes = PdfFlate.CompressLeaveOpen(new byte[] { 255, 255, 255 }, compressionLevel); } - } private PdfImageXObject(int objectNumber, int version, byte[] deflatedGray, int width, int height) diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs index aa6528ec8..5150d8d7c 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs @@ -23,6 +23,7 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Settings; +using EPPlus.Export.Pdf.Helpers; using System; namespace EPPlus.Export.Pdf.DocumentObjects @@ -49,11 +50,15 @@ private string Body() string sign = offset < TimeSpan.Zero ? "-" : "+"; offset = offset.Duration(); string pdfDate = string.Format("D:{0:yyyyMMddHHmmss}{1}{2:00}'{3:00}'", now, sign, offset.Hours, offset.Minutes); - return $"<< /Title ({Title})\n" + - $" /Author ({Author})\n" + - $" /Subject (EPPlus PDF Export with {LicenseType} for {LicenseHolder})\n" + - $" /Keywords (EPPlus, EPPlus Software, PDF, Export, {LicenseType}, {LicenseHolder})" + - $" /Creator (EPPlus Software {LicenseType}, {LicenseHolder})\n" + + string subject = "EPPlus PDF Export with " + LicenseType + " for " + LicenseHolder; + string keywords = "EPPlus, EPPlus Software, PDF, Export, " + LicenseType + ", " + LicenseHolder; + string creator = "EPPlus Software " + LicenseType + ", " + LicenseHolder; + + return $"<< /Title {Title.ToPdfTextString()}\n" + + $" /Author {Author.ToPdfTextString()}\n" + + $" /Subject {subject.ToPdfTextString()}\n" + + $" /Keywords {keywords.ToPdfTextString()}\n" + + $" /Creator {creator.ToPdfTextString()}\n" + $" /Producer (EPPlus Software PDF Exporter)\n" + $" /CreationDate ({pdfDate})\n" + $" /ModDate ({pdfDate})\n" + diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs index 3b0b1bcd8..f7b321ac6 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs @@ -43,9 +43,20 @@ public static PdfLinkAnnotationObject GoTo(int objectNumber, double lowerLeftX, private string Body() { - string action = IsGoTo - ? $"/A << /S /GoTo /D [ {DestPageObj.ToPdfStringF0()} 0 R /XYZ {DestX.ToPdfStringF4()} {DestY.ToPdfStringF4()} null ] >>" - : $"/A << /S /URI /URI {Uri.ToPdfLiteral()} >>"; + string action; + if (IsGoTo) + { + action = $"/A << /S /GoTo /D [ {DestPageObj.ToPdfStringF0()} 0 R /XYZ {DestX.ToPdfStringF4()} {DestY.ToPdfStringF4()} null ] >>"; + } + else if (!PdfString.IsDangerousUriScheme(Uri)) + { + action = $"/A << /S /URI /URI {Uri.ToPdfLiteral()} >>"; + } + else + { + // Active-content scheme (javascript:, file:, ...) -> emit an inert link, no action. + action = ""; + } string contents = string.IsNullOrEmpty(ToolTip) ? "" : $"\n /Contents {ToolTip.ToPdfTextString()}"; diff --git a/src/EPPlus.Export.Pdf/Helpers/BmpDecoder.cs b/src/EPPlus.Export.Pdf/Helpers/BmpDecoder.cs index 040300731..34c216a17 100644 --- a/src/EPPlus.Export.Pdf/Helpers/BmpDecoder.cs +++ b/src/EPPlus.Export.Pdf/Helpers/BmpDecoder.cs @@ -34,6 +34,7 @@ internal static bool TryDecode(byte[] d, out int width, out int height, out byte width = h.Width; height = h.Height; + if (!ImageLimits.IsAllowed(width, height, 3)) return false; var outRgb = new byte[width * height * 3]; if (h.Compression == BI_RLE8 || h.Compression == BI_RLE4) { diff --git a/src/EPPlus.Export.Pdf/Helpers/GifDecoder.cs b/src/EPPlus.Export.Pdf/Helpers/GifDecoder.cs index 205d6f668..c18263659 100644 --- a/src/EPPlus.Export.Pdf/Helpers/GifDecoder.cs +++ b/src/EPPlus.Export.Pdf/Helpers/GifDecoder.cs @@ -11,6 +11,7 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using System.IO; +using EPPlus.Export.Pdf.Helpers; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -50,7 +51,8 @@ internal static bool TryDecode(byte[] d, out int width, out int height, out byte pos += 10; if (fw <= 0 || fh <= 0 || fw > MaxDimension || fh > MaxDimension) return false; - + if (!ImageLimits.IsAllowed(screenW, screenH, 3) || !ImageLimits.IsAllowed(fw, fh, 1)) + return false; bool lctFlag = (packed & 0x80) != 0; bool interlace = (packed & 0x40) != 0; byte[] palette = gct; diff --git a/src/EPPlus.Export.Pdf/Helpers/IcoDecodercs.cs b/src/EPPlus.Export.Pdf/Helpers/IcoDecodercs.cs index ba6f05cdf..7960567a8 100644 --- a/src/EPPlus.Export.Pdf/Helpers/IcoDecodercs.cs +++ b/src/EPPlus.Export.Pdf/Helpers/IcoDecodercs.cs @@ -10,6 +10,7 @@ Date Author Change ************************************************************************************************* 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ +using EPPlus.Export.Pdf.Helpers; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -97,6 +98,7 @@ internal static bool TryDecodeDib(byte[] d, out int width, out int height, out b int andOffset = colorOffset + (int)colorSize; int andRow = ((w + 31) / 32) * 4; bool hasAnd = andOffset + (long)andRow * h <= d.Length; + if (!ImageLimits.IsAllowed(w, h, 3)) return false; var outRgb = new byte[w * h * 3]; var outAlpha = new byte[w * h]; bool anyTransparent = false; diff --git a/src/EPPlus.Export.Pdf/Helpers/ImageLimits.cs b/src/EPPlus.Export.Pdf/Helpers/ImageLimits.cs new file mode 100644 index 000000000..f7ad0b644 --- /dev/null +++ b/src/EPPlus.Export.Pdf/Helpers/ImageLimits.cs @@ -0,0 +1,46 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +namespace EPPlus.Export.Pdf.Helpers +{ + /// + /// Central guards for decoding untrusted embedded images. Dimensions come straight from + /// attacker-controlled image headers, so every decoder must validate them (in long space, + /// before allocating) to avoid int overflow, multi-GB allocations and decompression bombs. + /// + internal static class ImageLimits + { + /// Hard cap on either axis. Matches the existing BMP/GIF/TIFF/ICO caps. + internal const int MaxDimension = 30000; + + /// Total pixel ceiling. 100 MP keeps width*height*4 well inside Int32 range. + internal const long MaxPixels = 100_000_000; + + /// Upper bound on bytes produced by a single inflate (anti decompression-bomb). + internal const long MaxDecodedBytes = 512L * 1024 * 1024; + + /// + /// True only when width/height are positive, within range, and width*height*bytesPerPixel + /// stays within the pixel and byte ceilings. All arithmetic is done in long, so this never + /// overflows and can be called safely right before an allocation. + /// + internal static bool IsAllowed(int width, int height, int bytesPerPixel) + { + if (width <= 0 || height <= 0) return false; + if (width > MaxDimension || height > MaxDimension) return false; + long pixels = (long)width * height; + if (pixels > MaxPixels) return false; + if (pixels * bytesPerPixel > MaxDecodedBytes) return false; + return true; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/Helpers/JpegBlackWhiteHelper.cs b/src/EPPlus.Export.Pdf/Helpers/JpegBlackWhiteHelper.cs index d5679c9a9..7cf2c1181 100644 --- a/src/EPPlus.Export.Pdf/Helpers/JpegBlackWhiteHelper.cs +++ b/src/EPPlus.Export.Pdf/Helpers/JpegBlackWhiteHelper.cs @@ -230,6 +230,7 @@ private static byte[] TryTransform(byte[] d) } if (sosEnd < 0 || scanTermMarker < 0 || W == 0 || H == 0) return null; + if (!ImageLimits.IsAllowed(W, H, 4)) return null; bool threeYcbcr = comps == 3 && sNs == 3 && adobeTransform != 0; bool fourYcck = comps == 4 && sNs == 4 && adobeTransform == 2; // transform 0 on 3 comps = RGB, leave alone diff --git a/src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs b/src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs index ad2435e09..182eb6af8 100644 --- a/src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs +++ b/src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs @@ -193,7 +193,7 @@ private static bool Decode(byte[] d, out int width, out int height, out byte[] g i = segEnd; } - if (W == 0 || H == 0 || comps.Count != 4 || scanStart < 0) return false; + if (!ImageLimits.IsAllowed(W, H, 4)) return false; if (adobeTransform == 2) return false; // YCCK -> handled by the transcoder int Hmax = 1, Vmax = 1; diff --git a/src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs b/src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs index 88c72bf62..326096c2b 100644 --- a/src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs +++ b/src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs @@ -158,6 +158,7 @@ private static byte[] Transform(byte[] d) W = ((d[p + 3] & 0xFF) << 8) | (d[p + 4] & 0xFF); int nc = d[p + 5] & 0xFF; if (nc != 3) return null; + if (!ImageLimits.IsAllowed(W, H, 4)) return null; for (int c = 0; c < nc; c++) { int q = p + 6 + c * 3; diff --git a/src/EPPlus.Export.Pdf/Helpers/PdfColor.cs b/src/EPPlus.Export.Pdf/Helpers/PdfColor.cs index 572afba1a..4194e2975 100644 --- a/src/EPPlus.Export.Pdf/Helpers/PdfColor.cs +++ b/src/EPPlus.Export.Pdf/Helpers/PdfColor.cs @@ -63,40 +63,45 @@ public static Color SetColorFromHex(string hex) if (string.IsNullOrEmpty(hex) || hex == "0" || hex == "#0") { return Color.Empty; - } hex = hex.Trim().TrimStart('#'); - int R=0, G=0, B=0, A=0; - if (hex.Length == 3) - { - R = Convert.ToByte(new string(hex[0], 2), 16); - G = Convert.ToByte(new string(hex[1], 2), 16); - B = Convert.ToByte(new string(hex[2], 2), 16); - - } - else if (hex.Length == 4) - { - A = Convert.ToByte(new string(hex[0], 2), 16); - R = Convert.ToByte(new string(hex[1], 2), 16); - G = Convert.ToByte(new string(hex[2], 2), 16); - B = Convert.ToByte(new string(hex[3], 2), 16); - } - else if (hex.Length == 6) - { - R = Convert.ToByte(hex.Substring(0, 2), 16); - G = Convert.ToByte(hex.Substring(2, 2), 16); - B = Convert.ToByte(hex.Substring(4, 2), 16); - } - else if (hex.Length == 8) + int R = 0, G = 0, B = 0, A = 0; + try { - A = Convert.ToByte(hex.Substring(0, 2), 16); - R = Convert.ToByte(hex.Substring(2, 2), 16); - G = Convert.ToByte(hex.Substring(4, 2), 16); - B = Convert.ToByte(hex.Substring(6, 2), 16); + if (hex.Length == 3) + { + R = Convert.ToByte(new string(hex[0], 2), 16); + G = Convert.ToByte(new string(hex[1], 2), 16); + B = Convert.ToByte(new string(hex[2], 2), 16); + } + else if (hex.Length == 4) + { + A = Convert.ToByte(new string(hex[0], 2), 16); + R = Convert.ToByte(new string(hex[1], 2), 16); + G = Convert.ToByte(new string(hex[2], 2), 16); + B = Convert.ToByte(new string(hex[3], 2), 16); + } + else if (hex.Length == 6) + { + R = Convert.ToByte(hex.Substring(0, 2), 16); + G = Convert.ToByte(hex.Substring(2, 2), 16); + B = Convert.ToByte(hex.Substring(4, 2), 16); + } + else if (hex.Length == 8) + { + A = Convert.ToByte(hex.Substring(0, 2), 16); + R = Convert.ToByte(hex.Substring(2, 2), 16); + G = Convert.ToByte(hex.Substring(4, 2), 16); + B = Convert.ToByte(hex.Substring(6, 2), 16); + } + else + { + return Color.Empty; + } } - else + catch (FormatException) { - throw new FormatException("Invalid hex color format."); + return Color.Empty; // non-hex digits -> no colour instead of aborting the export } return Color.FromArgb(A, R, G, B); } diff --git a/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs b/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs index 651dca603..333971938 100644 --- a/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs +++ b/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs @@ -52,7 +52,7 @@ internal static byte[] CompressLeaveOpen(byte[] data, PdfCompressionLevel level } } - internal static byte[] Decompress(byte[] data) + internal static byte[] Decompress(byte[] data, long maxBytes = long.MaxValue) { using (var input = new MemoryStream(data)) using (var z = new ZlibStream(input, CompressionMode.Decompress)) @@ -60,7 +60,16 @@ internal static byte[] Decompress(byte[] data) { byte[] buffer = new byte[8192]; int n; - while ((n = z.Read(buffer, 0, buffer.Length)) > 0) output.Write(buffer, 0, n); + long total = 0; + while ((n = z.Read(buffer, 0, buffer.Length)) > 0) + { + total += n; + if (total > maxBytes) + { + throw new InvalidDataException("Compressed image stream expands beyond the allowed size."); + } + output.Write(buffer, 0, n); + } return output.ToArray(); } } diff --git a/src/EPPlus.Export.Pdf/Helpers/PdfString.cs b/src/EPPlus.Export.Pdf/Helpers/PdfString.cs index c3c1ad374..ed0c5a994 100644 --- a/src/EPPlus.Export.Pdf/Helpers/PdfString.cs +++ b/src/EPPlus.Export.Pdf/Helpers/PdfString.cs @@ -109,5 +109,64 @@ internal static string ToPdfTextString(this string val) sb.Append('>'); return sb.ToString(); } + + /// + /// Escapes a string for use as the body of a PDF name object (the part after '/'), + /// per the PDF spec: any character outside the regular set 0x21–0x7E, any of the + /// delimiters ()<>[]{}/% , and '#' itself are written as '#' followed by two hex + /// digits (UTF-8 bytes for non-ASCII). Leaves ordinary names (e.g. "ABCDEF+ArialMT") + /// byte-for-byte unchanged. + /// + internal static string ToPdfName(this string s) + { + if (string.IsNullOrEmpty(s)) return string.Empty; + var sb = new System.Text.StringBuilder(s.Length + 8); + foreach (byte b in System.Text.Encoding.UTF8.GetBytes(s)) + { + bool regular = b >= 0x21 && b <= 0x7E && + b != '(' && b != ')' && b != '<' && b != '>' && + b != '[' && b != ']' && b != '{' && b != '}' && + b != '/' && b != '%' && b != '#'; + if (regular) sb.Append((char)b); + else { sb.Append('#'); sb.Append(((int)b).ToString("X2")); } + } + return sb.ToString(); + } + + /// + /// True if a hyperlink URI uses an active-content scheme that should never be turned into + /// a PDF URI action (javascript:, vbscript:, data:, file:, about:). Whitespace and control + /// characters are stripped first so "java\tscript:" / " javascript:" can't slip past. + /// Relative URIs and ordinary web/mail schemes are treated as safe. + /// + internal static bool IsDangerousUriScheme(string uri) + { + if (string.IsNullOrEmpty(uri)) return false; + + var sb = new System.Text.StringBuilder(uri.Length); + foreach (char c in uri) if (c > ' ') sb.Append(c); // drop spaces + control chars + string norm = sb.ToString(); + + int colon = norm.IndexOf(':'); + if (colon <= 0) return false; // no scheme (relative) -> safe + for (int i = 0; i < colon; i++) + { + char c = norm[i]; + bool schemeChar = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (i > 0 && ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')); + if (!schemeChar) return false; // not a real scheme -> leave as-is + } + switch (norm.Substring(0, colon).ToLowerInvariant()) + { + case "javascript": + case "vbscript": + case "data": + case "file": + case "about": + return true; + default: + return false; + } + } } } diff --git a/src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs b/src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs index 43cc2fa97..a1efb8432 100644 --- a/src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs +++ b/src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs @@ -40,6 +40,7 @@ internal static bool ReadPngHeader(byte[] d, out int width, out int height, out bitDepth = d[q + 8]; colorType = d[q + 9]; interlace = d[q + 12]; + if (!ImageLimits.IsAllowed(width, height, 4)) return false; return true; } @@ -77,6 +78,8 @@ internal static byte[] ReadPngIdat(byte[] d, out byte[] palette) internal static void DecodePngTruecolor(byte[] pngBytes, int width, int height, bool blackAndWhite, out byte[] deflatedRgb) { const int channels = 3; + if (!ImageLimits.IsAllowed(width, height, channels)) + throw new InvalidDataException("PNG dimensions exceed the allowed limit."); byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _)); int stride = width * channels; var rgb = new byte[width * height * channels]; @@ -116,6 +119,8 @@ internal static void DecodePngWithAlpha(byte[] pngBytes, int width, int height, { int channels = colorType == 6 ? 4 : 2; int colorChannels = colorType == 6 ? 3 : 1; + if (!ImageLimits.IsAllowed(width, height, channels)) + throw new InvalidDataException("PNG dimensions exceed the allowed limit."); byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _)); int stride = width * channels; @@ -206,7 +211,7 @@ internal static bool DecodeIndexedAlpha(byte[] pngBytes, int width, int height, deflatedAlpha = null; if (!TryReadChunk(pngBytes, "tRNS", out byte[] trns) || trns == null || trns.Length == 0) return false; - + if (!ImageLimits.IsAllowed(width, height, 1)) return false; byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _)); const int bpp = 1; int stride = (width * bitDepth + 7) / 8; diff --git a/src/EPPlus.Export.Pdf/Helpers/TiffDecoder.cs b/src/EPPlus.Export.Pdf/Helpers/TiffDecoder.cs index 3fc630775..7706d2c19 100644 --- a/src/EPPlus.Export.Pdf/Helpers/TiffDecoder.cs +++ b/src/EPPlus.Export.Pdf/Helpers/TiffDecoder.cs @@ -12,6 +12,7 @@ Date Author Change *************************************************************************************************/ using OfficeOpenXml.Packaging.Ionic.Zlib; using System.IO; +using EPPlus.Export.Pdf.Helpers; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -99,6 +100,7 @@ internal static bool TryDecode(byte[] d, out int width, out int height, out byte if (predictor != 1 && predictor != 2) return false; if (compression != 1 && compression != 5 && compression != 8 && compression != 32946 && compression != 32773) return false; int w = (int)imgW, h = (int)imgH, samples = (int)spp; + if (!ImageLimits.IsAllowed(w, h, 4)) return false; int bits = (bitsPerSample != null && bitsPerSample.Length > 0) ? (int)bitsPerSample[0] : 1; if (bitsPerSample != null) foreach (var b in bitsPerSample) @@ -134,7 +136,7 @@ internal static bool TryDecode(byte[] d, out int width, out int height, out byte case 1: strip = raw; break; case 5: strip = LzwDecode(raw, expected); break; case 32773: strip = PackBits(raw, expected); break; - default: strip = Inflate(raw); break; + default: strip = Inflate(raw, ImageLimits.MaxDecodedBytes); break; } if (strip == null) return false; int copy = System.Math.Min(expected, strip.Length); @@ -251,7 +253,7 @@ private static byte[] PackBits(byte[] s, int expected) return outBuf; } - private static byte[] Inflate(byte[] s) + private static byte[] Inflate(byte[] s, long maxBytes) { try { @@ -261,7 +263,13 @@ private static byte[] Inflate(byte[] s) { var buf = new byte[8192]; int n; - while ((n = z.Read(buf, 0, buf.Length)) > 0) output.Write(buf, 0, n); + long total = 0; + while ((n = z.Read(buf, 0, buf.Length)) > 0) + { + total += n; + if (total > maxBytes) return null; + output.Write(buf, 0, n); + } return output.ToArray(); } } @@ -371,7 +379,7 @@ private static long ReadValue(byte[] d, bool be, int type, int fieldOffset) private static long[] ReadValues(byte[] d, bool be, int type, int count, int fieldOffset) { int ts = TypeSize(type); - if (ts == 0 || count <= 0 || count > (1 << 24)) return new long[0]; + if (ts == 0 || count <= 0 || count > (1 << 20)) return new long[0]; long total = (long)ts * count; int dataOffset = total <= 4 ? fieldOffset : (int)ReadU32(d, be, fieldOffset); var vals = new long[count];