Ahmed Benlafqih

All projects

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.

Source code

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.

README.md, lines 3–5; git log

Architecture

Four server stages and the crypto moduleStage 1, serverEcho.c: one client at a time, echoes each read. Stage 2, serverMulti.c: one thread per client, client counter under a mutex. Stage 3, serverCom.c and serverComList.c: line commands echo, random, time and quit; serverComList.c adds a client list. Stage 4, serverMess.c: mailbox chat with alias, send, recv and list; it decrypts each incoming line and encrypts each reply with crypto.h. crypto.h holds AES-256-GCM and Base64 and is called by the stage 4 server and the stage 4 client. The root client.c is a plaintext client for stages 1 to 3.1v1_echo_server/serverEcho.cOne client at a time; echoes each read.2v2_multithreaded/serverMulti.cOne thread per client; client counterunder a mutex.3v3_command_parser/serverCom*.cLine commands: echo, random, time, quit.serverComList.c adds a client list.4v4_encrypted_chat/serverMess.cMailbox chat: alias, send, recv, list.Decrypts each line, encrypts each reply.both call itcrypto.hAES-256-GCM, Base64v4 client.cEncrypts each line,decrypts each reply
The four stages in order. The stage 4 server and the stage 4 client both call crypto.h: every line on that link is encrypted. The client at the repository root is a plaintext client for stages 1 to 3.Drawn from the code at commit 2c728a6

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 bare ok when 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.

Layout of an encrypted messageencrypt_msg builds a 12-byte random IV, then the ciphertext, which is as long as the plaintext, then the 16-byte GCM tag. The whole block is Base64-encoded with EVP_EncodeBlock and followed by a newline, so it travels as one line of text.IV12 bytesciphertextsame length as the plaintexttag16 bytesEVP_EncodeBlock (Base64)Base64 text + "\n"one line of the text protocol
What encrypt_msg sends: IV, then ciphertext, then tag, encoded as one line of Base64. GCM adds no padding, so the ciphertext is as long as the plaintext.v4_encrypted_chat/crypto.h, lines 10–18 and 42–65

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.

Build and test of commit 2c728a6, 19 October 2026
CheckResult
make all, every stage and both clientsBuilds with no warnings
Stage 1, helloAnswers Message sent : hello
Stage 2, two clients connected at onceBoth answered
Stage 3, serverCom.c: echo, time, random, an unknown command, quitEach answered as documented; quit answers ok quitting
Stage 3, serverComList.c: list with two clients connectedReturns two client IDs
Stage 4, alias, send, recv and list between two clients, over AES-GCMMessage delivered with its sender; duplicate alias refused
Stage 4, one bit of a ciphertext flippedfail decryption error
Stage 4, a message encrypted under another keyfail decryption error
Stage 4, a 1,505-byte plaintextRefused, no overflow
Stage 4, a line that isn’t Base64fail decryption error
Stage 4, the same ciphertext sent twiceAccepted twice (no replay protection)
The repository’s own stage 4 client against the serverAlias, 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_client releases the list lock before returning the recipient, and send then writes into its mailbox. If the recipient disconnects in between, that write reaches freed memory.
  • list can 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_msg returns, and inside crypto.h the encrypt and decrypt Init, Update and Final calls and the two tag ctrl calls aren’t checked, except EVP_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 quit or q for “all” versions (stages 1 and 2 echo everything, and only the clients handle q).

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.