A TCP server in C, from echo to an encrypted mailbox chat
Personal project · 2025
A personal C project: a TCP server built in four stages with POSIX sockets and pthreads, ending in a mailbox chat encrypted with AES-256-GCM.
In short
- What it is
- A TCP server in C built in four stages, from a single-client echo server to a multithreaded mailbox chat with aliases. In stage 4, every line between client and server is encrypted with AES-256-GCM through OpenSSL, under one pre-shared key.
- Why
- To practise POSIX sockets, concurrency with pthreads, linked lists with manual memory management, and OpenSSL's EVP API, as the repository README sets out.
- My role
- Personal project.
- Domains and tech
- Systems programming. C, POSIX sockets, pthreads, OpenSSL EVP (AES-256-GCM, RAND_bytes, Base64), Make.
- Status
- Personal project: works as a demo; one hardcoded shared key, no key exchange. Rebuilt and tested for this write-up on 19 October 2026, at commit 2c728a6: every stage builds without warnings and 24 of 24 checks pass, including tampered and oversize messages under AddressSanitizer. Design limits: one hardcoded key shared by everyone, and no replay protection.
- Period
- 2025
Context and problem
This is a systems-programming exercise. The repository README names what it practises: POSIX sockets, concurrency with pthread, memory management with linked lists, and a cryptographic pipeline built on OpenSSL. Each stage lives in its own folder, so the repository reads as a sequence in which every version adds one idea to the previous one.
The project dates from 2025. The first commit on GitHub, from March 2026, had two files that didn’t compile and a server that never used its encryption module. Two commits on 17 October 2026 fixed that, and this page describes the result, commit 2c728a6. The browser version of the same idea is AESChat.
Architecture
Every server sets up its socket the same way: an IPv6 TCP socket bound to all addresses with SO_REUSEADDR, a backlog of SOMAXCONN, port 4242 unless another is given on the command line, and SIGPIPE ignored so that a client disconnecting mid-write doesn’t kill the process. A Makefile builds every stage with -Wall -Wextra.
Stage 1 handles one client at a time: the accept loop calls the handler directly. Stage 2 starts one detached thread per client and keeps a client counter under a mutex. Stage 3 adds line commands, and its second file keeps connected clients in a doubly linked list. Stage 4 turns the command server into an encrypted mailbox chat.
Implementation
Threads and shared state
The main thread runs the accept loop and starts one pthread per client. In stage 4, a global mutex protects the client list, the counter and the aliases, and each mailbox has its own mutex, so a client reading its messages doesn’t block the others.
A line protocol
Each command is one line, accepted with or without a leading /, split with strtok_r, and answered with ok or fail (except list, which returns the names). Stage 4 adds three commands to echo, random, time, quit and list, and its list returns aliases instead of client IDs:
alias <name>: 1 to 8 letters or digits, set once per connection, unique regardless of case;send <alias> <text>: only for a client that has set its alias;recv: returns the oldest waiting message with its sender, or a bareokwhen there is none;
Each mailbox is a queue in memory, read in arrival order and freed when its owner disconnects. Three clients against the stage 4 server, shown decrypted (every line below travelled as AES-GCM ciphertext):
alice> alias alice ok
bob> /alias bob ok
carol> alias ALICE fail alias already exists
alice> send bob hello bob ok
bob> recv ok alice hello bob
bob> recv ok
alice> list alice bob
Test run of commit 2c728a6, 19 October 2026
The encryption module
crypto.h holds two functions. encrypt_msg refuses a plaintext over 1,024 bytes, checks that the output buffer is large enough, then draws a fresh 12-byte IV with RAND_bytes, encrypts with AES-256-GCM and appends the 16-byte tag. GCM depends on that fresh IV: reusing an IV with the same key reveals the XOR of the two plaintexts and lets an attacker forge tags.
v4_encrypted_chat/crypto.h, lines 42–58
// Generating random IV
if (RAND_bytes(iv, IV_LEN) != 1) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
memcpy(binary_buf, iv, IV_LEN); // Put IV at the start of binary_buf
// Encrypting
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, AES_KEY, iv);
EVP_EncryptUpdate(ctx, binary_buf + IV_LEN, &len, (unsigned char *)plaintext, (int)pt_len);
ciphertext_len = len;
EVP_EncryptFinal_ex(ctx, binary_buf + IV_LEN + len, &len);
ciphertext_len += len;
// Get the authentication tag and append it to the end
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, TAG_LEN, tag);
memcpy(binary_buf + IV_LEN + ciphertext_len, tag, TAG_LEN);
The binary block is then Base64-encoded and ends with a newline, so an encrypted message travels as one line, like a plaintext command.
decrypt_msg reverses the steps. It rejects empty input, invalid Base64, a block shorter than IV plus tag, and a plaintext that wouldn’t fit the caller’s buffer. It sets the expected tag before EVP_DecryptFinal_ex and returns -1 when the check fails. The server answers any line that doesn’t decrypt with an encrypted fail decryption error, and encrypts every reply.
Security considerations
What the design gets right: authenticated encryption, a new random IV for each message with its return value checked, a tag check before any plaintext is used, and crypto buffers sized from one constant so a long message is refused instead of overflowing. That last point was the bug fixed on 17 October 2026: before it, a long enough line overflowed a stack buffer in the decryption path.
What it leaves out:
- One hardcoded key for everyone. The key is a constant in
crypto.h, the same for the server and every client, and public in the repository. The README says so and names the production fix: a per-session key from an ephemeral Diffie-Hellman exchange, and TLS with certificate checks. - The server reads everything. It decrypts each line to act on it. The encryption protects each client-to-server link, not the conversation between two users, and anyone with the key can read any client’s traffic.
- No replay protection. The same ciphertext sent twice is accepted twice; nothing tracks IVs or sequence numbers.
- No associated data. The README calls the scheme AEAD, which describes GCM, but no additional data is passed: nothing binds a message to its sender or its position.
- No user authentication. Any client can take any free alias.
Testing and validation
The repository has no tests. For this write-up, commit 2c728a6 was built in a scratch copy and tested from outside with a script on 19 October 2026 (Ubuntu 26.04, GCC 15.2, OpenSSL 3.5.5). The stage 4 server ran as a second build with AddressSanitizer and UndefinedBehaviorSanitizer.
| Check | Result |
|---|---|
make all, every stage and both clients | Builds with no warnings |
Stage 1, hello | Answers Message sent : hello |
| Stage 2, two clients connected at once | Both answered |
Stage 3, serverCom.c: echo, time, random, an unknown command, quit | Each answered as documented; quit answers ok quitting |
Stage 3, serverComList.c: list with two clients connected | Returns two client IDs |
| Stage 4, alias, send, recv and list between two clients, over AES-GCM | Message delivered with its sender; duplicate alias refused |
| Stage 4, one bit of a ciphertext flipped | fail decryption error |
| Stage 4, a message encrypted under another key | fail decryption error |
| Stage 4, a 1,505-byte plaintext | Refused, no overflow |
| Stage 4, a line that isn’t Base64 | fail decryption error |
| Stage 4, the same ciphertext sent twice | Accepted twice (no replay protection) |
| The repository’s own stage 4 client against the server | Alias, echo and quit answered |
| Sanitizers over the whole stage 4 run (leak detection off) | No error reported |
24 of 24 checks passed. This shows the protocol and the crypto work as described on one machine; it doesn’t prove the absence of races, which a single scripted run can’t exercise.
Limitations
These come from reading the code; the first two were not triggered in the test run.
- A recipient can be freed during
send.search_clientreleases the list lock before returning the recipient, andsendthen writes into its mailbox. If the recipient disconnects in between, that write reaches freed memory. listcan overflow by one byte when the names fill its 1,024-byte reply buffer, because a newline is appended after the buffer is full. That needs on the order of a hundred connected clients.- Unchecked return values. The server doesn’t check what
encrypt_msgreturns, and insidecrypto.hthe encrypt and decrypt Init, Update and Final calls and the two tagctrlcalls aren’t checked, exceptEVP_DecryptFinal_ex. - Client IDs can repeat, because they come from the live client count.
- Non-thread-safe calls (
localtime,asctime,rand) run in worker threads. - The README overstates two things: plaintext lines “up to ~1.5 KB” (the code caps them at 1,024 bytes), and
quitorqfor “all” versions (stages 1 and 2 echo everything, and only the clients handleq).
Possible next steps
The README already names the fix for the key: a per-session key from a Diffie-Hellman exchange, then TLS. Before that, the send race needs the recipient to stay locked or reference-counted until the message is queued, and a sequence number inside the encrypted payload would stop replays. AESChat takes the same AES-256-GCM scheme to the browser, with a fresh key per chat room.