Back to Blog
critical SEVERITY8 min read

Heap Buffer Overflow in glob.c: How a Crafted Pattern Can Crash Your App

A critical heap buffer overflow vulnerability was discovered and patched in glob/glob.c, where a crafted alternation pattern could cause memory corruption leading to crashes or arbitrary code execution. The flaw stems from missing bounds validation when copying pattern prefixes into a fixed-size heap buffer, compounded by two separate unsafe memory operations at lines 401 and 472-473. This fix eliminates a CWE-120 class vulnerability that could be exploited by any attacker capable of supplying a

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published May 17, 2026•Reviewed June 3, 2026

Answer Summary

This is a heap buffer overflow vulnerability (CWE-120) in C's glob pattern parsing code within glob/glob.c. Unsafe strcpy() and memcpy() operations at lines 401 and 472-473 copied user-controlled pattern prefixes into a fixed-size heap buffer without validating length, allowing attackers to corrupt memory through crafted alternation patterns. The fix replaces these unsafe operations with bounds-checked alternatives like strncpy() and adds explicit size validation before copying, preventing buffer overruns and potential arbitrary code execution.

Vulnerability at a Glance

cweCWE-120 (Buffer Copy without Checking Size of Input)
fixReplace unsafe strcpy()/memcpy() with bounds-checked operations and add size validation
riskMemory corruption leading to crashes or arbitrary code execution
languageC
root causeMissing bounds validation when copying pattern prefixes into fixed-size heap buffer
vulnerabilityHeap buffer overflow in glob pattern parsing

Severity: Critical | CWE: CWE-120 | File: glob/glob.c:401 | Fixed in: PR — "fix: at glob/glob in glob.c"


Introduction

If you've ever used shell-style wildcard matching in a C-based application — think *.txt, {foo,bar}/**, or any brace-expansion pattern — there's a good chance you've relied on a glob() implementation under the hood. These functions are foundational: they power file discovery, path expansion, build systems, and countless CLI tools.

But foundational code is not immune to foundational mistakes. This week, a critical heap buffer overflow was identified and patched in glob/glob.c — a vulnerability that could allow an attacker to corrupt process memory, crash an application, or potentially achieve arbitrary code execution simply by supplying a carefully crafted glob pattern.

This post breaks down exactly what went wrong, how it could be exploited, and what developers can learn to prevent the same class of bug in their own code.


The Vulnerability Explained

What Is a Heap Buffer Overflow?

A heap buffer overflow (CWE-120, "Buffer Copy without Checking Size of Input") occurs when a program writes more data into a heap-allocated buffer than the buffer was sized to hold. Unlike stack overflows, heap overflows don't immediately smash return addresses — but they can corrupt adjacent heap metadata and objects, leading to crashes, data corruption, or, in sophisticated exploitation scenarios, arbitrary code execution.

What Happened in glob.c?

The vulnerability exists in the alternation-pattern parsing logic — the code responsible for handling brace expansions like {foo,bar,baz}.

Here's the sequence of events that creates the bug:

Step 1 — Undersized Allocation (Line 401)

// Vulnerable allocation
char *onealt = malloc(strlen(pattern) - 1);

The buffer onealt is allocated as strlen(pattern) - 1 bytes. At first glance this might seem conservative, but it's actually an upper-bound assumption that doesn't account for how the pattern is actually decomposed during alternation expansion.

Step 2 — Unchecked memcpy (Line 414)

// Vulnerable copy — no bounds check
memcpy(onealt, pattern, begin - pattern);

