Back to Blog
critical SEVERITY8 min read

Critical Buffer Overflow in ENC28J60 Ethernet Driver: How a Single memcpy Can Compromise Embedded Devices

A critical buffer overflow vulnerability was discovered in the ENC28J60 Ethernet driver, where incoming packet data was copied into a fixed-size buffer without validating the packet's self-reported length. On embedded systems lacking ASLR, this flaw could allow an attacker on the same network segment to craft a malicious Ethernet frame and achieve arbitrary code execution. The fix introduces proper bounds checking before the memcpy operation, closing a highly reliable attack vector on constraine

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

Answer Summary

This is a CWE-120 buffer overflow vulnerability in the C-based ENC28J60 Ethernet driver for embedded systems. An attacker on the local network segment could send a crafted Ethernet frame with a malicious length field, causing memcpy() to write beyond buffer boundaries and achieve arbitrary code execution on devices lacking ASLR. The fix introduces proper bounds checking before the memcpy operation, validating that the packet's self-reported length does not exceed the allocated buffer size.

Vulnerability at a Glance

cweCWE-120 (Buffer Copy without Checking Size of Input)
fixAdded bounds validation before memcpy() to ensure packet length ≤ buffer size
riskRemote code execution via malicious Ethernet frames on local network
languageC
root causeUnchecked memcpy() using attacker-controlled packet length field
vulnerabilityBuffer overflow in network packet processing

Severity: šŸ”“ Critical | CVE Type: Heap/Stack Buffer Overflow | Component: ENC28J60 lwIP Network Driver | Fixed In: PR — "fix: remove unsafe exec() in enc28j60_lwip.cpp"


Introduction

Embedded systems are everywhere — in your home router, your industrial controller, your smart thermostat, and countless IoT devices running on shoestring resources. These systems often run lean, purpose-built network stacks, and when a vulnerability appears in that networking layer, the consequences can be severe.

This post covers a critical buffer overflow vulnerability discovered in the ENC28J60 Ethernet driver (src/DeviceInterfaces/Network/Enc28j60/enc28j60_lwip.cpp), a widely used low-cost SPI-attached Ethernet controller popular in Arduino, STM32, and other embedded platforms. The flaw lies in how the driver handles incoming packet data — specifically, it trusts the packet's own length field without verifying that the data will actually fit in the destination buffer.

If you write firmware, embedded C/C++, or work with lwIP-based networking stacks, this vulnerability is a textbook example of why never trust network-supplied length values is one of the most important rules in embedded security.


The Vulnerability Explained

What Went Wrong

At its core, this is a classic heap/stack buffer overflow via unchecked memcpy. Here's the pattern that caused the problem:

// VULNERABLE CODE (simplified illustration)
uint8_t pTx[MAX_TX_BUFFER_SIZE];  // Fixed-size transmit buffer

void enc28j60_output(struct pbuf *pPBuf) {
    // ...
    memcpy(pTx, pPBuf->payload, pPBuf->len);  // āŒ No bounds check!
    // ...
}

The driver allocates a fixed-size transmit buffer (pTx) and then copies incoming packet payload data directly into it using pPBuf->len — the packet's self-reported length — as the number of bytes to copy. The critical mistake: there is no verification that pPBuf->len is less than or equal to the size of pTx.

Why Is This Dangerous?

On a general-purpose OS (Linux, Windows, macOS), modern mitigations like Address Space Layout Randomization (ASLR), stack canaries, and NX bits make buffer overflows harder to exploit reliably. But embedded systems running bare-metal firmware or a minimal RTOS typically have:

  • āŒ No ASLR
  • āŒ No stack canaries (unless explicitly enabled)
  • āŒ No memory protection units (MPU) in low-end MCUs
  • āŒ Deterministic memory layouts that are often publicly known

This makes a buffer overflow on an embedded device highly reliable and predictable. An attacker who knows the target platform can craft a payload that overwrites a specific return address or function pointer with near-certainty.

How Could It Be Exploited?

The attack requires the adversary to be on the same network segment as the target device (e.g., the same LAN, VLAN, or local Wi-Fi network). Here's what a realistic attack looks like:

Step-by-Step Attack Scenario

1. Attacker joins the same network segment as the target embedded device.

2. Attacker crafts a raw Ethernet frame:
   - Sets the EtherType/length field to a value LARGER than MAX_TX_BUFFER_SIZE
   - Fills the oversized payload with a carefully constructed ROP chain
     or shellcode payload

3. Attacker sends the frame directly (using raw sockets or a tool like Scapy).

4. The ENC28J60 driver receives the frame and calls enc28j60_output().

5. memcpy() copies MORE bytes than pTx can hold, overwriting adjacent memory.

6. On a device with a known, fixed memory layout, the overflow overwrites
   a return address or function pointer with the attacker's target address.

7. When the overwritten function returns or is called, execution redirects
   to attacker-controlled code.

8. Attacker achieves arbitrary code execution on the embedded device.

Using a tool like Scapy in Python, crafting such a frame is trivially simple:

# Example attack frame using Scapy (for educational purposes)
from scapy.all import *

