Back to Blog
critical SEVERITY9 min read

Heap Buffer Overflow in NanoSVG: How a Crafted SVG File Could Lead to Code Execution

A critical heap buffer overflow vulnerability was discovered and patched in the NanoSVG SVG parsing library, where missing bounds checks on memcpy operations allowed attacker-controlled SVG data to overflow heap buffers. Without validation of gradient stop counts and attribute array indices, a specially crafted SVG file could trigger arbitrary code execution. The fix adds proper bounds checking before all memory copy operations, closing a dangerous attack vector present in any application that p

O
By Orbis AppSec
β€’Technically reviewed by Anupam Medirattaβ€’Published May 18, 2026β€’Reviewed June 3, 2026

Answer Summary

This is a heap buffer overflow vulnerability (CWE-122) in C's NanoSVG library where memcpy operations lacked bounds checking when parsing SVG gradient stops and attribute arrays. Attackers could supply crafted SVG files with excessive element counts to overflow heap buffers and potentially execute arbitrary code. The fix adds validation to ensure copy sizes don't exceed buffer capacities before any memcpy call, particularly when processing gradient stop counts and attribute array indices from untrusted SVG input.

Vulnerability at a Glance

cweCWE-122
fixAdd bounds checking to validate copy sizes against buffer capacities before memcpy calls
riskArbitrary code execution via malicious SVG files
languageC
root causeMissing bounds validation before memcpy operations on gradient stops and attribute arrays
vulnerabilityHeap Buffer Overflow

Heap Buffer Overflow in NanoSVG: How a Crafted SVG File Could Lead to Arbitrary Code Execution

Severity: πŸ”΄ Critical | File: 3rd/nanosvg.h | Fix: Bounds check before memcpy


Introduction

SVG files are everywhere. They power icons, illustrations, and user-uploaded graphics across millions of applications. Most developers treat them as harmless XML β€” after all, they're just vector graphics, right?

Wrong.

SVG parsers are complex pieces of software that interpret attacker-controlled data and translate it into memory structures. When that parsing logic skips a bounds check, the consequences can be catastrophic: heap corruption, memory disclosure, or full arbitrary code execution. That's exactly what was found β€” and fixed β€” in nanosvg.h, a popular single-header SVG parsing library widely embedded in C and C++ projects.

This post breaks down the vulnerability, explains how it could be exploited, and walks through the fix so you can understand not just what changed, but why it matters.


Background: What Is NanoSVG?

NanoSVG is a lightweight, single-header SVG parser written in C. Its appeal is simplicity β€” drop one header file into your project and you can parse SVG files. This convenience has made it a popular choice for game engines, GUI frameworks, and desktop applications.

The downside of that simplicity? Less code review, fewer eyes on edge cases, and a codebase that often gets vendored (copied directly into projects) and forgotten.


The Vulnerability Explained

The vulnerability is a heap buffer overflow β€” a class of memory safety bug where a program writes more data into a heap-allocated buffer than it was sized to hold. In NanoSVG's case, two distinct missing bounds checks were identified:

Issue 1: Unchecked Gradient Stop Count (Line 913)

When NanoSVG processes SVG gradient definitions, it copies gradient stop data using memcpy. The problematic pattern looks like this:

// VULNERABLE β€” no validation that nstops fits within allocated capacity
memcpy(grad->stops, stops, nstops * sizeof(NSVGgradientStop));

Here, nstops comes directly from parsing attacker-controlled SVG markup. If a crafted SVG declares more gradient stops than the destination buffer (grad->stops) was allocated to hold, the memcpy happily writes beyond the buffer's end β€” corrupting adjacent heap memory.

The allocation for grad->stops happens earlier with a fixed or estimated capacity. If the parser doesn't verify that nstops <= allocated_capacity before the copy, an attacker can supply an arbitrarily large number of stops.

Issue 2: Unbounded Attribute Stack Index (Line 766)

The second issue involves attrHead, an integer used as an array index into the attr attribute stack:

// VULNERABLE β€” attrHead not validated against array bounds
attr[attrHead].something = value;

