Back to Blog
critical SEVERITY9 min read

Critical Buffer Overflow in Windows USB HID: How One Byte Can Compromise Your System

A critical buffer overflow vulnerability was discovered and patched in the Windows USB HID host library, where four unsafe `memcpy` calls copied data using device-reported sizes without validating destination buffer capacity. The most dangerous instance could overflow a heap buffer by as little as one byte — enough to corrupt heap metadata and potentially allow arbitrary code execution. This post breaks down how the vulnerability works, why it matters, and how to write safer memory operations in

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

Answer Summary

This is a critical buffer overflow vulnerability (CWE-122) in C code within the Windows USB HID host library, caused by four unsafe `memcpy` calls that copied data using device-reported sizes without validating destination buffer capacity. The fix involves adding explicit bounds checking before each `memcpy` operation to ensure the source data size never exceeds the allocated destination buffer size, preventing heap corruption and potential arbitrary code execution.

Vulnerability at a Glance

cweCWE-122
fixAdd explicit size validation before each memcpy to ensure data fits in destination buffer
riskArbitrary code execution via heap metadata corruption
languageC
root causeUnsafe memcpy using device-reported sizes without bounds validation
vulnerabilityHeap-based Buffer Overflow

Severity: šŸ”“ Critical | CVE Type: Buffer Overflow (CWE-122) | Fixed In: Windows USB HID Host Library


Introduction

There's a saying in security circles: "It only takes one byte to ruin your day." That saying has never been more literal than in the vulnerability we're discussing today — a heap buffer overflow in the Windows USB HID (Human Interface Device) host library where a single off-by-one error in a memcpy call could corrupt heap metadata and open the door to arbitrary code execution.

This vulnerability was discovered in Win/lib/src/usb_hidhost_impl.cpp and affects code that processes data from USB HID devices — the same category of devices that includes keyboards, mice, gamepads, and countless specialty input devices. Because this code runs with elevated trust and interacts directly with hardware-reported data, the attack surface is significant.

If you're a developer who works with native C/C++ code, hardware interfaces, or low-level Windows APIs, this post is essential reading. Even if you don't, the lessons here apply broadly to any code that copies memory using externally-controlled size values.


The Vulnerability Explained

What Is a Heap Buffer Overflow?

A heap buffer overflow occurs when a program writes data beyond the boundaries of a buffer that was dynamically allocated on the heap. Unlike stack overflows (which famously overwrite return addresses), heap overflows corrupt adjacent heap memory — which often contains allocator metadata, other buffers, or object pointers.

Modern heap allocators like Windows' Low Fragmentation Heap (LFH) store bookkeeping information in structures adjacent to allocated blocks. Overwriting even a single byte of this metadata can cause the allocator to behave incorrectly on the next allocation or deallocation — a condition that skilled attackers can turn into reliable code execution primitives.

The Vulnerable Code

The vulnerability centered on four memcpy calls that used sizes derived from HID device-reported capabilities without first validating that the destination buffer was large enough to hold the data.

The two most critical instances:

Instance 1 — The Off-By-One at Line 318:

// VULNERABLE: vpTempBuf was allocated as `vCaps.FeatureReportByteLength` bytes
// Writing at offset +1 means we can overflow by at least 1 byte
memcpy(&vpTempBuf[1], pBuf, min(BufSize, vCaps.FeatureReportByteLength));

Here's the subtle but devastating problem: vpTempBuf is allocated with vCaps.FeatureReportByteLength bytes. The memcpy writes starting at vpTempBuf[1] — one byte into the buffer — but uses vCaps.FeatureReportByteLength as the maximum copy size. This means the write can extend to vpTempBuf[1 + FeatureReportByteLength - 1], which is one byte past the end of the allocated buffer.

Allocated buffer:  [0][1][2][3]...[N-1]
Write starts at:      [1]
Write ends at:           [2][3]...[N-1][N]  ← ONE BYTE PAST THE END
                                             ↑ HEAP CORRUPTION

Instance 2 — No Guard at All at Line 232:

