Skip to content

Commit 9df9713

Browse files
authored
Fix/pdf security (#2630)
* High risk exploits fixed * fixed more low risk security concerns
1 parent 4b702c2 commit 9df9713

23 files changed

Lines changed: 545 additions & 167 deletions
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
using EPPlus.Export.Pdf.Helpers; // internal PngDecoder (InternalsVisibleTo is already set)
2+
using EPPlus.Export.Pdf.Tests; // PdfTestBase -> TestBase (license + OpenTemplatePackage)
3+
using OfficeOpenXml;
4+
using OfficeOpenXml.Export.PdfExport; // SaveAsPdf extension methods
5+
using System;
6+
using System.IO;
7+
using System.Text;
8+
9+
namespace EPPlusTest.PDF
10+
{
11+
/// <summary>
12+
/// Security regression tests for the embedded-image decoders. The attack: a tiny PNG whose
13+
/// IHDR *declares* enormous dimensions (30000x30000) while the IDAT is a real 1x1 pixel.
14+
/// The decoder sizes its output buffer from the header (width*height*3 in Int32), which
15+
/// overflows to a negative length and throws, aborting the entire export. Reachable by anyone
16+
/// who can get an image into a workbook that gets converted to PDF.
17+
/// </summary>
18+
[TestClass]
19+
public class ImageDecoderSecurityTests : PdfTestBase
20+
{
21+
// IHDR says 30000x30000, 8-bit, colour type 6 (RGBA). IDAT is a valid zlib stream for one
22+
// 1x1 pixel. (Exact bytes of evil_oversized_30000x30000.png.)
23+
private static readonly byte[] OversizedRgbaPng = new byte[]
24+
{
25+
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13,
26+
73, 72, 68, 82, 0, 0, 117, 48, 0, 0, 117, 48,
27+
8, 6, 0, 0, 0, 102, 39, 248, 186, 0, 0, 0,
28+
13, 73, 68, 65, 84, 120, 218, 99, 248, 207, 192, 240,
29+
31, 0, 5, 0, 1, 255, 86, 199, 47, 13, 0, 0,
30+
0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
31+
};
32+
33+
private const int OversizedW = 30000;
34+
private const int OversizedH = 30000;
35+
private const int RgbaColorType = 6;
36+
37+
/// <summary>The header parses as a PNG but the dimensions must be rejected by the guard.</summary>
38+
[TestMethod]
39+
public void PngDecoder_RejectsOversizedDimensions()
40+
{
41+
Assert.IsTrue(PngDecoder.IsPng(OversizedRgbaPng));
42+
43+
bool ok = PngDecoder.ReadPngHeader(
44+
OversizedRgbaPng, out int w, out int h, out int bitDepth, out int colorType, out _);
45+
46+
Assert.IsFalse(ok, "Oversized PNG header must be rejected by the ImageLimits guard.");
47+
// Dimensions are still parsed out (the guard runs after reading them) — confirm the
48+
// payload really is the oversized one, so this test can't pass for the wrong reason.
49+
Assert.AreEqual(OversizedW, w);
50+
Assert.AreEqual(OversizedH, h);
51+
Assert.AreEqual(RgbaColorType, colorType);
52+
}
53+
54+
/// <summary>Calling the decode path directly must throw a clean, typed error — never overflow/OOM.</summary>
55+
[TestMethod]
56+
public void DecodePngWithAlpha_OnOversized_ThrowsInvalidData()
57+
{
58+
Assert.ThrowsExactly<InvalidDataException>(() =>
59+
PngDecoder.DecodePngWithAlpha(
60+
OversizedRgbaPng, OversizedW, OversizedH,
61+
blackAndWhite: false, colorType: RgbaColorType,
62+
out _, out _));
63+
}
64+
65+
/// <summary>End-to-end: a workbook containing the oversized image still exports cleanly.</summary>
66+
[TestMethod]
67+
public void Export_WithOversizedPng_DoesNotThrow_AndProducesValidPdf()
68+
{
69+
using var p = OpenTemplatePackage("PDFTest.xlsx");
70+
var ws = p.Workbook.Worksheets[0];
71+
72+
using (var imgStream = new MemoryStream(OversizedRgbaPng))
73+
ws.Drawings.AddPicture("evil_oversized", imgStream);
74+
75+
using var ms = new MemoryStream();
76+
77+
ws.SaveAsPdf(ms); // must NOT throw — the bad image is skipped/blanked
78+
79+
byte[] bytes = ms.ToArray();
80+
Assert.IsTrue(bytes.Length > 8, "No PDF was produced.");
81+
Assert.AreEqual("%PDF-", Encoding.ASCII.GetString(bytes, 0, 5), "Missing PDF header.");
82+
83+
string tail = Encoding.ASCII.GetString(bytes, Math.Max(0, bytes.Length - 8), Math.Min(8, bytes.Length));
84+
Assert.IsTrue(tail.Contains("%%EOF"), "Missing %%EOF trailer — document is truncated.");
85+
}
86+
}
87+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
using EPPlus.Export.Pdf.DocumentObjects;
2+
using EPPlus.Export.Pdf.DocumentObjects.Fonts;
3+
using EPPlus.Export.Pdf.Helpers;
4+
5+
namespace EPPlusTest.PDF
6+
{
7+
[TestClass]
8+
public class PdfLowRiskHardeningTests
9+
{
10+
[TestMethod]
11+
public void FontName_EscapesPdfDelimiters()
12+
{
13+
var font = new PdfFont(1, "Evil) /Type /Catalog (x", PdfFontSubType.Type1);
14+
string body = font.RenderBody();
15+
16+
Assert.IsFalse(body.Contains("Evil)"), "Unescaped ')' leaked into /BaseFont.");
17+
StringAssert.Contains(body, "Evil#29", "')' should be escaped as #29.");
18+
StringAssert.Contains(body, "#2F", "'/' should be escaped as #2F.");
19+
}
20+
21+
[TestMethod]
22+
public void FontDescriptor_EscapesPdfDelimiters()
23+
{
24+
var fd = new PdfFontDescriptor(1, "Bad>Name) (", 0, new EPPlus.Graphics.Rect(), 0, 0, 0, 0, 0);
25+
string body = fd.RenderBody();
26+
27+
Assert.IsFalse(body.Contains("Bad>Name"), "Unescaped '>' leaked into /FontName.");
28+
StringAssert.Contains(body, "#3E", "'>' should be escaped as #3E.");
29+
}
30+
31+
[TestMethod]
32+
public void LinkAnnotation_DropsJavascriptUri()
33+
{
34+
var evil = new PdfLinkAnnotationObject(1, 0, 0, 10, 10, "javascript:app.alert('x')", null);
35+
string body = evil.RenderBody();
36+
37+
Assert.IsFalse(body.Contains("/URI"), "javascript: must not produce a URI action.");
38+
Assert.IsFalse(body.Contains("javascript"), "Dangerous scheme leaked into the annotation.");
39+
StringAssert.Contains(body, "/Subtype /Link", "The link annotation itself should still be emitted (inert).");
40+
}
41+
42+
[TestMethod]
43+
public void LinkAnnotation_KeepsSafeUri()
44+
{
45+
var safe = new PdfLinkAnnotationObject(2, 0, 0, 10, 10, "https://example.com/report", null);
46+
string body = safe.RenderBody();
47+
48+
StringAssert.Contains(body, "/S /URI");
49+
StringAssert.Contains(body, "example.com");
50+
}
51+
52+
[TestMethod]
53+
public void LinkAnnotation_BlocksObfuscatedScheme()
54+
{
55+
// leading space + embedded tab must not bypass the filter
56+
var evil = new PdfLinkAnnotationObject(3, 0, 0, 10, 10, " java\tscript:evil()", null);
57+
string body = evil.RenderBody();
58+
59+
Assert.IsFalse(body.Contains("/URI"), "Obfuscated javascript: bypassed the scheme filter.");
60+
}
61+
62+
[TestMethod]
63+
public void CidFont_BaseFont_EscapesPdfDelimiters()
64+
{
65+
// PdfCIDFont derives BaseFont from fontData.FullName — exercised via the resource layer
66+
// in a full export; here we assert the escaping contract on the emitted token directly.
67+
string name = "Evil) /Type /Catalog (x";
68+
string escaped = name.Replace(" ", "").ToPdfName(); // ToPdfName is the fix
69+
Assert.IsFalse(escaped.Contains(")"), "')' must be hex-escaped in a PDF name.");
70+
Assert.IsFalse(escaped.Contains("/"), "'/' must be hex-escaped in a PDF name.");
71+
StringAssert.Contains(escaped, "#29");
72+
}
73+
}
74+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using EPPlus.Export.Pdf.DocumentObjects;
2+
using EPPlus.Export.Pdf.Settings;
3+
4+
namespace EPPlusTest.PDF
5+
{
6+
[TestClass]
7+
public class PdfMetadataSecurityTests
8+
{
9+
[TestMethod]
10+
public void InfoDictionary_EscapesMetadata_NoPdfInjection()
11+
{
12+
// A parenthesis breakout that tries to close the string + dictionary and inject an action.
13+
var settings = new PdfDocumentSettings
14+
{
15+
Title = "Report) >> endobj /JavaScript (app.alert\\('pwn'\\)) (",
16+
Author = "a) b ( c \\ d",
17+
LicenseType = "Lic)Type",
18+
LicenseHolder = "Holder) ("
19+
};
20+
21+
string body = new PdfInfoObject(1, settings).RenderBody();
22+
23+
// Title/Author are hex strings now, not literals -> the payload cannot appear as tokens.
24+
StringAssert.Contains(body, "/Title <FEFF", "Title should be emitted as a hex string.");
25+
StringAssert.Contains(body, "/Author <FEFF", "Author should be emitted as a hex string.");
26+
27+
// The injected keyword must not survive as literal PDF syntax anywhere in the object.
28+
Assert.IsFalse(body.Contains("/JavaScript"), "Injected /JavaScript token leaked into the Info dictionary.");
29+
Assert.IsFalse(body.Contains("endobj"), "Injected 'endobj' leaked into the Info dictionary.");
30+
31+
// The Info dictionary must still be exactly one well-formed object:
32+
// one opening "<<" and one closing ">>", and no stray literal "()" breakout.
33+
Assert.AreEqual(1, CountOccurrences(body, "<<"), "Info dict should open exactly once.");
34+
Assert.AreEqual(1, CountOccurrences(body, ">>"), "Info dict should close exactly once.");
35+
}
36+
37+
private static int CountOccurrences(string s, string sub)
38+
{
39+
int n = 0, i = 0;
40+
while ((i = s.IndexOf(sub, i, System.StringComparison.Ordinal)) >= 0) { n++; i += sub.Length; }
41+
return n;
42+
}
43+
}
44+
}

‎src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ private string Body()
8585
var sb = new StringBuilder();
8686
sb.AppendFormat($"<< /Type /Font\n" +
8787
$" /Subtype /{Subtype.ToString()}\n" +
88-
$" /BaseFont /{BaseFont}\n" +
89-
$" /CIDSystemInfo << /Registry ({CIDInfoObject.Registry}) /Ordering ({CIDInfoObject.Ordering}) /Supplement {CIDInfoObject.Supplement} >>\n" +
88+
$" /BaseFont /{BaseFont.ToPdfName()}\n" +
89+
$" /CIDSystemInfo << /Registry {CIDInfoObject.Registry.ToPdfLiteral()} /Ordering {CIDInfoObject.Ordering.ToPdfLiteral()} /Supplement {CIDInfoObject.Supplement} >>\n" +
9090
$" /FontDescriptor {FontDescriptorObjectNumber.ToPdfStringF0()} 0 R");
9191
if (DW != null)
9292
{

‎src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ private string Body()
6060
var sb = new StringBuilder();
6161
sb.AppendFormat($"<< /Type /Font\n" +
6262
$" /Subtype /{subType}\n" +
63-
$" /BaseFont /{baseFont.Replace(" ", "")}");
63+
$" /BaseFont /{baseFont.Replace(" ", "").ToPdfName()}");
6464
if (encoding == PdfFontEncoding.None)
6565
{
6666
sb.Append(" >>");

‎src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ private string Body()
6767
{
6868
StringBuilder sb = new StringBuilder();
6969
sb.AppendFormat($"<< /Type /FontDescriptor\n" +
70-
$" /FontName /{fontName.Replace(" ", "")}\n" +
70+
$" /FontName /{fontName.Replace(" ", "").ToPdfName()}\n" +
7171
$" /Flags {flags.ToPdfStringF0()}\n" +
7272
$" /FontBBox [{fontBBox.X.ToPdfStringF0()} {fontBBox.Y.ToPdfStringF0()} {fontBBox.Width.ToPdfStringF0()} {fontBBox.Height.ToPdfStringF0()}]\n" +
7373
$" /Ascent {ascent.ToPdfStringF0()}\n" +

‎src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ private string Body()
3838
var sb = new StringBuilder();
3939
sb.AppendFormat($"<< /Type /Font\n" +
4040
$" /Subtype /Type0\n" +
41-
$" /BaseFont /{BaseFont}\n" +
41+
$" /BaseFont /{BaseFont.ToPdfName()}\n" +
4242
$" /Encoding /{Encoding}\n" +
4343
$" /DescendantFonts [{DescendantFontsObjectNumbers.ToPdfStringF0()} 0 R]");
4444
if (ToUnicodeObjectNumber > 0)

‎src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ internal class PdfContentStream : PdfObject
3434
private readonly Stack<(int index, string header)> _artifactMarks = new Stack<(int, string)>();
3535

3636
public void BeginArtifact() => _artifactMarks.Push((commands.Count, "/Artifact BMC"));
37-
public void BeginArtifact(string type) => _artifactMarks.Push((commands.Count, $"/Artifact << /Type /{type} >> BDC"));
37+
public void BeginArtifact(string type) => _artifactMarks.Push((commands.Count, $"/Artifact << /Type /{type.ToPdfName()} >> BDC"));
3838

3939
public void EndArtifact()
4040
{

0 commit comments

Comments
 (0)