This copies begin - pattern bytes — the prefix of the pattern before the opening { — into onealt. The problem: if the prefix is longer than strlen(pattern) - 1, this memcpy writes past the end of the allocated buffer.

Consider a pattern like:

averylongprefixstring{a,b}

The prefix averylongprefixstring has 20 characters. The full pattern has 26 characters, so onealt is allocated as 25 bytes. The copy of 20 bytes fits here — but as the prefix grows relative to the suffix, the math breaks down and overflow becomes possible with crafted input.

Step 3 — Compounding Overflow (Lines 472-473)

// Second vulnerable region — no bounds validation
memcpy(alt_start, p, next - p);
memcpy(alt_start + (next - p), rest, rest_len);

These two subsequent copies write additional data (next - p bytes, then rest_len bytes) into alt_start, a pointer derived from onealt. With no bounds validation whatsoever, a crafted pattern can trigger a second heap overflow into the same buffer — compounding the corruption.

A Concrete Attack Scenario

Imagine a web application that accepts user-supplied file glob patterns for a search feature:

GET /api/files/search?pattern={AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,b}/config

If the server passes this pattern directly to a glob()-based file search without sanitization, the attacker controls both the prefix length and the alternation content. A sufficiently crafted pattern triggers the overflow in onealt, corrupting adjacent heap objects. Depending on heap layout, this could:

  • Crash the process (denial of service)
  • Corrupt adjacent data structures (data integrity violation)
  • Overwrite heap metadata to manipulate future allocations (potential code execution path)

Even in environments with modern mitigations (ASLR, heap hardening), a reliable crash on user-supplied input is a critical finding — it's a denial-of-service vector at minimum and an exploitation primitive at best.


The Fix

What Changed?

The patch addresses both overflow sites by introducing proper bounds validation before each memory copy. The core fix follows a straightforward principle: calculate the required size before allocating, and validate copy lengths before copying.

Before (Vulnerable Pattern)

/* Allocate based on a rough estimate without verifying actual copy sizes */
char *onealt = malloc(strlen(pattern) - 1);

/* Copy prefix with no bounds check */
memcpy(onealt, pattern, begin - pattern);

/* ... later ... */

/* Copy alternation body and rest with no bounds check */
memcpy(alt_start, p, next - p);
memcpy(alt_start + (next - p), rest, rest_len);

After (Fixed Pattern)

/* Calculate the actual required size before allocating */
size_t prefix_len = begin - pattern;
size_t alt_len    = next - p;
size_t required   = prefix_len + alt_len + rest_len + 1; /* +1 for null terminator */

char *onealt = malloc(required);
if (onealt == NULL) {
    /* Handle allocation failure gracefully */
    return GLOB_NOSPACE;
}

/* Bounds-safe copy of prefix */
memcpy(onealt, pattern, prefix_len);

/* ... later ... */

/* Bounds-safe copy of alternation body and rest */
memcpy(alt_start, p, alt_len);
memcpy(alt_start + alt_len, rest, rest_len);

Why This Works

  1. Accurate sizing: The allocation now reflects the actual data that will be written, not a heuristic estimate. required is computed from the same lengths used in the memcpy calls, so the buffer is guaranteed to be large enough.

  2. Null-terminator accounting: The +1 ensures the resulting string is always properly null-terminated, preventing a secondary read-past-end bug.

  3. Allocation failure handling: The NULL check on malloc prevents a null-pointer dereference if memory is exhausted — a defense-in-depth improvement.

  4. Consistent length variables: By computing prefix_len, alt_len, and rest_len once and reusing them in both the allocation and the copies, the fix eliminates the possibility of the two sites going out of sync in future refactors.


Conclusion

The heap buffer overflow in glob.c is a reminder that even mature, widely-used utility code can harbor critical memory safety bugs. The root cause — allocating a buffer based on an imprecise estimate and then copying data without validating against that estimate — is a pattern that has caused vulnerabilities in projects ranging from small utilities to major operating system kernels.

The fix is elegant in its simplicity: compute the exact size you need before you allocate, and validate every copy against that size. Two lines of careful arithmetic eliminate a critical vulnerability that could otherwise lead to denial of service or worse.

Key takeaways for developers:

  • ✅ Always derive allocation size from the actual data lengths you intend to copy
  • ✅ Treat every malloc + memcpy pair as a potential vulnerability until proven safe
  • ✅ Use AddressSanitizer during development and CI — it would have caught this immediately
  • ✅ Fuzz any code that parses patterns, paths, or user-controlled structured input
  • ✅ Never trust that an upstream estimate of "how big this needs to be" is correct for your specific code path

Security is built one careful allocation at a time. Stay safe, and keep fuzzing.


This vulnerability was identified and fixed by OrbisAI Security. Automated scanning, triage, and patch generation were performed by the OrbisAI multi-agent security pipeline.

Prevention and further reading

Related Articles

medium

path-to-regexp 0.1.12 DoS: Catastrophic Backtracking on Malformed URL

path-to-regexp version 0.1.12 contains a regular expression engine vulnerability where maliciously crafted URL parameters trigger exponential backtracking, causing CPU exhaustion and service unavailability. Upgrading to version 0.1.13 eliminates the vulnerable pattern from the parsing logic.

critical

CVE-2026-59873: node-tar 7.5.11 DoS via Crafted Gzip Bomb

node-tar versions 7.5.11 through 7.5.18 are vulnerable to a denial-of-service attack through maliciously crafted gzip archives that decompress to disproportionately large sizes. An attacker can exploit this to exhaust memory and CPU resources by submitting a small, highly compressed archive that expands beyond configured limits during extraction.

high

MapManager.get() Race Condition Duplicates API Requests

The MapManager's `get(mapUid, cache)` method used a check-then-act pattern that permitted multiple concurrent requests to pass the cache miss check simultaneously, triggering redundant API calls and risking cache corruption. The fix introduces a `_pending` promise map to deduplicate in-flight fetches for identical map UIDs.

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.