// VULNERABLE: `len` comes from device-reported data, no bounds check whatsoever
memcpy(destBuf, srcBuf, len);

This instance is arguably worse: len is sourced directly from HID device capabilities (vTempBufSize) with no min() guard against the actual destination buffer size. An attacker controlling a malicious USB HID device could report an arbitrarily large len value and trigger a massive heap overflow.

Why Is This Exploitable?

The key detail that elevates this from a bug to a critical vulnerability is where the size values come from: the HID device itself.

HID devices report their capabilities (including buffer sizes like FeatureReportByteLength) through USB descriptors. A malicious USB device — or a legitimate device with manipulated firmware — can report whatever values it wants. This means:

  1. A rogue USB device plugged into a machine could report a FeatureReportByteLength larger than what the host actually allocates.
  2. The memcpy would then write beyond the buffer boundary.
  3. Heap metadata corruption could lead to a crash, or with careful crafting, to arbitrary code execution.

Real-World Attack Scenario

Imagine a malicious USB device disguised as a standard keyboard or game controller. When plugged in:

  1. The device reports a FeatureReportByteLength of, say, 512 bytes.
  2. The host allocates a buffer based on this value.
  3. The device then sends a feature report that triggers the vulnerable memcpy at line 318.
  4. Because of the +1 offset, the copy overflows by one byte into the adjacent heap chunk's metadata.
  5. On the next heap operation, the corrupted metadata causes a controlled write to an attacker-chosen address.
  6. Code execution is achieved — potentially at the privilege level of the process handling USB input.

This class of attack is known as a "BadUSB" style attack and has been demonstrated in real-world scenarios. Physical access to a USB port is the only prerequisite.


The Fix

What Changed

The fix addressed all four vulnerable memcpy calls in Win/lib/src/usb_hidhost_impl.cpp by implementing proper bounds validation before each copy operation.

The core principle of the fix:

Never trust externally-supplied size values. Always validate that the number of bytes to be copied does not exceed the capacity of the destination buffer — accounting for any offsets applied to the destination pointer.

Fixed Instance 1 — Accounting for the Offset:

// BEFORE (vulnerable):
memcpy(&vpTempBuf[1], pBuf, min(BufSize, vCaps.FeatureReportByteLength));

// AFTER (safe):
// The destination starts at offset 1, so available space is (bufferSize - 1)
size_t availableSpace = vCaps.FeatureReportByteLength - 1;
size_t copySize = min({BufSize, availableSpace, vCaps.FeatureReportByteLength - 1});
memcpy(&vpTempBuf[1], pBuf, copySize);

The critical insight: when your destination pointer is buffer + offset, your available space is bufferSize - offset, not bufferSize. The fix correctly subtracts the offset from the available space calculation.

Fixed Instance 2 — Adding the Missing Guard:

// BEFORE (vulnerable):
memcpy(destBuf, srcBuf, len);

// AFTER (safe):
size_t safeLen = min(len, destBufSize);
memcpy(destBuf, srcBuf, safeLen);

A min() guard ensures that no matter what value a device reports for len, the copy can never exceed the actual allocated buffer size.

The Broader Security Improvement

Beyond the individual fixes, this patch reinforces a critical security boundary: hardware-reported values must be treated as untrusted input. Just as web developers sanitize user input before using it in SQL queries, systems programmers must validate device-reported sizes before using them in memory operations.

This is especially important for USB and HID code because:
- USB devices can be emulated by software (e.g., USB/IP, virtual machines)
- Physical USB devices can have their firmware modified
- The attack requires no network access — just physical proximity


Conclusion

This vulnerability is a textbook example of why trusting external data is dangerous — and why the consequences can be severe even when the bug seems small. A single byte of overflow was enough to create a potential path to arbitrary code execution via heap metadata corruption.

The key takeaways from this fix:

  1. Treat hardware-reported values as untrusted input — just like you'd treat user-supplied data in a web application.
  2. Always account for pointer offsets when calculating available buffer space — &buf[1] has bufSize - 1 bytes available, not bufSize.
  3. Add explicit size guards to every memcpy that uses an externally-derived size.
  4. Use static analysis and fuzzing to catch these issues before they reach production.
  5. Prefer safe memory APIs (memcpy_s, bounded iterators) over raw memcpy where possible.

