Skip to content

Harden EPPlus.Fonts.OpenType against malformed fonts - #2634

Merged
AdrianEPPlus merged 3 commits into
develop9from
font-security-fixes
Dec 2, 2026
Merged

AdrianEPPlus merged 3 commits into
develop9from
font-security-fixes

Conversation

@swmal

@swmal swmal commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Harden EPPlus.Fonts.OpenType against malformed fonts

Summary

A security review of EPPlus.Fonts.OpenType found that a crafted or broken font file could crash the process, make it hang, or make it allocate memory and CPU out of all proportion to the size of the font. This PR fixes those issues in two rounds (two commits) and adds regression tests for each of them.

Fonts reach the library from three places: the font folders scanned on the machine, fonts passed in with OpenTypeFontEngine.GetFromBytes, and fonts embedded in exported documents. The fixes matter most where fonts can come from users or third parties, for example a server that generates PDF or SVG with customer fonts.

All findings are availability issues (denial of service) or robustness issues. Nothing found allows code execution or memory corruption, since the library is managed code.

Valid fonts behave as before. Each step was checked against about 600 real font faces: the test fonts, C:\Windows\Fonts and the user font folder. Where output changes, it is listed under Behavior changes below.

Commit 1: parsing (cmap, glyf, TTC, GSUB/GPOS)

Area Problem Fix
CmapSubtable12.GetGlyphMappings Overlapping or reversed groups, and code points up to 0xFFFFFFFF, made enumeration run billions of iterations (the uint loop could also wrap). long loop, clamped to U+10FFFF, overlapping groups skipped (first group wins), reversed groups skipped.
CmapSubtable4.GetGlyphMappings Overlapping segments were enumerated repeatedly. Segments start after the end of the previous one, matching MapCodePointToGlyph.
PairPosSubTableFormat2Deserializer Class1Count × Class2Count allocated a matrix of up to 4 billion records from a few bytes. The matrix size is checked against the remaining data before allocation; the subtable is dropped if it does not fit. ValueRecord.GetSize was added.
SinglePosSubTableFormat2Deserializer Same allocation pattern for ValueCount. Size check. ValueFormat 0 is kept as valid, since it is used by Yu Gothic.
glyf (GlyfTableLoader, glyph deserializers) Glyphs could read outside their own byte range and outside the table. Glyph bounds are checked against loca and the table length. Simple and composite glyph parsing stops at the glyph end. A broken glyph becomes an empty glyph.
DefaultFontFileReader.ExtractTtcFont Unchecked offsets and lengths in TTC collections. Bounds checks for the header, the directory, each table and the total size. Throws InvalidDataException.
GSUB/GPOS parsing Shared offsets let a small table make the parser read the same data over and over (gigabytes from kilobytes). Read budget in FontsBinaryReader: at most max(256 KB, 16 × table length). Real fonts read at most 10.4 × the table length (measured on 785 tables). If the budget is exceeded, the table is ignored and a warning is recorded.

Load warnings: a new FontLogEventType.FontTableIgnored value is logged through IFontLogger when a table is ignored. The warnings are also available internally as OpenTypeFont.LoadWarnings.

Commit 2: second review (parsing, subsetting, shaping, serialization)

Parsing

  • Stack overflow in GSUB subsetting: a chaining contextual lookup that references itself recursed until the process crashed, and a stack overflow cannot be caught. ChainingContextualHandler.Discover no longer recurses; the fixpoint loop in GsubSubsetProcessor already discovers the referenced lookups.
  • TableLoader hang: if loading a table threw an exception, every later Load() on that loader waited forever in Monitor.Wait. The in-progress flag is now cleared and waiting threads are woken.
  • Table directory validation: in both OpenTypeFont and the scanner (FontScannerV2Core), the directory must fit in the data, every table record must lie within the data, and duplicate tags are rejected. Before, the scanner could allocate a buffer of almost 2 GB from a forged name length.
  • MarkToBase: a subtable with MarkClassCount = 0 can never attach a mark, and it allocated up to 65535 empty records. It is now skipped.
  • LigatureSubst:
    • Before, the whole coverage table was expanded, which with overlapping format 2 ranges meant billions of glyphs. Now only as many glyphs as there are ligature sets are taken.
    • A glyph listed twice in the coverage no longer throws.
  • Read budget for cmap, kern and name, including NameTable.LoadFromBytes in the scanner. A kern table over budget is ignored with a warning. A font whose cmap or name table is over budget is rejected with InvalidDataException, since it cannot be used without them. Real fonts read at most 2 × the table length.

Subsetting

  • Infinite loop: BuildGlyphMapping used a ushort loop counter, and a GSUB substitution that pulled in all 65536 glyph IDs made it wrap around forever. Glyph IDs that do not exist in the font (≥ maxp.numGlyphs) are now removed before the mapping is built, and the counter is an int.
  • Class-based kerning (PairPos format 2): it was expanded into individual glyph pairs. That work grows with the subset size squared, and with a crafted font it could reach billions of pairs. Subtables over 64 KB were also written with wrapped 16-bit offsets: 150 of 995 real subtables were affected for large subsets. Format 2 is now kept:
    • The coverage table and both class definitions are remapped to the subset glyph IDs.
    • Unused classes are removed and the rest renumbered, with class 0 kept as 0.
    • Kerning for every glyph pair is identical to the original font (checked on 173 faces with class kerning).
    • Pairs of the same glyph (for example "TT") were dropped before and are kept now.
  • PairPosSubTableFormat2.Serialize wrote the header fields in the wrong order. The bug was latent, because only subsets serialize from objects and they never contained format 2 before.