The attr array has a fixed compile-time size. If deeply nested SVG elements push attrHead beyond that size, writes occur past the end of the array into adjacent heap memory. A crafted SVG with excessive nesting depth is all it takes.

How Could an Attacker Exploit This?

Let's walk through a realistic attack scenario:

Step 1 β€” Craft a malicious SVG

An attacker creates an SVG file containing a linear gradient with a fabricated stop count far exceeding any reasonable allocation:

<svg xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="evil">
      <!-- Parser tricks: metadata claims N stops, actual data overflows buffer -->
      <stop offset="0%" stop-color="red"/>
      <!-- ... hundreds more stops ... -->
    </linearGradient>
  </defs>
  <rect fill="url(#evil)" width="100" height="100"/>
</svg>

Step 2 β€” Trigger the parse

The attacker delivers this file to a victim application β€” perhaps through a file upload feature, a document import dialog, or even an image preview in a file manager.

Step 3 β€” Heap corruption

The unchecked memcpy writes past the allocated buffer. Depending on what lives adjacent in the heap, this can:

  • Corrupt heap metadata (enabling heap exploitation primitives)
  • Overwrite function pointers or vtables
  • Overwrite adjacent object fields to manipulate program logic

Step 4 β€” Code execution

With careful heap manipulation (heap feng shui), an attacker can turn the overflow into controlled writes, ultimately redirecting execution to attacker-supplied shellcode or ROP chains.

Real-World Impact

Any application that:
- Accepts SVG file uploads from users
- Renders SVG files from the filesystem or network
- Embeds NanoSVG as a vendored dependency

...is potentially vulnerable to remote or local code execution simply by processing a malicious SVG file. No authentication bypass required. No special privileges needed. Just a crafted file.

This is particularly dangerous in:
- Desktop applications that open user files (the attacker sends you an SVG)
- Web services with SVG upload features
- Game engines that load SVG assets
- Document editors that import SVG graphics


The Fix

The fix is conceptually straightforward: validate before you copy.

Gradient Stop Bounds Check

Before performing the memcpy for gradient stops, the patched code verifies that nstops does not exceed the allocated capacity of grad->stops:

// FIXED β€” validate nstops against allocated capacity before copy
if (nstops > grad->nstops) {
    // Handle error: too many stops, truncate or abort
    nstops = grad->nstops;
}
memcpy(grad->stops, stops, nstops * sizeof(NSVGgradientStop));

The key insight: the number of stops to copy must be bounded by what was actually allocated. If the parsed count exceeds capacity, the code either truncates to the safe maximum or returns an error β€” but it never writes beyond the buffer.

Attribute Stack Index Check

For the attribute stack overflow, the fix validates attrHead against the array's compile-time size before using it as an index:

// FIXED β€” check attrHead before indexing into attr array
#define NSVG_MAX_ATTR 128

if (attrHead >= NSVG_MAX_ATTR) {
    // SVG nesting too deep β€” handle gracefully
    return;
}
attr[attrHead].something = value;

By checking attrHead < NSVG_MAX_ATTR before every array access, deeply nested SVG elements cause a graceful parse failure rather than a heap overflow.

Why These Fixes Work

Both fixes follow the same principle: establish an invariant before a dangerous operation and enforce it. Instead of trusting that input-derived values are safe, the code now explicitly proves they are safe before using them.

This is the essence of defensive programming in C/C++: never assume attacker-controlled values are within expected ranges.


Lessons for Developers

This vulnerability illustrates several patterns that appear repeatedly in security research:

πŸ”΄ Complexity hides bugs. SVG is a complex format. The more states a parser must handle, the more edge cases exist, and the more likely that some path skips a safety check.

πŸ”΄ "It's just a file" is a dangerous assumption. Files are user input. Any file format parser must treat its input as potentially adversarial.

πŸ”΄ Single-header libraries accumulate technical debt. The convenience of dropping in a .h file comes with the responsibility of maintaining it β€” including security patches.

🟒 Bounds checking is cheap. The performance cost of an integer comparison before a memcpy is negligible. The security cost of skipping it can be catastrophic.

🟒 Defense in depth helps. Even if a bounds check is missed, ASan in CI, fuzzing, and exploit mitigations like ASLR reduce the likelihood and impact of exploitation.