Memory safety bugs in hardware interface code are particularly dangerous because they often run with elevated privileges and interact with devices that can be controlled by attackers. As USB-based attacks become more sophisticated and accessible, hardening the code that processes USB data is not optional — it's essential.

The fix here was relatively straightforward once the vulnerability was identified: validate sizes, account for offsets, and never assume that a device is telling the truth about its capabilities. These are small changes that make an enormous difference in security posture.


This vulnerability was discovered and fixed by the OrbisAI Security automated scanning system. If you're interested in automated security scanning for your codebase, visit orbisappsec.com.


Further Reading:
- MSDN: HID Architecture
- CWE-122: Heap-based Buffer Overflow
- CERT C Coding Standard: MEM35-C
- BadUSB: On Accessories that Turn Evil
- Microsoft SDL: Banned Functions

Prevention and further reading

Related Articles

critical

Aardvark.Cef.Process.Core Shared Memory Handler: Unvalidated memcpy

The shared memory handler in Aardvark.Cef.Process.Core failed to validate that the `length` parameter passed from JavaScript did not exceed the destination buffer size before calling `memcpy`. This allowed a compromised Chromium renderer process to corrupt heap memory by supplying an oversized `handle->length` value to the `openMapping` function. The fix adds explicit bounds checking using `GetArrayBufferByteLength()` before the copy operation.

high

XShmGetImage Heap Corruption: Unvalidated Image Height in streamproxy

The `XShmGetImage` function in the X11 shared memory image path copies pixel data row-by-row using `memcpy` without validating that the source image height matches the destination buffer height. An attacker or compromised server could provide an oversized source image, causing writes beyond the allocated heap buffer and triggering heap corruption or code execution.

critical

SGX Enclave ecall_store_data memcpy Buffer Overflow in 256-Byte

The Intel SGX enclave's trusted bridge functions `ecall_store_data` and `ecall_retrieve_data` used `memcpy()` to move data into and out of a fixed 256-byte `secure_storage` buffer without validating that `data_len` fit within destination boundaries. An attacker providing oversized `data_len` values could corrupt enclave memory, breaking SGX's confidentiality guarantees.

critical

How Buffer Overflow via strcpy() Happens in C++ XML Parsers and How to Fix It

A critical buffer overflow vulnerability was discovered in `buildroot-external/package/libxmlparser/xmlParser.cpp`, where the `toXMLString` function used `_tcscpy()` to write XML escape sequences into a destination buffer without any bounds checking. An attacker supplying a crafted XML document could overflow the buffer and potentially execute arbitrary code. The fix replaces all five unsafe `_tcscpy()` calls with `memcpy()` calls that copy only the exact number of bytes required for each escape

critical

How Heap Buffer Overflows Happen in C++ ZIP Extraction and How to Fix Them

A critical heap buffer overflow vulnerability was discovered in `TKLiveSync/unzip.cpp`, where ZIP archive entry names were copied into a `PATH_MAX`-sized heap buffer using `strcpy()` without any length validation. Since the ZIP specification allows entry names up to 65,535 bytes — far exceeding typical `PATH_MAX` values of 1,024 to 4,096 bytes — a crafted archive could overflow the buffer and corrupt heap memory. The fix replaces the unsafe `strcpy`/`dirname` pattern with `std::string` operation

medium

How Integer Overflow happens in C++ image processing and how to fix it

A signed integer overflow in OpenCV's `bilateralFilter.cpp` allowed the buffer size calculation `cal_width * cal_height * cn` to wrap around to a small or negative value, causing `padding.resize()` to allocate far less memory than needed. Subsequent `memcpy` operations would then write beyond the allocated buffer, creating a heap corruption primitive. The fix is a single targeted cast to `size_t` that promotes the multiplication to unsigned 64-bit arithmetic before any overflow can occur.