Back to Blog
critical SEVERITY9 min read

Buffer Overflow in C: How Unbounded strcpy() Calls Enable Code Execution

A critical buffer overflow vulnerability was discovered and patched in `src/dclock/clocktime.c`, where multiple unbounded `strcpy()` calls copied untrusted data into fixed-size buffers without any length validation. Left unpatched, these flaws could allow an attacker to overwrite stack memory and achieve arbitrary code execution — one of the most severe outcomes in software security. This post breaks down how the vulnerability works, how it was fixed, and what every C developer should know to pr

O
By Orbis AppSec
Published May 15, 2026Reviewed June 3, 2026

Answer Summary

This is a stack-based buffer overflow vulnerability (CWE-121) in C, found in `src/dclock/clocktime.c`. Multiple calls to `strcpy()` copied untrusted input into fixed-size stack buffers with no bounds checking, allowing an attacker to overwrite adjacent stack memory — including saved return addresses — and potentially achieve arbitrary code execution. The fix replaces each `strcpy()` call with a length-bounded alternative such as `strncpy()` or `strlcpy()`, enforcing a maximum copy length equal to the destination buffer size minus one, and ensuring the buffer is always null-terminated.

Vulnerability at a Glance

cweCWE-121
fixReplace strcpy() with bounded alternatives (strncpy/strlcpy) enforcing destination buffer size limits
riskArbitrary code execution via stack memory corruption
languageC
root causestrcpy() copies untrusted input into fixed-size stack buffers with no length validation
vulnerabilityStack-Based Buffer Overflow via unbounded strcpy()

Buffer Overflow in C: How Unbounded strcpy() Calls Enable Arbitrary Code Execution

Vulnerability ID: V-001 | Severity: 🔴 Critical | CWE: CWE-120 (Buffer Copy Without Checking Size of Input)


Introduction

Few vulnerability classes have as long and destructive a history as the buffer overflow. First weaponized in the Morris Worm of 1988, buffer overflows have been responsible for some of the most devastating exploits in computing history — from early worms to modern privilege escalation chains. Yet despite decades of awareness, they continue to appear in production codebases, particularly in C and C++ projects where memory management is entirely manual.

This post covers a critical buffer overflow vulnerability recently discovered and patched in src/dclock/clocktime.c (and related files), caused by the misuse of strcpy() — a function so dangerous that many modern security guidelines recommend banning it outright.

If you write C code, maintain legacy systems, or work anywhere near native code, this one is for you.


The Vulnerability Explained

What Is a Buffer Overflow?

A buffer overflow occurs when a program writes more data into a fixed-size memory region (a "buffer") than it was designed to hold. The excess data spills into adjacent memory, potentially overwriting critical data structures — including saved return addresses on the stack.

When an attacker controls the overflowing data, they can redirect program execution to arbitrary code. This is the essence of stack smashing, and it remains one of the most powerful exploitation primitives available.

The Vulnerable Code Pattern

The vulnerability was found across several files, all sharing the same root cause: unbounded calls to strcpy(). Here's what that looks like in practice:

// ❌ VULNERABLE: clocktime.c:68
// asctime() returns a 26-character string, but what if ds is smaller?
// Or what if a malformed time struct produces unexpected output?
char ds[20];
strcpy(ds, asctime(timeptr));  // No length check — classic overflow
// ❌ VULNERABLE: xfont.c:617
// Font family name received from X11 server — attacker-influenced!
char name[64];
strcpy(impl_->name, font_family_name);  // Trusting external input blindly
// ❌ VULNERABLE: xfont.c:668
// Font names from X11 server copied into fixed array
strcpy(r->names_[i], font_name);  // No bounds check on font_name length
// ❌ VULNERABLE: dface.c:151
// Date string copied without validation
char date[32];
strcpy(date.text, date_string);  // What if date_string is longer than 32 bytes?

The common thread: data from external sources (the X11 server, system time functions) is copied into fixed-size stack or heap buffers with no length validation whatsoever.

Why Is strcpy() So Dangerous?

The strcpy(dest, src) function copies bytes from src to dest until it encounters a null terminator (\0). It has no concept of the destination buffer's size. If src is longer than dest can hold, strcpy() happily writes past the end of the buffer.

