Remote Code Execution via Unsafe strcat/strncat Usage in C Standard Library

Critical Risk Memory Safety
cstrcatstrncatbuffer-overflowrcestring-functionsmemory-corruptionstack-overflow

What it is

A critical memory safety vulnerability where C code uses strcat or strncat functions without ensuring destination buffer size and remaining capacity, enabling buffer overflow attacks. These functions append strings without bounds checking, allowing attackers to write past buffer boundaries when the combined length of destination and source strings exceeds the allocated buffer size. This can lead to stack corruption, arbitrary code execution, denial of service, or complete system compromise.

#include <stdio.h>
#include <string.h>

// VULNERABLE: strcat without bounds checking
void build_path(const char* dir, const char* file) {
    char path[64] = "/home/user/";
    
    strcat(path, dir);   // BUFFER OVERFLOW!
    strcat(path, "/");
    strcat(path, file);  // BUFFER OVERFLOW!
    
    printf("Path: %s\n", path);
}
#include <stdio.h>
#include <string.h>

// SECURE: snprintf with size checking
void build_path(const char* dir, const char* file) {
    char path[64];
    
    int written = snprintf(path, sizeof(path), 
                          "/home/user/%s/%s", dir, file);
    
    if (written >= sizeof(path)) {
        printf("Error: Path too long\n");
        return;
    }
    
    printf("Path: %s\n", path);
}

💡 Why This Fix Works

The vulnerable code uses strcat() which doesn't check buffer bounds, allowing overflow. The secure version uses snprintf() which limits output to buffer size and returns the number of characters that would have been written, allowing overflow detection.

Why it happens

Using strcat to concatenate strings without verifying that the destination buffer has sufficient remaining space.

Root causes

Unbounded String Concatenation with strcat

Using strcat to concatenate strings without verifying that the destination buffer has sufficient remaining space.

Misused strncat with Incorrect Length Calculations

Using strncat with incorrect length parameters that don't account for the current destination string length or remaining buffer space.

Multiple Concatenations Without Size Tracking

Performing multiple string concatenations without tracking accumulated length and remaining buffer space.

Fixes

1

Replace strcat with strlcat

Use strlcat() which takes the total destination buffer size and prevents overflow (available on BSD systems).

2

Use snprintf for Safe String Building

Use snprintf() to safely construct strings with known maximum size.

3

Calculate Remaining Buffer Space

If using strncat, calculate remaining space as: buffer_size - strlen(dest) - 1.

Detect This Vulnerability in Your Code

Sourcery automatically identifies remote code execution via unsafe strcat/strncat usage in c standard library and many other security issues in your codebase.