Capstone: Harden a Vulnerable Server
You're handed a deliberately vulnerable TCP echo server. Your job: find every bug, fix every bug. It compiles, it runs, and it's stuffed with the same flavours of mistake that have powered real-world breaches — buffer overflows, format string holes, integer overflows, race conditions, the lot.
The Vulnerable Server
Study this code carefully. There are at least 8 distinct vulnerabilities:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <pthread.h>#include <signal.h>
#define PORT 8080#define MAX_CLIENTS 100
int client_count = 0; // BUG 1: No synchronisation
struct client_info { int fd; char username[32];};
// BUG 2: Heap buffer overflow - no bounds checkvoid set_username(struct client_info *client, const char *name) { strcpy(client->username, name);}
// BUG 3: Format string vulnerabilityvoid log_message(const char *msg) { printf(msg); printf("\n");}
// BUG 4: Integer overflow in size calculationchar *create_response(const char *prefix, const char *data, size_t data_len) { size_t prefix_len = strlen(prefix); size_t total = prefix_len + data_len + 1; // Can overflow char *buf = malloc(total); if (!buf) return NULL; memcpy(buf, prefix, prefix_len); memcpy(buf + prefix_len, data, data_len); // Writes data_len bytes buf[prefix_len + data_len] = '\0'; return buf;}
void *handle_client(void *arg) { struct client_info *client = (struct client_info *)arg; char buffer[256];
// BUG 5: No check on client_count limit client_count++;
// Send welcome char welcome[512]; sprintf(welcome, "Welcome! You are client #%d\n", client_count); write(client->fd, welcome, strlen(welcome));
while (1) { // BUG 6: one read() treated as one complete command int n = read(client->fd, buffer, sizeof(buffer)); if (n <= 0) break; buffer[n] = '\0'; // BUG 7: Off-by-one if n == sizeof(buffer)
if (strncmp(buffer, "USER ", 5) == 0) { set_username(client, buffer + 5); char ack[300]; sprintf(ack, "Username set to: %s\n", client->username); write(client->fd, ack, strlen(ack)); } else if (strncmp(buffer, "MSG ", 4) == 0) { log_message(buffer + 4); // Logs with format string vuln write(client->fd, "Message logged\n", 15); } else { // Echo back write(client->fd, buffer, n); } }
close(client->fd); client_count--; // BUG 8: Race condition on decrement free(client); return NULL;}
int main() { int server_fd = socket(AF_INET, SOCK_STREAM, 0); // BUG: No check on socket() return value
struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(PORT), .sin_addr.s_addr = INADDR_ANY, };
bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)); listen(server_fd, 10);
printf("Server listening on port %d\n", PORT);
while (1) { struct client_info *client = malloc(sizeof(*client)); client->fd = accept(server_fd, NULL, NULL);
pthread_t thread; pthread_create(&thread, NULL, handle_client, client); pthread_detach(thread); }
return 0;}Vulnerability Analysis
Try to find all eight yourself before reading on. Then go through them one by one.
BUG 1: Unsynchronized global counter — client_count gets touched by multiple threads with no mutex in sight. Classic data race, undefined behaviour, counts that drift.
BUG 2: Heap overflow in set_username — strcpy will copy as much as you send into a 32-byte buffer. client_info comes from malloc, and username is its last member, so a client sending USER plus 100 characters runs straight off the end of the heap chunk. It tramples the allocator's metadata and whatever object sits next door, which is the raw material for classic heap exploits. (fd comes before username, so it survives.)
BUG 3: Format string vulnerability — printf(msg) happily reads user input as a format string. %x%x%x%x leaks stack data; %n writes to memory.
BUG 4: Integer overflow — prefix_len + data_len + 1 rolls over if data_len flirts with SIZE_MAX. You get a tiny total, then the second memcpy writes data_len bytes into it: a heap overflow.
BUG 5: No client limit — without checking client_count, an attacker opens thousands of connections and watches the server choke on file descriptors and memory.
BUG 6: No message framing — TCP is a byte stream, so one read can return half of USER alice or two commands glued together, and the server misparses both. (Storing the ssize_t result in an int is harmless here, since n is at most 256, but it's a bad habit for large reads.)
BUG 7: Off-by-one — when read fills the whole buffer (n == sizeof(buffer)), buffer[n] = '\0' writes one byte past the end.
BUG 8: Race condition on decrement — same flavour as BUG 1: client_count-- isn't atomic.
The Hardened Version
Here is how to fix each vulnerability:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <pthread.h>#include <signal.h>#include <stdatomic.h>#include <stdint.h>#include <errno.h>
#define PORT 8080#define MAX_CLIENTS 100#define MAX_USERNAME 31 // +1 for null terminator
// FIX 1 & 8: Use atomic counterstatic atomic_int client_count = 0;
struct client_info { int fd; char username[MAX_USERNAME + 1];};
// FIX 2: Bounded string copyvoid set_username(struct client_info *client, const char *name) { snprintf(client->username, sizeof(client->username), "%s", name); // Remove newline if present char *nl = strchr(client->username, '\n'); if (nl) *nl = '\0';}
// FIX 3: Never use user input as format stringvoid log_message(const char *msg) { printf("%s\n", msg);}
// FIX 4: Safe size calculation with overflow checkchar *create_response(const char *prefix, const char *data, size_t data_len) { size_t prefix_len = strlen(prefix); if (data_len > SIZE_MAX - prefix_len - 1) { return NULL; // Would overflow } size_t total = prefix_len + data_len + 1; char *buf = malloc(total); if (!buf) return NULL; memcpy(buf, prefix, prefix_len); memcpy(buf + prefix_len, data, data_len); buf[prefix_len + data_len] = '\0'; return buf;}
void *handle_client(void *arg) { struct client_info *client = (struct client_info *)arg; char buffer[256];
// FIX 5: Enforce client limit int current = atomic_fetch_add(&client_count, 1); if (current >= MAX_CLIENTS) { const char *msg = "Server full, try again later\n"; write(client->fd, msg, strlen(msg)); close(client->fd); atomic_fetch_sub(&client_count, 1); free(client); return NULL; }
char welcome[64]; snprintf(welcome, sizeof(welcome), "Welcome! You are client #%d\n", current + 1); write(client->fd, welcome, strlen(welcome));
while (1) { // FIX 6 & 7: Proper read handling with bounds ssize_t n = read(client->fd, buffer, sizeof(buffer) - 1); if (n <= 0) break; buffer[n] = '\0';
if (strncmp(buffer, "USER ", 5) == 0) { set_username(client, buffer + 5); char ack[128]; snprintf(ack, sizeof(ack), "Username set to: %s\n", client->username); write(client->fd, ack, strlen(ack)); } else if (strncmp(buffer, "MSG ", 4) == 0) { log_message(buffer + 4); write(client->fd, "Message logged\n", 15); } else { write(client->fd, buffer, n); } }
close(client->fd); atomic_fetch_sub(&client_count, 1); free(client); return NULL;}
int main() { // Ignore SIGPIPE to prevent crashes on broken connections signal(SIGPIPE, SIG_IGN);
int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { perror("socket"); return 1; }
int opt = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(PORT), .sin_addr.s_addr = INADDR_ANY, };
if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; }
if (listen(server_fd, 10) < 0) { perror("listen"); return 1; }
printf("Server listening on port %d\n", PORT);
while (1) { struct client_info *client = malloc(sizeof(*client)); if (!client) { fprintf(stderr, "Out of memory\n"); continue; }
client->fd = accept(server_fd, NULL, NULL); if (client->fd < 0) { perror("accept"); free(client); continue; }
client->username[0] = '\0';
pthread_t thread; if (pthread_create(&thread, NULL, handle_client, client) != 0) { perror("pthread_create"); close(client->fd); free(client); continue; } pthread_detach(thread); }
close(server_fd); return 0;}Key Takeaways
- Every
strcpyis an overflow waiting to happen. Reach forsnprintf. - Every
printf(user_data)is a format string attack. Alwaysprintf("%s", user_data). - Every size arithmetic can overflow. Check before you compute.
- Every shared variable needs synchronisation. Atomics or mutexes — pick one.
- Every system call can fail. Check the return value.
- Every read needs bounds. Read into
sizeof(buf) - 1so the null terminator has somewhere to go.
Compile the hardened version with full protections:
gcc -Wall -Wextra -Werror \ -fstack-protector-strong \ -D_FORTIFY_SOURCE=2 \ -pie -fPIE \ -Wl,-z,relro,-z,now \ -pthread \ server.c -o serverSecurity isn't something you bolt on at the end. It lives in every line you write, or it doesn't live at all.