Engineer working on a laptop connected to a device test rig, surrounded by wiring harnesses and test hardware

Firmware vulnerabilities & fixes

How to fix memory corruption in embedded firmware

Last updated:

Memory corruption covers a family of weaknesses — out-of-bounds writes and reads (CWE-787, CWE-119/121/122), classic buffer overflow (CWE-120), use-after-free (CWE-416), integer overflow feeding an overflow (CWE-190), NULL pointer dereference (CWE-476) and type confusion (CWE-843) — where a program accesses memory outside what it was actually allocated. MITRE's CWE-787 page (read 2026-10-29) defines the core case plainly: the product "writes data past the end, or before the beginning, of the intended buffer." These are the bugs most likely to turn a crash into remote code execution, and CISA's joint statement with the FBI, NSA and international partners puts them at roughly 70% of Microsoft's CVEs and of the vulnerabilities identified in Google's Chromium project — the single largest weakness family most C/C++ embedded codebases carry.

Key takeaways

  • Very common, and it ranks high on both MITRE's list and CISA's list of exploited CVEs.
  • If the code only runs on the target, build the parser alone for the host.
  • Prefer a memory-safe language for new or rewritten code.
  • Synthetic example.

How common is memory corruption among exploited bugs?

Very common, and it ranks high on both MITRE's list and CISA's list of exploited CVEs. The 2025 CWE Top 25 places seven memory-safety weaknesses in its top 16, including CWE-476 NULL Pointer Dereference at 13. In CISA's KEV JSON feed (catalog version 2026.11.10, 1,779 entries), the same CWE IDs are tagged on hundreds of exploited CVEs. An entry can carry more than one CWE, so the KEV counts below overlap.

CWE Name 2025 Top 25 rank KEV entries tagged (2026.11.10)
CWE-787 Out-of-bounds Write 5 106
CWE-416 Use After Free 7 96
CWE-125 Out-of-bounds Read 8 17
CWE-120 Classic Buffer Overflow 11 12
CWE-121 Stack-based Buffer Overflow 14 12
CWE-122 Heap-based Buffer Overflow 16 33
CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer outside the 2025 list 88

For the joint government view, the December 2023 guide The Case for Memory Safe Roadmaps, from CISA, NSA, FBI and the Australian, Canadian, UK and New Zealand cyber agencies, calls memory safety vulnerabilities "the most prevalent type of disclosed software vulnerability." See the CWE Top 25 guide for how MITRE builds the ranking.

1. Detect

  • Run the firmware's parsers and protocol handlers (the code paths that touch network input: HTTP, MQTT, proprietary device protocols, file-format parsers for configuration or firmware images) through a fuzzer with AddressSanitizer or an equivalent memory-safety sanitizer enabled — this catches out-of-bounds access and use-after-free even on inputs that don't visibly crash the unsanitized build.
  • If the code only runs on the target, build the parser alone for the host. Most parsers take a buffer and a length, so a small harness compiled with libFuzzer (clang -g -O1 -fsanitize=fuzzer,address) can exercise them on a workstation. For drivers and kernel code on embedded Linux, the kernel's KASAN is "a dynamic memory safety error detector designed to find out-of-bounds and use-after-free bugs."
  • Run static analysis with CWE-787/120/416/190 rule coverage across the full C/C++ codebase, prioritising code that parses attacker-reachable input over internal-only utility code.
  • Audit every call to an unbounded copy or formatting function (strcpy, sprintf, gets, raw memcpy with an attacker-influenced length) for a missing or incorrect bounds check.
  • Check build flags: confirm stack canaries, FORTIFY_SOURCE//GS-equivalent hardening and ASLR/PIE are actually enabled in the shipped firmware image, not just the development build.

