Skip to content
Open
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
87 changes: 87 additions & 0 deletions src/EPPlus.Export.Pdf.Tests/ImageDecoderSecurityTests.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// 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.
/// </summary>
[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;

/// <summary>The header parses as a PNG but the dimensions must be rejected by the guard.</summary>
[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);
}

/// <summary>Calling the decode path directly must throw a clean, typed error — never overflow/OOM.</summary>
[TestMethod]
public void DecodePngWithAlpha_OnOversized_ThrowsInvalidData()
{
Assert.ThrowsExactly<InvalidDataException>(() =>
PngDecoder.DecodePngWithAlpha(
OversizedRgbaPng, OversizedW, OversizedH,
blackAndWhite: false, colorType: RgbaColorType,
out _, out _));
}

/// <summary>End-to-end: a workbook containing the oversized image still exports cleanly.</summary>
[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.");
}
}
}
74 changes: 74 additions & 0 deletions src/EPPlus.Export.Pdf.Tests/PdfLowRiskHardeningTests.cs
Original file line number Diff line number Diff line change
@@ -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");
}
}
}
44 changes: 44 additions & 0 deletions src/EPPlus.Export.Pdf.Tests/PdfMetadataSecurityTests.cs
Original file line number Diff line number Diff line change
@@ -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 <FEFF", "Title should be emitted as a hex string.");
StringAssert.Contains(body, "/Author <FEFF", "Author should be emitted as a hex string.");

// The injected keyword must not survive as literal PDF syntax anywhere in the object.
Assert.IsFalse(body.Contains("/JavaScript"), "Injected /JavaScript token leaked into the Info dictionary.");
Assert.IsFalse(body.Contains("endobj"), "Injected 'endobj' leaked into the Info dictionary.");

// The Info dictionary must still be exactly one well-formed object:
// one opening "<<" and one closing ">>", 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;
}
}
}
4 changes: 2 additions & 2 deletions src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
2 changes: 1 addition & 1 deletion src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(" >>");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Loading
Loading