Compare this to the safer alternative:

// strcpy has NO length parameter — it cannot protect you
char *strcpy(char *dest, const char *src);

// strncpy DOES have a length parameter — but has its own pitfalls
char *strncpy(char *dest, const char *src, size_t n);

// strlcpy is the modern, safe alternative (where available)
size_t strlcpy(char *dest, const char *src, size_t size);

How Could This Be Exploited?

Let's walk through a concrete attack scenario using the X11 font name vulnerability:

Attack Scenario: Malicious X11 Server

1. Attacker sets up a rogue X11 server (or performs a man-in-the-middle
   attack on an unencrypted X11 connection  X11 often runs without TLS).

2. When the vulnerable application requests font information, the rogue
   server responds with a crafted font family name:

   "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
   + [shellcode address] + [NOP sled] + [shellcode]

3. strcpy() dutifully copies this entire string into the 64-byte
   impl_->name buffer on the stack.

4. The excess bytes overwrite:
   - Local variables
   - The saved frame pointer (RBP)
   - The saved return address (RIP/EIP)

5. When the function returns, execution jumps to the attacker's
   chosen address  potentially into injected shellcode or a
   ROP (Return-Oriented Programming) chain.

6. The attacker now has arbitrary code execution in the context
   of the vulnerable process.

Real-World Impact

  • Arbitrary code execution with the privileges of the running process
  • Privilege escalation if the application runs as root or with elevated permissions
  • Remote exploitation if the X11 connection is network-accessible
  • Local exploitation via crafted font files or manipulated environment variables
  • Complete compromise of the host system in worst-case scenarios

The CVSS score for a remotely exploitable, unauthenticated buffer overflow enabling code execution is typically 9.0–10.0 (Critical) — the highest tier of severity.


The Fix

What Was Changed

The fix in src/dclock/clocktime.c (and the related files) replaces unsafe unbounded copy operations with length-aware alternatives that respect buffer boundaries.

The general pattern of the fix:

// ✅ FIXED: Use snprintf instead of strcpy for string formatting
// snprintf always null-terminates and never writes beyond n bytes
char ds[32];  // Also: ensure buffer is large enough for expected content
snprintf(ds, sizeof(ds), "%s", asctime(timeptr));
// ✅ FIXED: Use strlcpy or strncpy with explicit size for copies
// strlcpy(dest, src, dest_size) — safe, always null-terminates
strlcpy(impl_->name, font_family_name, sizeof(impl_->name));
// ✅ FIXED: Validate length before copying
size_t name_len = strlen(font_name);
if (name_len >= sizeof(r->names_[i])) {
    // Handle error: log, skip, or truncate safely
    fprintf(stderr, "Font name too long, skipping\n");
    continue;
}
strlcpy(r->names_[i], font_name, sizeof(r->names_[i]));
// ✅ FIXED: Bounds-checked date string copy
snprintf(date.text, sizeof(date.text), "%s", date_string);

Why These Fixes Work

Technique Why It's Safe
snprintf(buf, sizeof(buf), ...) Always null-terminates; never writes beyond sizeof(buf) bytes
strlcpy(dst, src, sizeof(dst)) Explicitly bounds-checked; returns total length for truncation detection
strncpy + manual null-term Works but error-prone; strlcpy is preferred
Explicit length validation Fail-fast before the copy even happens

The key insight: every write to a fixed-size buffer must be bounded by the size of that buffer, and the programmer must explicitly supply that size. C will not do this for you.


Prevention & Best Practices

1. Ban Dangerous Functions — Use a Blocklist

Many organizations maintain a list of banned C functions. At minimum, treat these with extreme caution:

 strcpy()    Use strlcpy() or snprintf() strcat()    Use strlcat() or snprintf() sprintf()   Use snprintf() gets()      Use fgets() scanf("%s")  Use scanf("%Ns") with explicit width

Microsoft's Security Development Lifecycle (SDL) and many CERT C guidelines explicitly prohibit these functions in security-sensitive code.

2. Always Use sizeof() — Not Magic Numbers

// ❌ BAD: Magic number — what if buffer size changes?
strncpy(buf, src, 64);

