cybersecurity · intermediate · ~15 min · safe pentest lab

Fix a toy buffer overflow

Apply bounded-copy + early failure on overflow.

Challenge

You're given a vulnerable function that copies a string into a fixed-size buffer with no bounds check:

void render(const char *user_input, char *banner) {
    strcpy(banner, "Welcome, ");
    strcat(banner, user_input);
}

Rewrite as int render_safe(const char *user_input, char *banner, size_t banner_sz) that produces "Welcome, <input>", returning 0 on success or -1 on overflow (caller's buffer untouched on overflow except for guaranteed NUL termination).

Why this matters

Patching a deliberately vulnerable function teaches the diagnostic mindset: spot the unbounded write, audit the destination size, replace with a bounded equivalent. This is the daily work of security auditors.

Starter code

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

int render_safe(const char *user_input, char *banner, size_t banner_sz) {
    /* TODO */
    return -1;
}

Common mistakes

Replacing only the symptom (the obvious strcpy) without checking the rest of the function — overflows often come in pairs. Using strncpy (gotcha — doesn't NUL-terminate when source fits exactly).

Edge cases to handle

Maximum-length input. Empty input. Input containing NUL bytes (rare in text, common in binary).

Complexity

O(input length).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.