2. How do you fix it?

  1. Prefer a memory-safe language for new or rewritten codeMITRE's CWE-787 Requirements-phase mitigation is explicit: "use a language that does not allow this weakness to occur ... or provides constructs that make this weakness easier to avoid." For embedded teams, this usually means scoping new network-facing parsers in Rust or a similarly memory-safe language rather than C, even if the rest of the codebase stays C/C++. MITRE adds a caution: a language's interface to native code "may still be subject to overflows."
  2. Publish — and work from — a memory-safety planCISA's post on the urgent need for memory safety urges manufacturers to make eliminating memory safety vulnerabilities a top-level company goal and to publish a "memory safety roadmap", for example the date after which new products or components are built in a memory-safe language and plans to support memory-safety work in the open-source libraries in their supply chain.
  3. Where C/C++ must stay, use vetted libraries and bounded functionsReplace strcpy() with strncpy() (checking NULL-termination behaviour when source and destination sizes match) or an equivalent bounded API; use a vetted safe-string library (for example SafeStr or Microsoft's Strsafe.h) instead of hand-rolled buffer arithmetic.
  4. Validate every buffer size and length against specification before use, following MITRE's "accept known good" input-validation strategy, rather than relying only on pattern-matching for known-bad input. Check the length against both the destination size and the number of bytes actually received.
  5. Enable compiler and OS hardening in the shipped build: stack canaries, FORTIFY_SOURCE//GS, and ASLR/PIE. These do not fix the underlying bug, but they convert many exploitable overflows into a detected crash, raising the attacker's cost.
  6. For use-after-free specifically, null out freed pointers immediately after free()/delete, and consider a hardened allocator that detects use-after-free in test builds. MITRE's CWE-416 rates this as defense in depth: a later access becomes a NULL dereference, which can still crash but "will reduce or eliminate the risk of code execution."

Worked example: how do you fix a TLV parser overflow?

Synthetic example. The device, frame format and code are invented for illustration.

A hypothetical sensor gateway reads type-length-value records from a radio frame. The vulnerable version trusts the length byte:

struct rec { uint8_t type; uint8_t len; uint8_t value[32]; };

int parse_tlv(const uint8_t *buf, size_t buf_len, struct rec *out) {
    out->type = buf[0];
    out->len  = buf[1];
    memcpy(out->value, &buf[2], out->len);   /* len comes from the frame */
    return 2 + out->len;
}

There are three bugs here. It reads two header bytes without checking that buf_len is at least 2 (an out-of-bounds read, CWE-125). It copies up to 255 bytes into a 32-byte array (CWE-787). And it reads past the end of the received frame when the length byte is larger than what arrived. The fixed version checks all three before copying:

int parse_tlv(const uint8_t *buf, size_t buf_len, struct rec *out) {
    if (buf_len < 2)
        return -1;                          /* header present */
    uint8_t len = buf[1];
    if (len > sizeof out->value)
        return -1;                          /* fits the destination */
    if ((size_t)len > buf_len - 2)
        return -1;                          /* fits what was received */
    out->type = buf[0];
    out->len  = len;
    memcpy(out->value, &buf[2], len);
    return 2 + len;
}

The last check subtracts from buf_len only after confirming it is at least 2, so it cannot wrap around. Writing it as 2 + len > buf_len is safe here, but the same pattern with wider length fields is a common source of CWE-190 integer overflows. To keep the fix, wrap the parser in a fuzz target, the function libFuzzer calls with each generated input:

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    struct rec r;
    int n;
    while (size > 0 && (n = parse_tlv(data, size, &r)) > 0) {
        data += n;
        size -= (size_t)n;
    }
    return 0;
}

Built with AddressSanitizer, the original version reports a heap or stack overflow within seconds. The fixed version should run clean, and the crashing input goes into the regression corpus.

Which build flags should ship in an embedded Linux image?

The OpenSSF Compiler Options Hardening Guide is written for device makers among others, and lists the minimum GCC or Clang version for each option. The run-time options most relevant to memory corruption:

Option What it does (per OpenSSF) Note
-D_FORTIFY_SOURCE=3 Compile- and run-time checks for unsafe libc usage and buffer overflows GCC 12+; needs -O1 or higher and a libc that implements it
-fstack-protector-strong Run-time checks for stack-based buffer overflows Canary-based
-fstack-clash-protection Checks variable-size stack allocations GCC 8+
-Wl,-z,noexecstack Marks the stack non-executable Data execution prevention
-Wl,-z,relro -Wl,-z,now Makes load-time relocation entries read-only Startup cost
-fPIE -pie Position-independent executable, so ASLR can randomise it Some cost on 32-bit targets
-ftrivial-auto-var-init Initialises automatic variables that lack an initialiser GCC 12+
-mbranch-protection=standard Protection against ROP and JOP on AArch64 -fcf-protection=full on x86_64

