Skip to content

Commit 462cc2b

Browse files
authored
Found some more potential security flaws (#2633)
1 parent 9df9713 commit 462cc2b

11 files changed

Lines changed: 104 additions & 35 deletions

File tree

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

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -282,13 +282,24 @@ private void DrawDoubleBorder(PdfContentStream contentStream, PdfCellBorderData
282282
contentStream.AddCommand($"{PdfCellBorderData.DoubleWidth.ToPdfString()} w");
283283
contentStream.AddCommand(border.BorderStyle != ExcelBorderStyle.Dotted ? (border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown ? "0 J" : "2 J") : "1 J");
284284
contentStream.AddCommand(PdfCellBorderData.NoDash);
285-
if ((border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown) && DiagonalUp.BorderStyle != ExcelBorderStyle.None && DiagonalDown.BorderStyle != ExcelBorderStyle.None)
285+
286+
double idx = ix2 - ix1, idy = iy2 - iy1;
287+
double odx = ox2 - ox1, ody = oy2 - oy1;
288+
double iLen = System.Math.Sqrt(idx * idx + idy * idy);
289+
double oLen = System.Math.Sqrt(odx * odx + ody * ody);
290+
291+
// Only split the line to leave the mid-gap when both segments have real length;
292+
// a zero-length (degenerate / zero-size cell) segment would divide by zero -> NaN operands.
293+
bool diagDoubleGap =
294+
(border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown)
295+
&& DiagonalUp.BorderStyle != ExcelBorderStyle.None
296+
&& DiagonalDown.BorderStyle != ExcelBorderStyle.None
297+
&& iLen > 1e-6 && oLen > 1e-6;
298+
299+
if (diagDoubleGap)
286300
{
287-
double dx = ix2 - ix1;
288-
double dy = iy2 - iy1;
289-
double length = System.Math.Sqrt(dx * dx + dy * dy);
290-
double ux = dx / length;
291-
double uy = dy / length;
301+
double ux = idx / iLen;
302+
double uy = idy / iLen;
292303
double midX = (ix1 + ix2) / 2.0;
293304
double midY = (iy1 + iy2) / 2.0;
294305
double leftDist = 0.25;
@@ -301,11 +312,9 @@ private void DrawDoubleBorder(PdfContentStream contentStream, PdfCellBorderData
301312
contentStream.AddCommand($"{xA.ToPdfStringF4()} {yA.ToPdfStringF4()} l");
302313
contentStream.AddCommand($"{xB.ToPdfStringF4()} {yB.ToPdfStringF4()} m");
303314
contentStream.AddCommand($"{ix2.ToPdfStringF4()} {iy2.ToPdfStringF4()} l");
304-
dx = ox2 - ox1;
305-
dy = oy2 - oy1;
306-
length = System.Math.Sqrt(dx * dx + dy * dy);
307-
ux = dx / length;
308-
uy = dy / length;
315+
316+
ux = odx / oLen;
317+
uy = ody / oLen;
309318
midX = (ox1 + ox2) / 2.0;
310319
midY = (oy1 + oy2) / 2.0;
311320
leftDist = 2.15;

‎src/EPPlus.Export.Pdf/Helpers/ImageLimits.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ internal static class ImageLimits
2828
/// <summary>Upper bound on bytes produced by a single inflate (anti decompression-bomb).</summary>
2929
internal const long MaxDecodedBytes = 512L * 1024 * 1024;
3030

31+
internal const long MaxDecodeWorkingBytes = 256L * 1024 * 1024;
32+
33+
internal static bool IsDecodeAllowed(int width, int height, int bytesPerPixel)
34+
{
35+
if (!IsAllowed(width, height, 1)) return false; // dimension + 100 MP guard
36+
return (long)width * height * bytesPerPixel <= MaxDecodeWorkingBytes;
37+
}
38+
3139
/// <summary>
3240
/// True only when width/height are positive, within range, and width*height*bytesPerPixel
3341
/// stays within the pixel and byte ceilings. All arithmetic is done in long, so this never

‎src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ private static bool Decode(byte[] d, out int width, out int height, out byte[] g
193193
i = segEnd;
194194
}
195195

196-
if (!ImageLimits.IsAllowed(W, H, 4)) return false;
196+
if (!ImageLimits.IsDecodeAllowed(W, H, 32)) return false;
197197
if (adobeTransform == 2) return false; // YCCK -> handled by the transcoder
198198

199199
int Hmax = 1, Vmax = 1;

‎src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ private static byte[] Transform(byte[] d)
158158
W = ((d[p + 3] & 0xFF) << 8) | (d[p + 4] & 0xFF);
159159
int nc = d[p + 5] & 0xFF;
160160
if (nc != 3) return null;
161-
if (!ImageLimits.IsAllowed(W, H, 4)) return null;
161+
if (!ImageLimits.IsDecodeAllowed(W, H, 12)) return null;
162162
for (int c = 0; c < nc; c++)
163163
{
164164
int q = p + 6 + c * 3;

‎src/EPPlus.Export.Pdf/Helpers/PdfString.cs‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,20 @@ internal static bool IsDangerousUriScheme(string uri)
143143
{
144144
if (string.IsNullOrEmpty(uri)) return false;
145145

146+
// Normalize: percent-decode one level, then drop spaces + control chars, so
147+
// "java\tscript:", " javascript:", "java%73cript:" and "javascript%3A..."
148+
// all resolve to their real scheme before the blocklist check below.
146149
var sb = new System.Text.StringBuilder(uri.Length);
147-
foreach (char c in uri) if (c > ' ') sb.Append(c); // drop spaces + control chars
150+
for (int i = 0; i < uri.Length; i++)
151+
{
152+
char c = uri[i];
153+
if (c == '%' && i + 2 < uri.Length && IsHex(uri[i + 1]) && IsHex(uri[i + 2]))
154+
{
155+
c = (char)((HexVal(uri[i + 1]) << 4) | HexVal(uri[i + 2]));
156+
i += 2;
157+
}
158+
if (c > ' ') sb.Append(c); // drop spaces + control chars
159+
}
148160
string norm = sb.ToString();
149161

150162
int colon = norm.IndexOf(':');
@@ -168,5 +180,11 @@ internal static bool IsDangerousUriScheme(string uri)
168180
return false;
169181
}
170182
}
183+
184+
private static bool IsHex(char c) =>
185+
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
186+
187+
private static int HexVal(char c) =>
188+
c <= '9' ? c - '0' : (char.ToLowerInvariant(c) - 'a' + 10);
171189
}
172190
}

‎src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ internal static byte[] ReadPngIdat(byte[] d, out byte[] palette)
5555
int len = ReadBE32(d, p);
5656
string type = Ascii(d, p + 4, 4);
5757
int dataStart = p + 8;
58-
if (len < 0 || dataStart + len + 4 > d.Length) break;
58+
long end = (long)dataStart + len + 4;
59+
if (len < 0 || end > d.Length) break;
5960
if (type == "PLTE")
6061
{
6162
palette = new byte[len];
@@ -80,8 +81,9 @@ internal static void DecodePngTruecolor(byte[] pngBytes, int width, int height,
8081
const int channels = 3;
8182
if (!ImageLimits.IsAllowed(width, height, channels))
8283
throw new InvalidDataException("PNG dimensions exceed the allowed limit.");
83-
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));
8484
int stride = width * channels;
85+
long maxFiltered = (long)height * (stride + 1);
86+
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
8587
var rgb = new byte[width * height * channels];
8688
var prev = new byte[stride];
8789
var cur = new byte[stride];
@@ -121,9 +123,9 @@ internal static void DecodePngWithAlpha(byte[] pngBytes, int width, int height,
121123
int colorChannels = colorType == 6 ? 3 : 1;
122124
if (!ImageLimits.IsAllowed(width, height, channels))
123125
throw new InvalidDataException("PNG dimensions exceed the allowed limit.");
124-
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));
125-
126-
int stride = width * channels;
126+
int stride = width * channels; // channels = 4 or 2
127+
long maxFiltered = (long)height * (stride + 1);
128+
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
127129
var color = new byte[width * height * colorChannels];
128130
var alpha = new byte[width * height];
129131
var prev = new byte[stride];
@@ -193,7 +195,8 @@ internal static bool TryReadChunk(byte[] d, string chunkType, out byte[] data)
193195
int len = ReadBE32(d, p);
194196
string type = Ascii(d, p + 4, 4);
195197
int dataStart = p + 8;
196-
if (len < 0 || dataStart + len + 4 > d.Length) break;
198+
long end = (long)dataStart + len + 4;
199+
if (len < 0 || end > d.Length) break;
197200
if (type == chunkType)
198201
{
199202
data = new byte[len];
@@ -212,9 +215,10 @@ internal static bool DecodeIndexedAlpha(byte[] pngBytes, int width, int height,
212215
if (!TryReadChunk(pngBytes, "tRNS", out byte[] trns) || trns == null || trns.Length == 0)
213216
return false;
214217
if (!ImageLimits.IsAllowed(width, height, 1)) return false;
215-
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));
216-
const int bpp = 1;
217218
int stride = (width * bitDepth + 7) / 8;
219+
long maxFiltered = (long)height * (stride + 1);
220+
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
221+
const int bpp = 1;
218222
var prev = new byte[stride];
219223
var cur = new byte[stride];
220224
var alpha = new byte[width * height];

‎src/EPPlus/Export/PdfExport/Data/PdfCellCollection.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ internal class PdfCellCollection
2323

2424
private PdfCell[,] Cells;
2525

26+
internal const long MaxCells = 64L * 1024 * 1024;
27+
2628
public PdfCellCollection(int fromRow, int toRow, int fromColumn, int toColumn)
2729
{
2830
if(fromRow > toRow) throw new ArgumentOutOfRangeException("Invalid row range. toRow must be equal or greater than fromRow");
@@ -33,7 +35,8 @@ public PdfCellCollection(int fromRow, int toRow, int fromColumn, int toColumn)
3335
ToColumn = toColumn;
3436
int x = toRow - fromRow + 1;
3537
int y = toColumn - fromColumn + 1;
36-
38+
if ((long)x * y > MaxCells)
39+
throw new System.InvalidOperationException($"PDF export range is too large ({x} rows × {y} columns). " + "Reduce the print area or the worksheet's used range.");
3740
Cells = new PdfCell[x, y];
3841
}
3942

‎src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -537,15 +537,23 @@ private void GetPrintTitles(PdfRenderSettings pageSettings, PdfWorksheet pdfShee
537537
//Check PdfPageSettings overrides
538538
if (pageSettings.RowsToRepeatAtTop != null)
539539
{
540-
ExcelAddressBase repeatRows = new ExcelAddressBase(pageSettings.RowsToRepeatAtTop);
541-
pdfSheet.PrintTitleRowFrom = repeatRows._fromRow;
542-
pdfSheet.PrintTitleRowTo = repeatRows._toRow;
540+
try
541+
{
542+
var repeatRows = new ExcelAddressBase(pageSettings.RowsToRepeatAtTop);
543+
pdfSheet.PrintTitleRowFrom = repeatRows._fromRow;
544+
pdfSheet.PrintTitleRowTo = repeatRows._toRow;
545+
}
546+
catch {}
543547
}
544548
if (pageSettings.ColumnsToRepeatAtLeft != null)
545549
{
546-
ExcelAddressBase repeatCols = new ExcelAddressBase(pageSettings.ColumnsToRepeatAtLeft);
547-
pdfSheet.PrintTitleColFrom = repeatCols._fromCol;
548-
pdfSheet.PrintTitleColTo = repeatCols._toCol;
550+
try
551+
{
552+
var repeatCols = new ExcelAddressBase(pageSettings.ColumnsToRepeatAtLeft);
553+
pdfSheet.PrintTitleColFrom = repeatCols._fromCol;
554+
pdfSheet.PrintTitleColTo = repeatCols._toCol;
555+
}
556+
catch {}
549557
}
550558
foreach (var range in pdfSheet.Ranges)
551559
MarkPrintTitleCells(pdfSheet, range);

‎src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,7 @@ private static PdfPageSize GetPageSize(ePaperSize PaperSize)
227227
case ePaperSize.A3ExtraTransverse:
228228
return PdfPageSize.A3ExtraTransverse;
229229
default:
230-
//should return custom paper size instead.
231-
throw new ArgumentOutOfRangeException(nameof(PaperSize), PaperSize, "Unsupported paper size.");
230+
return PdfPageSize.A4;
232231
}
233232

234233
}

‎src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P
7979
text += DateTime.Now.ToString($"yyyy-MM-dd");
8080
break;
8181
case ExcelHeaderFooterFormattingCodes.FileName:
82-
text += ws._package.File.Name;
82+
text += ws._package.File?.Name ?? "";
8383
break;
8484
case ExcelHeaderFooterFormattingCodes.NumberOfPages:
8585
text += "000";
@@ -93,7 +93,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P
9393
text += DateTime.Now.ToString("HH:mm");
9494
break;
9595
case ExcelHeaderFooterFormattingCodes.FilePath:
96-
text += ws._package.File.Directory.FullName + "\\";
96+
text += ws._package.File?.Directory != null ? ws._package.File.Directory.FullName + "\\" : "";
9797
break;
9898
default:
9999
text += hf.Text;

0 commit comments

Comments
 (0)