Conclusion

The heap buffer overflow in nanosvg.h is a textbook example of why input validation is non-negotiable in C/C++ code that processes untrusted data. Two missing bounds checks β€” one on a gradient stop count, one on an attribute array index β€” created a critical code execution vulnerability reachable simply by opening a malicious SVG file.

The fix is elegant in its simplicity: check that values derived from input are within safe bounds before using them in memory operations. That's it. Two comparisons stand between a working SVG parser and a critical exploit.

As developers, the key takeaways are:

  1. Treat all parsed input as adversarial β€” especially in C/C++
  2. Validate lengths and indices before every memory operation
  3. Fuzz your parsers β€” they will find what code review misses
  4. Keep vendored dependencies updated and audited
  5. Enable compiler sanitizers in your development and CI pipelines

Security isn't about perfection β€” it's about building layers of protection so that when one layer fails, another catches the fall. Start with the basics: validate your inputs, check your bounds, and never trust a file just because it has a .svg extension.


This vulnerability was identified and patched as part of a proactive security audit. The fix has been verified by automated scanner re-scan and LLM-assisted code review.

Have questions about memory safety or SVG parsing security? Drop a comment below or reach out to the security team.


Further Reading:
- The Art of Software Security Assessment β€” Chapter on integer and buffer overflows
- Heap Exploitation Techniques β€” Understanding how heap overflows become exploits
- libFuzzer Tutorial β€” Getting started with coverage-guided fuzzing
- NanoSVG GitHub Repository β€” Upstream source

Prevention and further reading

Related Articles

critical

Lampa Desktop Auto-Update Heuristic Bypass: Execution of Unverified

Lampa Desktop's auto-update mechanism downloaded JavaScript and CSS from `raw.githubusercontent.com` using only heuristic validationβ€”file size thresholds and string pattern matchingβ€”that attackers could trivially satisfy. The fix introduces cryptographic integrity verification by cross-referencing Git blob hashes from the GitHub Contents API, ensuring downloaded code matches the repository's authoritative state before execution.

high

adm-zip 0.6.0 Preserves SUID Bits From ZIPs: CVE-2026-102282

The `adm-zip` dependency resolved to 0.6.0 in this project's dependency tree, a version affected by CVE-2026-102282: during extraction it applies the Unix permission bits stored in each ZIP entry's external file attributes verbatim, including the setuid (`04000`), setgid (`02000`), and sticky bits. An attacker who controls an archive passed to `extractAllTo()` or `extractEntryTo()` can therefore have the extractor create a setuid binary owned by whatever user the extraction process runs as. The

high

requestInput() Type Confusion: NaN and Object Bypass in JavaScript

The `requestInput()` utility function lacked validation on its `type` parameter and failed to handle `NaN` results from float conversions, creating a type confusion weakness. An attacker could supply malformed inputs that propagate unhandled `NaN` values or unexpected object types through the type system. The fix adds explicit guards against `NaN` type parameters and rejects non-primitive type values.

critical

No Rate Limit on /api/uploads/presign Enables DoS

The `/api/uploads/presign` endpoint accepted unlimited concurrent requests to generate storage presigned URLs, giving an attacker a free lever to exhaust storage-provider quotas and server resources. The fix adds an `express-rate-limit` middleware capping each client to 30 requests per minute on that route.

high

CVE-2026-54673: builder-util-runtime Leaks Auth Headers on Redirect

electron-updater and electron-builder rely on builder-util-runtime to fetch update manifests and artifacts over HTTP. A flaw in that shared HTTP executor allowed credential headers attached to the original update-feed request to be re-sent after a redirect, exposing them to any host the redirect pointed to. The project fixes this by upgrading builder-util-runtime to 9.7.0 and collapsing a duplicate, older copy of the package that electron-updater had pinned on its own.

high

image-size 1.2.1 DoS: Zero-Valued Dimensions in Image Buffer Parser

A high-severity denial-of-service vulnerability in image-size 1.2.1 allows attackers to crash Node.js services using malicious image buffers with zero-valued dimensions. The fix removes the vulnerable `queue` dependency and tightens dimension validation in version 2.0.3.