// ✅ GOOD: sizeof() always reflects the actual allocation
strncpy(buf, src, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';  // Ensure null termination

// ✅ BETTER: strlcpy handles null termination for you
strlcpy(buf, src, sizeof(buf));

3. Treat All External Input as Untrusted

Data from any external source must be validated before use:
- Network data (X11, sockets, HTTP)
- File contents
- Environment variables
- Command-line arguments
- IPC mechanisms

// Validate BEFORE copying
size_t input_len = strlen(external_input);
if (input_len >= BUFFER_SIZE) {
    log_error("Input exceeds maximum length: %zu >= %d", input_len, BUFFER_SIZE);
    return ERROR_INPUT_TOO_LONG;
}
strlcpy(buffer, external_input, BUFFER_SIZE);

4. Enable Compiler Protections

Modern compilers offer multiple layers of buffer overflow mitigation. Enable them all:

# Stack canaries — detect stack smashing at runtime
CFLAGS += -fstack-protector-strong

# Address Space Layout Randomization support
CFLAGS += -fpie
LDFLAGS += -pie

# Non-executable stack
LDFLAGS += -Wl,-z,noexecstack

# Fortify source — replaces unsafe calls with checked versions
CFLAGS += -D_FORTIFY_SOURCE=2 -O2

# Enable all warnings — many overflow risks are caught at compile time
CFLAGS += -Wall -Wextra -Wformat=2 -Wformat-overflow

5. Use Static Analysis Tools

Don't rely on code review alone. Integrate these tools into your CI/CD pipeline:

Tool Type What It Catches
Clang Static Analyzer Static Buffer overflows, use-after-free
Coverity Static Comprehensive C/C++ defects
cppcheck Static Buffer overflows, undefined behavior
AddressSanitizer (ASan) Dynamic Out-of-bounds reads/writes at runtime
Valgrind Dynamic Memory errors, leaks
CodeQL Semantic Data flow analysis, taint tracking
# Run AddressSanitizer during testing
gcc -fsanitize=address -fsanitize=undefined -g -o myapp myapp.c
./myapp  # ASan will catch overflows immediately

6. Consider Memory-Safe Languages for New Code

If you're starting a new project or have the opportunity to rewrite components, consider languages with built-in memory safety:

  • Rust: Zero-cost abstractions, no buffer overflows by design
  • Go: Garbage-collected, bounds-checked arrays/slices
  • C++: Use std::string, std::vector, std::span — avoid raw arrays

For existing C code, tools like Safe C Library or bounds-checking GCC can add a safety layer without a full rewrite.

7. Security Standards & References


Key Takeaways

┌─────────────────────────────────────────────────────────────┐
│  Buffer Overflow Prevention Checklist                       │
├─────────────────────────────────────────────────────────────┤
│  ✅ Never use strcpy(), strcat(), sprintf(), or gets()      │
│  ✅ Always bound copies with sizeof(destination)            │
│  ✅ Validate length of external input BEFORE copying        │
│  ✅ Enable -fstack-protector-strong and -D_FORTIFY_SOURCE=2 │
│  ✅ Run ASan/Valgrind in your test suite                    │
│  ✅ Integrate static analysis in CI/CD                      │
│  ✅ Treat ALL external data as potentially malicious        │
└─────────────────────────────────────────────────────────────┘

Conclusion

Buffer overflows caused by unbounded strcpy() calls are a textbook vulnerability — and yet they keep appearing in real codebases. The fix is straightforward: always know how much space you have, and never write more than that. Use snprintf(), strlcpy(), or explicit length validation. Enable compiler protections. Run dynamic analysis tools during testing.

The vulnerability patched here is a reminder that C is a powerful but unforgiving language. It gives you complete control over memory — and complete responsibility for getting it right. One missing bounds check can turn a routine string copy into a full system compromise.

Security is not a feature you add at the end. It's a discipline you practice from the first line of code.


This vulnerability was identified and patched by OrbisAI Security. Security fixes like this one are part of continuous security improvement — if you're not scanning your codebase regularly, you may have similar issues waiting to be discovered.

Have questions about buffer overflow mitigations or secure C coding practices? Drop them in the comments below.

Frequently Asked Questions

What is a buffer overflow in C?

A buffer overflow occurs when a program writes more data into a fixed-size memory buffer than it can hold, overwriting adjacent memory. In C, functions like strcpy() perform no bounds checking, making them especially dangerous when handling untrusted input.

How do you prevent buffer overflow in C?

Replace unbounded string functions like strcpy() and strcat() with length-bounded alternatives such as strncpy(), strlcpy(), or snprintf(). Always validate that input length does not exceed the destination buffer size minus one byte for the null terminator.

What CWE is buffer overflow?

Stack-based buffer overflows are classified as CWE-121 (Stack-based Buffer Overflow). The broader category of buffer copy without checking input size is CWE-120, and out-of-bounds writes more generally fall under CWE-787.

Is stack canaries enough to prevent buffer overflow exploitation?

Stack canaries detect some stack-smashing attacks at runtime, but they are a mitigation, not a prevention. A determined attacker may bypass canaries using information leaks or partial overwrites. The correct fix is to eliminate the unbounded copy at the source by using bounded string functions.

Can static analysis detect buffer overflow from strcpy()?

Yes. Static analysis tools such as Semgrep, Coverity, CodeQL, and clang-tidy can flag unsafe uses of strcpy() with tainted or unknown-length input. Orbis AppSec detected this specific vulnerability automatically by tracing data flow from untrusted sources into unbounded copy sinks.

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #34

Related Articles

critical

How buffer overflow happens in C tar header parsing and how to fix it

A critical buffer overflow vulnerability was discovered in `microtar/microtar.c` where the `raw_to_header()` and `header_to_raw()` functions used unbounded `strcpy()` and `sprintf()` calls to copy tar header fields. Malicious tar files with non-null-terminated name fields could overflow destination buffers, potentially leading to code execution. The fix replaces all unsafe string operations with bounded alternatives: `memcpy()` with explicit null-termination and `snprintf()` instead of `sprintf(

critical

How buffer overflow happens in C ieee80211_input() and how to fix it

A critical buffer overflow vulnerability was discovered in `src/firmware/src/net/ieee80211.c` at line 1584, where the `ieee80211_input()` function processed raw 802.11 data frames without verifying that the incoming frame was large enough to contain a valid `ieee80211_frame` header. An attacker within wireless range could craft undersized or malformed frames to trigger memory corruption, potentially leading to remote code execution on the firmware. The fix adds a single, targeted bounds check th

high

How buffer overflow from unsafe string copy functions happens in C network interface code and how to fix it

A high-severity buffer overflow vulnerability was discovered in `generic/eth-impl.c`, where unsafe `strncpy()` and `sprintf()` calls could write beyond buffer boundaries when handling network interface names and device filenames. The fix replaced these dangerous functions with bounded `snprintf()` calls that guarantee null-termination and prevent memory corruption.

critical

How buffer overflow in FuzzIxml.c sprintf() happens in C and how to fix it

A critical buffer overflow vulnerability was discovered in `fuzzer/FuzzIxml.c` where `sprintf()` wrote a PID-formatted filename into a fixed 256-byte stack buffer without any bounds checking. The fix replaces `sprintf()` with `snprintf()`, explicitly passing the buffer size to prevent any overflow. While exploitation in this specific fuzzer context requires local access, the pattern is a textbook example of CWE-120 that developers should recognize and eliminate everywhere it appears.

critical

How buffer overflow happens in C HTML parsing and how to fix it

A critical buffer overflow vulnerability in `include/html_parse.h` allowed attackers to overflow buffers by providing malicious HTML input exceeding buffer capacity. The fix adds proper bounds checking before memcpy() operations to prevent memory corruption and potential code execution.

critical

How buffer overflow in memcpy() happens in Node.js N-API bindings and how to fix it

A critical buffer overflow vulnerability was discovered in the GetBufferAsVector() function in examples_nodejs/src/zupt_napi.cpp, where memcpy() copied data from JavaScript Uint8Array buffers without proper bounds validation. This vulnerability could allow attackers to trigger memory corruption by providing maliciously crafted input arrays to the native Node.js module, potentially leading to crashes or arbitrary code execution.