# Craft an oversized Ethernet payload
target_mac = "AA:BB:CC:DD:EE:FF"
overflow_payload = b"A" * 2048  # Far exceeds typical TX buffer sizes

frame = Ether(dst=target_mac) / Raw(load=overflow_payload)
sendp(frame, iface="eth0")

Real-World Impact

Impact Category Description
Confidentiality Attacker can read device memory, extract secrets/keys
Integrity Firmware logic can be subverted or replaced
Availability Device crash, reboot loop, or permanent compromise
Lateral Movement Compromised device used as pivot point in OT/ICS networks

In industrial or critical infrastructure contexts, a compromised embedded network node can be catastrophic — from disrupting a production line to providing a foothold into an OT network.


The Fix

What Changed

The fix introduces explicit bounds checking before the memcpy call. The corrected code validates that the incoming packet length does not exceed the available buffer space before performing the copy operation.

// BEFORE (vulnerable)
void enc28j60_output(struct pbuf *pPBuf) {
    uint8_t pTx[MAX_TX_BUFFER_SIZE];

    // No length validation — trusts the packet's self-reported size
    memcpy(pTx, pPBuf->payload, pPBuf->len);

    enc28j60_send_packet(pTx, pPBuf->len);
}
// AFTER (fixed)
void enc28j60_output(struct pbuf *pPBuf) {
    uint8_t pTx[MAX_TX_BUFFER_SIZE];

    // āœ… Validate length before copying
    if (pPBuf->len > MAX_TX_BUFFER_SIZE) {
        // Log the anomaly and drop the packet
        ENC28J60_LOG_ERROR("Packet length %u exceeds TX buffer size %u, dropping.",
                           pPBuf->len, MAX_TX_BUFFER_SIZE);
        return;  // Safely discard oversized packet
    }

    memcpy(pTx, pPBuf->payload, pPBuf->len);
    enc28j60_send_packet(pTx, pPBuf->len);
}

Why This Fix Works

The fix applies the "validate before use" principle to all network-supplied length values:

  1. Explicit upper-bound check: pPBuf->len > MAX_TX_BUFFER_SIZE ensures the copy can never exceed the buffer's capacity.
  2. Fail-safe behavior: When an oversized packet is detected, the function returns early and drops the packet rather than attempting a partial copy or truncation that might introduce other bugs.
  3. Logging for observability: Recording the anomaly allows operators to detect active exploitation attempts or misconfigured senders.

Defense in Depth: Additional Hardening

Beyond the immediate fix, a defense-in-depth approach would layer additional protections:

// Even more robust version with multiple safeguards
void enc28j60_output(struct pbuf *pPBuf) {
    uint8_t pTx[MAX_TX_BUFFER_SIZE];

    // Guard 1: Null pointer check
    if (pPBuf == NULL || pPBuf->payload == NULL) {
        return;
    }

    // Guard 2: Zero-length sanity check
    if (pPBuf->len == 0) {
        return;
    }

    // Guard 3: Upper bound enforcement
    if (pPBuf->len > MAX_TX_BUFFER_SIZE) {
        ENC28J60_LOG_ERROR("Oversized packet dropped: %u bytes", pPBuf->len);
        return;
    }

    // Safe to copy
    memcpy(pTx, pPBuf->payload, pPBuf->len);
    enc28j60_send_packet(pTx, pPBuf->len);
}

Conclusion

This vulnerability is a stark reminder that the most dangerous bugs are often the simplest ones. A missing bounds check — just a handful of characters of code — turned a routine memcpy into a critical remote code execution vector on embedded devices that often lack the safety nets of modern operating systems.

Key Takeaways

āœ… Always validate network-supplied length values before using them in memory operations.

āœ… Embedded systems are high-value targets precisely because they lack modern OS-level mitigations like ASLR and stack canaries.

āœ… Defense in depth matters — combine input validation, compiler hardening, static analysis, and hardware protections.

āœ… Fail safely — when invalid input is detected, drop it and log it. Don't try to "make it work" with malformed data.

āœ… Integrate security scanning into CI/CD — tools like OrbisAI Security can catch these patterns automatically before they ship.

The fix here was straightforward, but finding it required recognizing the pattern of trusting externally-controlled data for memory operation sizes — a pattern that appears in countless forms across embedded codebases. Train yourself and your team to spot it, and you'll prevent an entire class of critical vulnerabilities.


This vulnerability was identified and fixed by the automated security pipeline at OrbisAI Security. Automated scanning + human review = faster, safer firmware.


Further Reading:
- lwIP Security Considerations
- Embedded Security Best Practices — ENISA
- ARM Cortex-M MPU Programming Guide
- CERT C Coding Standard

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 happens in C++ and how to fix it

A critical buffer overflow in `create_hex_string()` within `hmlangw.cpp` let an unconditional 16-iteration loop write past the bounds of a 100-byte `hex` buffer using unchecked `sprintf` calls. The fix replaces `sprintf` with `snprintf` and caps the loop iterations based on the actual destination buffer size, closing off a memory corruption path reachable from serial or network input.

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