OpenSSF also flags that binary size can be a concern on embedded systems, so measure image size and boot time with the options on. Then confirm the release image has them, not only the developer build.

What changes on a microcontroller or RTOS?

Without an MMU, there is often no ASLR and no separate process address space, so a single overflow can reach the whole system. The protections move to the RTOS and the memory protection unit. Zephyr is a useful reference because its documentation spells out the options and their limits:

  • Threads in user mode (CONFIG_USERSPACE) have stack overflows "always caught", because the memory protection hardware denies writes outside the stack.
  • CONFIG_HW_STACK_PROTECTION uses CPU features or MPU/MMU guard regions to catch overflows in supervisor mode, but Zephyr notes it "cannot guarantee against data corruption."
  • CONFIG_STACK_SENTINEL is a software-only check of a sentinel value, often detected well after the overflow happened.
  • CONFIG_STACK_CANARIES turns on GCC stack canaries.

On any RTOS, run network parsers in the least privileged context the platform offers. Treat a stack-guard fault as a security event to log and report, not only a reboot reason.

3. Verify

  • Re-run the fuzzer with sanitizer instrumentation against the patched code for a sustained period (not just the single original proof-of-concept input), since memory bugs often have multiple reachable variants in the same handler.
  • Confirm static-analysis findings for the relevant CWE(s) are resolved in the patched build, not merely suppressed by an inline annotation.
  • Keep every proof-of-concept and fuzzer-found crash input in a permanent regression corpus.
  • Inspect the shipped binaries, not the build scripts: check that the stack is marked non-executable, RELRO is present, executables are position-independent and the stack-protector symbols are linked in.

What are the common pitfalls?

  • Swapping strcpy for strncpy and stopping there. MITRE's CWE-120 warns that strncpy() may leave the string unterminated when sizes match, and that bounded functions are "still susceptible to calculation errors."
  • Checking the length against the destination but not the input. The TLV example above needs both.
  • Hardening only the development build. Toolchain defaults differ between SDKs, and vendor binary blobs bring their own flags.
  • Treating a canary abort as a fix. MITRE notes that with these mechanisms "the result is still a denial of service, since the typical response is to exit the application." On a safety-relevant device, a crash loop is its own incident.
  • Fuzzing without sanitizers. Many overflows corrupt memory silently and only crash later, far from the bug.
  • Fixing your fork but not the upstream library. If the bug is in a third-party component, report it upstream and track the fixed version in your SBOM.

4. Ship an update

Memory-corruption fixes are usually self-contained but should still go through your full secure-update path — signed image, integrity verification, rollback protection — since these bugs are frequently remotely triggerable with no authentication. See secure boot and the hardware root of trust for the chain that makes a signed update meaningful. Confirm with your firmware SBOM exactly which shipped product lines and versions share the vulnerable parser or library before scoping the release.

5. Disclose via PSIRT

Memory-corruption CVEs are routinely assigned a high CVSS score because they so often lead to remote code execution; prioritise disclosure and patch timelines accordingly, and check CISA KEV/FIRST EPSS exploitation signals for similar classes — see our KEV + EPSS prioritization guide. When you score the bug, note that the CVSS v4.0 specification counts the need to circumvent ASLR or data execution prevention under Attack Complexity: High, so the hardening you ship can legitimately appear in the vector; see CVSS v4.0 vs v3.1. Run the fix through your coordinated vulnerability disclosure process (see CVD process explained and, if you have no PSIRT today, PSIRT setup for a hardware company), and check the EU Cyber Resilience Act's 24-/72-hour reporting duty if there is evidence of active exploitation (CRA 24h/72h reporting).

What can SoftWSP check, and what needs code review?

SoftWSP extracts a firmware image into a CycloneDX SBOM, matches its components against NVD, CISA KEV, FIRST EPSS and CISA ICS advisories, and drafts a cited report for an engineer to review. That shows which published memory-corruption CVEs in open-source and third-party components (a TLS library, a DNS forwarder, the kernel) affect the image, ranked by exploitation evidence. It does not analyse your own code paths, find unbounded copies or fuzz your parsers; those steps stay with your engineers and the tools above. See device & firmware security.