Serialization

  • Lookup lists over 64 KB: subsetting unwraps Extension lookups, so large GSUB/GPOS subsets were written with wrapped 16-bit offsets. LookupListTable.Serialize now writes Extension lookups (GSUB type 7, GPOS type 9, with 32-bit offsets) when the 16-bit layout does not fit. Lists that fit are written byte for byte as before.

Shaping

  • Multiple Substitution: a single character could expand into up to 65535 glyphs. Sequences longer than 32 glyphs are now ignored during shaping (MultipleSubstitutionProcessor.MaxSequenceLength). Real fonts use at most 8.
  • Building the shaper: seven processors collected feature record × lookup index × subtable. A font that lists the same lookup many times, with many offsets to the same subtable, grew this quadratically: 386 MB at n = 4000, and about 20 GB at n = 30 000. Every glyph pair also iterated the whole list. The new ShapingLimits.MaxSubtableReferences = 65536 bounds the references examined. Real fonts have at most 9938 (Gabriola).

Behavior changes

  • New enum value: FontLogEventType.FontTableIgnored (in EPPlus.Interfaces).
  • Rejected fonts: malformed fonts that were accepted before can now be rejected with InvalidDataException. This applies to a table directory outside the data, a duplicate table tag, a malformed TTC, and cmap or name over the read budget. The scanner skips such files.
  • Ignored tables: a malformed GSUB, GPOS or kern table can be ignored, with a FontTableIgnored warning.
  • Subset fonts:
    • Class kerning stays format 2, and same-glyph pairs are kept.
    • Large subsets get Extension lookups.
    • Glyph IDs outside the font are no longer included.
    • Subsets of real fonts are otherwise byte-identical. The only changed subsets are the ones that were broken before.
  • Shaping of real fonts: unchanged, verified on 598 faces with three sample texts.

Tests

The new test classes are listed below. Each was also run against the code before the fix, and fails there as expected.

  • Commit 1:
    • CmapSubtable12Tests
    • CmapSubtable4Tests
    • PairPosSubTableFormat2DeserializerTests
    • SinglePosSubTableFormat2DeserializerTests
    • GlyfBoundsTests
    • DefaultFontFileReaderTests
    • LayoutTableReadBudgetTests
    • LayoutTableReadAmountTests
  • Commit 2:
    • GsubSubsetRecursionTests
    • TableLoaderFailureTests
    • TableDirectoryValidationTests
    • MarkToBaseSubTableFormat1DeserializerTests
    • LigatureSubstSubTableDeserializerTests
    • BasicTableReadBudgetTests
    • SubsetGlyphRangeTests
    • MultipleSubstitutionLimitTests
    • PairPosFormat2SubsettingTests
    • LayoutLookupOverflowTests
    • ShapingLookupReferenceLimitTests
    • The helper GsubTestFontBuilder.

The crafted fonts are built in the tests, by patching or extending Roboto-Regular.ttf and a few other test fonts, so no malicious font files are checked in.

Result: 705 tests passed and 12 were skipped. The library builds for all target frameworks with no new warnings.

Known remaining issues (not in this PR)

  • Medium: quadratic glyph closure in subsetting, unbounded font-name caches and kerning cache, the ThreadStatic ShaperCache keeping fonts alive, and the fsType check that can be bypassed with a self-declared family name.
  • Low:
    • mixed exception types reaching callers,
    • new ushort[-1] in LigatureTableDeserializer when the component count is 0,
    • the glyf coordinate loops,
    • CR/LF in font names in log output,
    • the font ID stored in a byte,
    • the TTC OffsetInFile in the scanner,
    • SinglePos format 2 device bits,
    • loca not bounded by the table length,
    • GposTable.Rewrite without a FeatureList,
    • the 2-second FontStore stall.
  • Correctness, not security: a single subtable over 64 KB in large subsets is still written with wrapped offsets. This affects Segoe Script, which needs shared PairSets, and Gabriola, which needs smaller class definitions. Segoe UI Variable kerning is also not preserved after serialization; that predates this PR and was not investigated.

@swmal swmal added this to the EPPlus 9.0 or later milestone Dec 1, 2026
@swmal swmal self-assigned this Dec 1, 2026
@swmal swmal added the enhancement New feature or request label Dec 1, 2026
@@ -24,6 +24,51 @@ public FontsBinaryReader(Stream input) : base(input)

private string _context;
private int _numberOfReadBytes = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GitHub säger:

The field 'FontsBinaryReader._numberOfReadBytes' is assigned but its value is never used

@AdrianEPPlus
AdrianEPPlus merged commit 137886e into develop9 Dec 2, 2026
3 checks passed
@github-project-automation github-project-automation Bot moved this to Pending Release in Epplus Enhancements Dec 2, 2026
@AdrianEPPlus
AdrianEPPlus deleted the font-security-fixes branch December 2, 2026 10:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

Status: Pending Release

Development

Successfully merging this pull request may close these issues.

2 participants