This guide summarises public MITRE CWE, CISA, OpenSSF, Zephyr, LLVM and FIRST guidance; it is not a substitute for fuzzing, sanitizer-instrumented testing, or a full source-code review, and does not constitute legal advice.

Put this guide to work

Frequently asked questions

What counts as a memory-corruption weakness?

This guide covers the family of CWEs where a program writes or reads outside the bounds of the memory it was given: CWE-787 (Out-of-bounds Write), CWE-120 (Buffer Copy without Checking Size of Input, i.e. classic buffer overflow), CWE-119/121/122 (restriction-of-buffer, stack and heap overflow variants), CWE-416 (Use After Free), CWE-190 (Integer Overflow, which frequently triggers a downstream overflow), CWE-476 (NULL Pointer Dereference) and CWE-843 (Type Confusion). MITRE defines CWE-787 simply as the product "writes data past the end, or before the beginning, of the intended buffer"; CWE-120 is "the product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer." Both pages read as of 2026-10-29.

How common are memory-safety bugs, really?

CISA's post "The Urgent Need for Memory Safety in Software Products" (first published 20 September 2023, revised 6 December 2023) cites several vendors' own figures: Microsoft reported that "~70% of the vulnerabilities Microsoft assigns a CVE each year continue to be memory safety issues"; the Chromium project reports "around 70%" of its serious security bugs are memory safety problems; Mozilla found 32 of 34 critical/high severity bugs in one analysis were memory-related; and Google Project Zero attributed 39 of 58 (67%) of the zero-days it tracked in one year to memory corruption.

What is MITRE's top recommended fix?

CWE-787's own Requirements-phase mitigation is language selection: "use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid" — i.e. prefer a memory-safe language (Rust, Go, Java, C#) for new code, especially network-facing parsers, over C/C++. CISA's memory-safety statement asks manufacturers to go further and publish a memory-safety roadmap: a public timeline for transitioning to memory-safe languages and for memory-safety work across the supply chain, including open-source dependencies.

We cannot rewrite our C/C++ codebase overnight — what fixes exist short of that?

MITRE's CWE-787/120 mitigations, short of a language change, are: use a vetted library or framework that avoids the raw pointer-arithmetic pattern; replace unbounded copy functions with length-aware equivalents ("replace strcpy with strncpy", and double-check that `strncpy()` still NULL-terminates correctly, since it may not when the destination equals the source size); validate every buffer-allocation size against a specification before use (an "accept known good" strategy) rather than only hunting for malicious patterns; and compile with hardening flags — Microsoft's `/GS`, GCC/Fedora's `FORTIFY_SOURCE`, stack canaries (StackGuard/ProPolice) and ASLR/PIE — which do not remove the bug but raise the cost of exploiting it and can turn a silent corruption into a detected crash.

How do we verify a memory-safety fix actually holds?

Run the firmware's fuzzing harness (or add one, scoped to the fixed parser/handler) with sanitizer instrumentation (AddressSanitizer or an equivalent) enabled, which catches out-of-bounds and use-after-free access even when the program would otherwise appear to run correctly, then confirm no crash or sanitizer report on the original proof-of-concept input and keep that input in the fuzz corpus for regression.

Sources

  1. MITRE CWE-787: Out-of-bounds Write
  2. MITRE CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
  3. CISA (Bob Lord): The Urgent Need for Memory Safety in Software Products (20 September 2023, revised 6 December 2023)
  4. CISA, NSA, FBI, ASD's ACSC, CCCS, NCSC-UK, NCSC-NZ, CERT-NZ: The Case for Memory Safe Roadmaps (December 2023)
  5. MITRE CWE-416: Use After Free
  6. MITRE: 2025 CWE Top 25 Most Dangerous Software Weaknesses
  7. OpenSSF: Compiler Options Hardening Guide for C and C++
  8. Zephyr Project documentation: Fatal Errors (stack overflow detection)
  9. LLVM: libFuzzer, a library for coverage-guided fuzz testing
  10. Clang: AddressSanitizer
  11. Linux kernel documentation: Kernel Address Sanitizer (KASAN)
  12. FIRST: CVSS v4.0 Specification Document
  13. CISA Known Exploited Vulnerabilities catalog, JSON feed (cisagov/kev-data, catalog version 2026.11.10)
Was this guide helpful?

In this cluster