From 9e1d304cac5367c3dbb1ca14700736680bd3a804 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Wed, 11 Nov 2026 08:31:06 +0300 Subject: publish --- 05/.gitignore | 2 + 05/build.sh | 46 ++++ 05/genkey.sh | 18 ++ 05/src/client.c | 684 +++++++++++++++++++++++++++++++++++++++++++++++++ 05/src/common.c | 39 +++ 05/src/common.h | 40 +++ 05/src/crypto.c | 239 +++++++++++++++++ 05/src/crypto.h | 37 +++ 05/src/dynamic-array.h | 68 +++++ 05/src/gcm.c | 143 +++++++++++ 05/src/server.c | 539 ++++++++++++++++++++++++++++++++++++++ 05/src/utils.h | 90 +++++++ 12 files changed, 1945 insertions(+) create mode 100644 05/.gitignore create mode 100755 05/build.sh create mode 100755 05/genkey.sh create mode 100644 05/src/client.c create mode 100644 05/src/common.c create mode 100644 05/src/common.h create mode 100644 05/src/crypto.c create mode 100644 05/src/crypto.h create mode 100644 05/src/dynamic-array.h create mode 100644 05/src/gcm.c create mode 100644 05/src/server.c create mode 100644 05/src/utils.h (limited to '05') diff --git a/05/.gitignore b/05/.gitignore new file mode 100644 index 0000000..3d33a15 --- /dev/null +++ b/05/.gitignore @@ -0,0 +1,2 @@ +/client +/server diff --git a/05/build.sh b/05/build.sh new file mode 100755 index 0000000..db75cb9 --- /dev/null +++ b/05/build.sh @@ -0,0 +1,46 @@ +#!/bin/sh +## build.sh +# +# Copyright (C) 2026 by Martin Michalec +# +# SPDX-License-Identifier: MIT +# +## Commentary: +# +## Code: + +ROOT="$(dirname "$0")" + +CC=cc + +CFLAGS="$CFLAGS -std=gnu99" +CFLAGS="$CFLAGS -ggdb3" +# CFLAGS="$CFLAGS -O3 -march=native" +# CFLAGS="$CFLAGS -DNDEBUG" +CFLAGS="$CFLAGS -Wall -Wextra" +CFLAGS="$CFLAGS -Wno-unused-function" +CFLAGS="$CFLAGS -Wno-unused-variable" +CFLAGS="$CFLAGS -Wno-unused-parameter" +CFLAGS="$CFLAGS -Wno-unused-but-set-variable" +CFLAGS="$CFLAGS -Wno-parentheses" +CFLAGS="$CFLAGS -Wno-unused-label" +CFLAGS="$CFLAGS -Wno-comment" +CFLAGS="$CFLAGS -Wno-stringop-overflow" +CFLAGS="$CFLAGS -I$ROOT/src/" + +set -xeu + +$CC $CFLAGS -o $ROOT/src/crypto.o -c \ + $ROOT/src/crypto.c +$CC $CFLAGS -o $ROOT/src/common.o -c \ + $ROOT/src/common.c + +$CC $CFLAGS -lcrypto -o $ROOT/server \ + $ROOT/src/crypto.o \ + $ROOT/src/common.o \ + $ROOT/src/server.c + +$CC $CFLAGS -lcrypto -lncurses -o $ROOT/client \ + $ROOT/src/crypto.o \ + $ROOT/src/common.o \ + $ROOT/src/client.c diff --git a/05/genkey.sh b/05/genkey.sh new file mode 100755 index 0000000..83ad3bb --- /dev/null +++ b/05/genkey.sh @@ -0,0 +1,18 @@ +#!/bin/sh +## genkey.sh --- generate pseudo-random AES-256 key +# +# Copyright (C) 2026 by Martin Michalec +# +# SPDX-License-Identifier: MIT +# +## Commentary: +# +## Code: + +set -xeu + +umask 077 + +openssl rand -hex 32 > aes-256.key + +# genkey.sh ends here diff --git a/05/src/client.c b/05/src/client.c new file mode 100644 index 0000000..ca3e368 --- /dev/null +++ b/05/src/client.c @@ -0,0 +1,684 @@ +// client.c --- client component +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LOG(PRIORITY, FMT, ...) \ + fprintf (stderr, FMT "\n" __VA_OPT__ (,) __VA_ARGS__) + +#include "utils.h" +#include "common.h" +#include "dynamic-array.h" +#include "crypto.h" + +static bool should_stop = false; + +static bool salt = false; +static bool check_integrity = false; +static bool bad_line = false; +static char *key_filename = NULL; +static enum key_kind key_kind = KK_PSK; +static aes_256_key key; + +static int epoll_fd; +static int server; + +enum color { + COLOR_NORMAL, + COLOR_WARNING, + COLOR_ERROR, +}; + +struct history_item { + char *message; + short color_pair; +}; + +static struct history { + struct history_item *items; + int count; + int capacity; +} history = {0}; + +static struct kill_ring { + char *items; + int count; + int capacity; + bool active; + bool killed; +} kill_ring = {0}; + +void +usage (FILE *stream, const char *progname) +{ + fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname); + fprintf (stream, "\n"); + fprintf (stream, "Options:\n"); + fprintf (stream, " -h, --help display this help message and exit\n"); + fprintf (stream, " -l, --login LOGIN use LOGIN instead of system login\n"); + fprintf (stream, " -p, --plain don't use encryption*\n"); + fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n"); + fprintf (stream, " -s, --salt add salt to encrypted messages*\n"); + fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n"); + fprintf (stream, " -c, --check-integrity use message integrity checking*\n"); + fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n"); + fprintf (stream, "\n"); + fprintf (stream, "Notes:\n"); + fprintf (stream, " Options marked with (*) must match the ones use by the server!\n"); + fprintf (stream, "\n"); +} + +void +send_plain (struct memory_view mv) +{ + uint8_t buffer[MAX_PACKET_SIZE]; + memcpy (buffer, mv.data, mv.size); + size_t size = mv.size; + if (check_integrity) { + uint8_t hash[SHA_DIGEST_SIZE]; + sha1_hash (hash, mv); + if (bad_line) { + for (int i = 0; i < SHA_DIGEST_SIZE; ++i) + hash[i] += i; + } + memcpy (&buffer[size], hash, sizeof (hash)); + size += sizeof (hash); + } + + again: + ssize_t bytes_written = write (server, buffer, size); + if (bytes_written == -1) { + switch (errno) { + case EAGAIN: goto again; + default: ERROR ("write: %s", strerror (errno)); + } + } + + if (bytes_written == 0) { + endwin (); + DIE ("Connection to server lost while sending message!"); + } + + if ((size_t) bytes_written != size) { + endwin (); + DIE ("Failed to write whole buffer"); + } +} + +void +send_encrypted (struct memory_view msg_mv) +{ + static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; + struct packet *packet = (void *) buffer; + struct memory_span packet_ms = { + .data = packet->data, + .size = MAX_PACKET_SIZE, + }; + ssize_t size = aes_256_cbc_encrypt (packet_ms, msg_mv, key, salt); + if (size == -1) { + endwin (); + DIE ("Failed to decrypt message"); + } + packet->size = size; + + struct memory_view packet_mv = { + .data = (void *) packet, + .size = sizeof (packet->size) + packet->size, + }; + return send_plain (packet_mv); +} + +void +send_message (const struct message *msg) +{ + struct history_item item = { + .message = malloc (msg->length + 1), + }; + memcpy (item.message, msg->data, msg->length); + item.message[(int) msg->length] = '\0'; + DYNAMIC_ARRAY_APPEND (history, item); + + if (key_kind == KK_NONE) { + struct memory_view mv = { + .data = (void *) msg, + .size = sizeof (msg->length) + msg->length, + }; + return send_plain (mv); + } else { + struct memory_view mv = { + .data = (void *) msg->data, + .size = msg->length, + }; + return send_encrypted (mv); + } +} + +void +send_shell_output (const struct message *orig, int base_msg_length) +{ + static char *line = NULL; + static size_t line_length = 0; + + struct message msg; + memcpy (msg.data, orig->data, base_msg_length); + + if (line_length < (size_t) orig->length - base_msg_length - 4 + 6) { + line_length = orig->length - base_msg_length - 4 + 6; + line = realloc (line, line_length); + } + memcpy (line, orig->data + base_msg_length + 4, + orig->length - base_msg_length - 4); + strcpy (line + orig->length - base_msg_length - 4, " 2>&1"); + + FILE *stream = popen (line, "r"); + ssize_t bytes_read; + while ((bytes_read = getline (&line, &line_length, stream)) != -1) { + ssize_t length = base_msg_length + bytes_read - 1; + msg.length = length > MAX_MESSAGE_LENGTH ? MAX_MESSAGE_LENGTH : length; + memcpy (&msg.data[base_msg_length], line, msg.length - base_msg_length); + send_message (&msg); + } pclose (stream); +} + +void +process_message (const struct message *msg, int base_msg_length) +{ + if (msg->length > base_msg_length && msg->data[base_msg_length] == '/') { + if (msg->length >= base_msg_length + 4 && + strncmp (&msg->data[base_msg_length], "/sh ", 4) == 0) { + send_shell_output (msg, base_msg_length); + return; + } + DYNAMIC_ARRAY_APPEND (history, ((struct history_item) { + .message = "error: No such command", + .color_pair = COLOR_ERROR, + })); + return; + } + + send_message (msg); +} + +void +receive_messages (void) +{ + static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; + struct packet *packet = (void *) buffer; + + again: + ssize_t bytes_read = read (server, packet, sizeof (*packet)); + if (bytes_read == -1) { + if (errno == EAGAIN) + return; + + endwin (); + DIE ("read: %s", strerror (errno)); + } + + if (bytes_read == 0) { + endwin (); + DIE ("Connection to server lost while receiving message!"); + } + + if (bytes_read != sizeof (*packet)) { + endwin (); + DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read); + DIE ("Received malformed message!"); + } + + bytes_read = read (server, packet->data, packet->size); + if (bytes_read == -1) { + if (errno == EAGAIN) + return; + + endwin (); + DIE ("read: %s", strerror (errno)); + } + + if (bytes_read == 0) { + endwin (); + DIE ("Connection to server lost while receiving message!"); + } + + if ((size_t) bytes_read != packet->size) { + endwin (); + DEBUG ("expected %hhu, received %ld", packet->size, bytes_read); + DIE ("Received malformed message!"); + } + + if (check_integrity) { + uint8_t hash1[SHA_DIGEST_SIZE]; + uint8_t hash2[SHA_DIGEST_SIZE]; + + bytes_read = read (server, hash1, sizeof (hash1)); + if (bytes_read == -1) { + if (errno == EAGAIN) + return; + + endwin (); + DIE ("read: %s", strerror (errno)); + } + + if (bytes_read == 0) { + endwin (); + DIE ("Connection to server lost while receiving message!"); + } + + if ((size_t) bytes_read != sizeof (hash1)) { + endwin (); + DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read); + DIE ("Received malformed message!"); + } + + struct memory_view mv = { + .data = (void *) packet, + .size = sizeof (*packet) + packet->size, + }; + sha1_hash (hash2, mv); + if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) { + struct history_item item = { + .message = "warning: Received wrong hash from server", + .color_pair = COLOR_WARNING, + }; + DYNAMIC_ARRAY_APPEND (history, item); + } + } + + if (key_kind == KK_NONE) { + struct message *msg = (void *) packet; + if (msg->length > MAX_MESSAGE_LENGTH) + goto again; + + struct history_item item = { + .message = malloc (msg->length + 1), + }; + if (item.message == NULL) + goto again; + memcpy (item.message, msg->data, msg->length); + item.message[(int) msg->length] = '\0'; + DYNAMIC_ARRAY_APPEND (history, item); + } else { + static struct message msg; + struct memory_span plain_ms = { + .data = (void *) &msg.data, + .size = sizeof (msg.data), + }; + struct memory_view enc_mv = { + .data = packet->data, + .size = packet->size, + }; + ssize_t size = aes_256_cbc_decrypt (plain_ms, enc_mv, key, salt); + if (size == -1) { + struct history_item item = { + .message = "warning: Failed to decrypt message", + .color_pair = COLOR_WARNING, + }; + DYNAMIC_ARRAY_APPEND (history, item); + goto again; + } + + struct history_item item = { + .message = malloc (size + 1), + }; + if (item.message == NULL) + goto again; + memcpy (item.message, msg.data, size); + item.message[size] = '\0'; + DYNAMIC_ARRAY_APPEND (history, item); + } + + goto again; +} + +void +kill (char *start, int len) +{ + if (!kill_ring.active) + DYNAMIC_ARRAY_RESET (kill_ring); + + DYNAMIC_ARRAY_APPEND_MANY (kill_ring, start, len); + + kill_ring.active = true; + kill_ring.killed = true; +} + +int +main (int argc, char *argv[]) +{ + char *progname = argv[0]; + + char *login = getlogin (); + + struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "login", required_argument, NULL, 'l' }, + { "plain", no_argument, NULL, 'p' }, + { "key", required_argument, NULL, 'k' }, + { "salt", no_argument, NULL, 's' }, + { "key-exchange", no_argument, NULL, 'x' }, + { "check-integrity", no_argument, NULL, 'c' }, + { "bad-hash", no_argument, NULL, 'b' }, + {0} + }; + char ch; + while ((ch = getopt_long (argc, argv, ":hl:pk:sxcb", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + usage (stdout, progname); + exit (EXIT_SUCCESS); + case 'l': login = optarg; break; + case 'p': key_kind = KK_NONE; break; + case 'k': key_kind = KK_PSK; key_filename = optarg; break; + case 's': salt = true; break; + case 'x': key_kind = KK_DHKX; break; + case 'c': check_integrity = true; break; + case 'b': bad_line = true; break; + case '?': DIE ("Unknown option %s", argv[optind - 1]); + case ':': DIE ("Missing argument for %s", argv[optind - 1]); + default: DIE ("Unexpected opt error"); + } + } + + if (argc - optind != 2) { + usage (stderr, argv[0]); + exit (EXIT_FAILURE); + } + + if (salt && key_kind == KK_NONE) + DIE ("Using --salt doesn't make sense with --plain"); + + if (key_kind == KK_PSK) { + if (!key_filename) + DIE ("When using PSK (the default), you need to specify --key"); + + if (!load_aes_256_key (key, key_filename)) + DIE ("Unable to load AES-256 key from '%s': %s", + key_filename, strerror (errno)); + } + + const char *addr = argv[optind + 0]; + char *tail = NULL; + unsigned long int port = strtoul (argv[optind + 1], &tail, 10); + if (!tail || *tail != '\0') + DIE ("Failed to parse port"); + + struct sockaddr_in sin = { + .sin_family = AF_INET, + .sin_port = htons (port), + }; + if (!inet_aton (addr, &sin.sin_addr)) + DIE ("Failed to convert address %s", addr); + + if (!crypto_init ()) + DIE ("Failed to initialize crypto"); + + epoll_fd = epoll_create1 (0); + if (epoll_fd == -1) + DIE ("Failed to create epoll file descriptor: %s", strerror (errno)); + + struct epoll_event event; + event.events = EPOLLIN | EPOLLWAKEUP; + event.data.fd = STDIN_FILENO; + if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event)) + DIE ("Failed to add stdin file descriptor to epoll: %s", strerror (errno)); + + server = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (server == -1) + DIE ("Failed to create socket: %s", strerror (errno)); + + if (connect (server, (struct sockaddr *) &sin, sizeof (sin)) == -1) + DIE ("connect: %s", strerror (errno)); + + if (key_kind == KK_DHKX) { + if (write (server, local_pubkey, sizeof (local_pubkey)) != + sizeof (local_pubkey)) { + DIE ("write: %s", strerror (errno)); + } + uint8_t server_pubkey[X25519_PUBKEY_LEN]; + if (read (server, server_pubkey, sizeof (server_pubkey)) != + sizeof (server_pubkey)) { + DIE ("read: %s", strerror (errno)); + } + if (!hkdf_sha256 (server_pubkey, key)) + DIE ("Failed to create shared key"); + } + + if (fcntl (server, F_SETFL, O_NONBLOCK) == -1) + WARNING ("Failed to set nonblocking mode for socket: %s", strerror (errno)); + + event.events = EPOLLIN | EPOLLWAKEUP; + event.data.fd = server; + if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, server, &event)) + DIE ("Failed to add socket file descriptor to epoll: %s", strerror (errno)); + + struct message msg; + int base_msg_length = sprintf (msg.data, "<%s> ", login); + int cursor = msg.length = base_msg_length; + int scroll = 0; + + initscr (); + start_color (); + use_default_colors (); + init_pair (COLOR_NORMAL, -1, -1); + init_pair (COLOR_WARNING, COLOR_YELLOW, -1); + init_pair (COLOR_ERROR, COLOR_RED, -1); + noecho (); + cbreak (); + keypad (stdscr, TRUE); + nodelay (stdscr, TRUE); + curs_set (1); + + int maxy = 0; + int maxx = 0; + while (!should_stop) { + struct epoll_event events[2]; + int event_count = epoll_wait (epoll_fd, events, 2, 250); + for (int i = 0; i < event_count; ++i) { + if (events[i].data.fd == server) { + receive_messages (); + continue; + } + + if (events[i].data.fd == STDIN_FILENO) { + int ch; + while ((ch = getch ()) != ERR) { + kill_ring.killed = false; + if (isprint (ch)) { + if (msg.length >= MAX_MESSAGE_LENGTH) + continue; + + memmove (msg.data + cursor + 1, + msg.data + cursor, msg.length - cursor); + msg.data[cursor++] = ch; + msg.length += 1; + continue; + } + switch (ch) { + case 'h' & ~0x60: + case KEY_BACKSPACE: { + if (cursor <= base_msg_length) + continue; + if (cursor != msg.length) { + memmove (msg.data + cursor - 1, + msg.data + cursor, msg.length - cursor); + } + + msg.length -= 1; + cursor -= 1; + } break; + case 'd' & ~0x60: { + if (cursor >= msg.length) + continue; + if (cursor != msg.length - 1) { + memmove (msg.data + cursor, + msg.data + cursor + 1, msg.length - cursor); + } + + msg.length -= 1; + } break; + case '\n': { + process_message (&msg, base_msg_length); + scroll = 0; + cursor = msg.length = base_msg_length; + } break; + case KEY_LEFT: + case 'b' & ~0x60: { + if (cursor > base_msg_length) + cursor -= 1; + } break; + case KEY_RIGHT: + case 'f' & ~0x60: { + if (cursor < msg.length) + cursor += 1; + } break; + case KEY_UP: + case 'p' & ~0x60: { + if (scroll < history.count - 1) + scroll += 1; + } break; + case KEY_DOWN: + case 'n' & ~0x60: { + if (scroll > 0) + scroll -= 1; + } break; + case 'v' & ~0x60: { + scroll -= maxy/2; + if (scroll < 0) + scroll = 0; + } break; + case 'l' & ~0x60: { + scroll = 0; + } break; + case 'a' & ~0x60: { + cursor = base_msg_length; + } break; + case 'e' & ~0x60: { + cursor = msg.length; + } break; + case 'u' & ~0x60: { + kill (msg.data + base_msg_length, cursor - base_msg_length); + memmove (msg.data + base_msg_length, + msg.data + cursor, msg.length - cursor); + msg.length -= cursor - base_msg_length; + cursor = base_msg_length; + } break; + case 'k' & ~0x60: { + kill (msg.data + cursor, msg.length - cursor); + msg.length = cursor; + } break; + case 't' & ~0x60: { + if (cursor == base_msg_length) + break; + + if (cursor == msg.length) { + if (msg.length - base_msg_length < 2) + break; + + char tmp = msg.data[cursor - 2]; + msg.data[cursor - 2] = msg.data[cursor - 1]; + msg.data[cursor - 1] = tmp; + break; + } + + char tmp = msg.data[cursor - 1]; + msg.data[cursor - 1] = msg.data[cursor + 0]; + msg.data[cursor + 0] = tmp; + cursor += 1; + } break; + case 'y' & ~0x60: { + int count = msg.length + kill_ring.count > MAX_MESSAGE_LENGTH + ? MAX_MESSAGE_LENGTH - msg.length : kill_ring.count; + memmove (msg.data + cursor + count, + msg.data + cursor, msg.length - cursor); + memcpy (msg.data + cursor, kill_ring.items, count); + msg.length += count; + cursor += count; + } break; + case '\e': + timeout (100); + nodelay (stdscr, FALSE); + switch (getch ()) { + case 'b': { + while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1; + while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1; + } break; + case 'f': { + while (msg.data[cursor] == ' ' && cursor < msg.length) cursor += 1; + while (msg.data[cursor] != ' ' && cursor < msg.length) cursor += 1; + } break; + case KEY_BACKSPACE: + case 'h': { + int to = cursor; + while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1; + while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1; + kill (msg.data + cursor, to - cursor); + memmove (&msg.data[cursor], &msg.data[to], msg.length - to); + msg.length -= to - cursor; + } break; + case 'd': { + int to = cursor; + while (msg.data[to] == ' ' && to < msg.length) to += 1; + while (msg.data[to] != ' ' && to < msg.length) to += 1; + kill (msg.data + cursor, to - cursor); + memmove (&msg.data[cursor], &msg.data[to], msg.length - to); + msg.length -= to - cursor; + } break; + case 'v': { + scroll += maxy/2; + if (scroll >= history.count - 1) + scroll = history.count - 1; + } break; + // TODO(cmmm): M+t + } + nodelay (stdscr, TRUE); + break; + } + + kill_ring.active &= kill_ring.killed; + } + } + } + + erase (); + getmaxyx (stdscr, maxy, maxx); + int y = maxy - 3; + for (uint32_t i = history.count - scroll; y >= 0 && i > 0; y -= 1) { + i -= 1; + color_set (history.items[i].color_pair, NULL); + mvaddstr (y, 0, history.items[i].message); + } color_set (COLOR_NORMAL, NULL); + mvhline (maxy - 2, 0, 0, maxx); + mvaddnstr (maxy - 1, 0, msg.data, msg.length); + if (scroll) { + int width = snprintf (NULL, 0, "[%u/%u]", scroll + 1, history.count); + mvprintw (0, maxx - width, "[%u/%u]", scroll + 1, history.count); + } + move (maxy - 1, cursor); + refresh (); + } + + endwin (); + + return EXIT_SUCCESS; +} + +// client.c ends here diff --git a/05/src/common.c b/05/src/common.c new file mode 100644 index 0000000..b09c06e --- /dev/null +++ b/05/src/common.c @@ -0,0 +1,39 @@ +// common.c --- shared between client and server +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include "common.h" +#include "utils.h" + +bool +load_aes_256_key (aes_256_key key, const char *filename) +{ + FILE *stream = fopen (filename, "r"); + if (stream == NULL) + return false; + + // TODO(cmmm): handle wrong format better... + int assignments = 0; + for (int i = 0; i < AES_256_KEY_SIZE; ++i) + assignments += fscanf (stream, "%02hhx", &key[i]); + fclose (stream); + + return assignments == AES_256_KEY_SIZE; +} + +void +print_hex (uint8_t *data, size_t size) +{ + for (size_t i = 0; i < size; ++i) { + if (i && i % 2 == 0) printf (" "); + printf ("%02x", data[i]); + } printf ("\n"); +} + +// common.c ends here diff --git a/05/src/common.h b/05/src/common.h new file mode 100644 index 0000000..1c6f0ca --- /dev/null +++ b/05/src/common.h @@ -0,0 +1,40 @@ +// common.h --- shared between client and server +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_COMMON_H +#define INCLUDED_COMMON_H + +#include "stdint.h" +#include "crypto.h" + +struct packet { + uint8_t size; + uint8_t data[]; +}; +#define MAX_PACKET_SIZE (256 - sizeof (struct packet)) + +#define MAX_MESSAGE_LENGTH 80 +struct message { + char length; + char data[MAX_MESSAGE_LENGTH]; +}; + +enum key_kind { + KK_NONE, + KK_PSK, + KK_DHKX, +}; + +bool load_aes_256_key (aes_256_key, const char *filename); +void print_hex (uint8_t *data, size_t size); + +#endif // INCLUDED_COMMON_H + +// common.h ends here diff --git a/05/src/crypto.c b/05/src/crypto.c new file mode 100644 index 0000000..eb60ba9 --- /dev/null +++ b/05/src/crypto.c @@ -0,0 +1,239 @@ +// crypto.c --- cryptography utilities +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include "crypto.h" + +#include +#include +#include +#include +#include +#include + +#include "common.h" + +static EVP_PKEY *pkey_local = NULL; +static EVP_PKEY_CTX *pkey_derive_ctx = NULL; + +uint8_t local_pubkey[X25519_PUBKEY_LEN]; + +static EVP_MD *md_sha1 = NULL; +static EVP_MD_CTX *md_sha1_ctx = NULL; + +static EVP_KDF *hkdf = NULL; +static EVP_KDF_CTX *hkdf_ctx = NULL; + +static EVP_CIPHER *cipher_aes_cbc = NULL; +static EVP_CIPHER_CTX *cipher_ctx = NULL; + +bool +crypto_init (void) +{ + EVP_PKEY_CTX *pkey_gen_ctx = + EVP_PKEY_CTX_new_from_name (NULL, "X25519", NULL); + if (pkey_gen_ctx == NULL) goto error; + + if (EVP_PKEY_keygen_init (pkey_gen_ctx) <= 0) { + EVP_PKEY_CTX_free (pkey_gen_ctx); + goto error; + } + + if (EVP_PKEY_keygen (pkey_gen_ctx, &pkey_local) <= 0) { + EVP_PKEY_CTX_free (pkey_gen_ctx); + goto error; + } EVP_PKEY_CTX_free (pkey_gen_ctx); + + pkey_derive_ctx = EVP_PKEY_CTX_new_from_pkey (NULL, pkey_local, NULL); + if (pkey_derive_ctx == NULL) goto error; + + size_t len; + if (EVP_PKEY_get_raw_public_key (pkey_local, local_pubkey, &len) <= 0) + goto error; + if (len != X25519_PUBKEY_LEN) goto error_pkey_derive_ctx; + + md_sha1 = EVP_MD_fetch (NULL, "SHA-1", NULL); + if (md_sha1 == NULL) goto error_pkey_derive_ctx; + + md_sha1_ctx = EVP_MD_CTX_new (); + if (md_sha1_ctx == NULL) goto error_md_sha1; + + if (!EVP_DigestInit_ex2 (md_sha1_ctx, md_sha1, NULL)) + goto error_md_sha1_ctx; + + hkdf = EVP_KDF_fetch (NULL, "HKDF", NULL); + if (!hkdf) goto error_md_sha1_ctx; + + hkdf_ctx = EVP_KDF_CTX_new (hkdf); + if (!hkdf_ctx) goto error_hkdf; + + cipher_aes_cbc = EVP_CIPHER_fetch (NULL, "AES-256-CBC", NULL); + if (cipher_aes_cbc == NULL) goto error_hkdf_ctx; + + cipher_ctx = EVP_CIPHER_CTX_new (); + if (cipher_ctx == NULL) goto error_cipher_aes_cbc; + + return true; + + error_cipher_aes_cbc: + EVP_CIPHER_free (cipher_aes_cbc); + error_hkdf_ctx: + EVP_KDF_CTX_free (hkdf_ctx); + error_hkdf: + EVP_KDF_free (hkdf); + error_pkey_derive_ctx: + EVP_PKEY_CTX_free (pkey_derive_ctx); + error_md_sha1_ctx: + EVP_MD_CTX_free (md_sha1_ctx); + error_md_sha1: + EVP_MD_free (md_sha1); + error: + ERR_print_errors_fp (stderr); + return false; +} + +ssize_t +sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in) +{ + unsigned int length; + + if (EVP_DigestInit_ex2 (md_sha1_ctx, NULL, NULL) != 1) goto error; + if (EVP_DigestUpdate (md_sha1_ctx, in.data, in.size) != 1) goto error; + if (EVP_DigestFinal_ex (md_sha1_ctx, out, &length) != 1) goto error; + + return length; + + error: + ERR_reason_error_string (ERR_get_error ()); + return -1; +} + +bool +hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out) +{ + EVP_PKEY *peer_pkey = + EVP_PKEY_new_raw_public_key_ex (NULL, "X25519", NULL, + peer_pubkey, X25519_PUBKEY_LEN); + if (peer_pkey == NULL) goto error; + + if (EVP_PKEY_derive_init (pkey_derive_ctx) <= 0) + goto error; + if (EVP_PKEY_derive_set_peer (pkey_derive_ctx, peer_pkey) <= 0) + goto error; + + size_t ikm_len = 0; + if (EVP_PKEY_derive (pkey_derive_ctx, NULL, &ikm_len) <= 0) goto error; + + uint8_t *ikm = OPENSSL_malloc (ikm_len); + if (!ikm) goto error; + + if (EVP_PKEY_derive (pkey_derive_ctx, ikm, &ikm_len) <= 0) goto error; + EVP_PKEY_free (peer_pkey); + + uint8_t salt[] = { 0xcd }; + size_t salt_len = sizeof (salt); + uint8_t info[] = { 0xcd }; + size_t info_len = sizeof (info); + + OSSL_PARAM params[] = { + OSSL_PARAM_construct_utf8_string (OSSL_KDF_PARAM_DIGEST, "SHA256", 0), + OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_KEY, (void *) ikm, ikm_len), + OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_SALT, (void *) salt, salt_len), + OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_INFO, (void *) info, info_len), + OSSL_PARAM_construct_end (), + }; + + EVP_KDF_CTX_reset (hkdf_ctx); + if (EVP_KDF_derive (hkdf_ctx, out, AES_256_KEY_SIZE, params) <= 0) + goto error; + OPENSSL_free (ikm); + + return true; + + error: + EVP_PKEY_free (peer_pkey); + OPENSSL_free (ikm); + ERR_print_errors_fp (stderr); + return false; +} + +ssize_t +aes_256_cbc_encrypt (struct memory_span out, + struct memory_view in, const aes_256_key key, bool salt) +{ + ASSERT (out.size >= AES_IV_SIZE + in.size + AES_BLOCK_SIZE - 1); + + uint8_t *head = out.data; + + uint8_t *iv = NULL; + if (salt) { + iv = head; + if (RAND_bytes (iv, AES_IV_SIZE) != 1) + goto error; + head += AES_IV_SIZE; + } + + if (!EVP_CIPHER_CTX_reset (cipher_ctx)) + goto error; + + if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1) + goto error; + + int bytes_written = 0; + if (EVP_EncryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1) + goto error; + head += bytes_written; + + if (EVP_EncryptFinal_ex (cipher_ctx, head, &bytes_written) != 1) + goto error; + head += bytes_written; + + return head - out.data; + +error: + ERR_print_errors_fp (stderr); + return -1; +} + +ssize_t +aes_256_cbc_decrypt (struct memory_span out, + struct memory_view in, const aes_256_key key, bool salt) +{ + uint8_t *head = out.data; + + const uint8_t *iv = NULL; + if (salt) { + const uint8_t *iv = in.data; + in.data += AES_IV_SIZE; + in.size -= AES_IV_SIZE; + } + + if (!EVP_CIPHER_CTX_reset (cipher_ctx)) + goto error; + + if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1) + goto error; + + int bytes_written = 0; + if (EVP_DecryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1) + goto error; + head += bytes_written; + + if (EVP_DecryptFinal_ex (cipher_ctx, head, &bytes_written) != 1) + goto error; + head += bytes_written; + + return head - out.data; + +error: + // ERR_print_errors_fp (stderr); + return -1; +} + +// crypto.c ends here diff --git a/05/src/crypto.h b/05/src/crypto.h new file mode 100644 index 0000000..eb3330d --- /dev/null +++ b/05/src/crypto.h @@ -0,0 +1,37 @@ +// crypto.h --- cryptography utilities +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_CRYPTO_H +#define INCLUDED_CRYPTO_H + +#include +#include + +#include "utils.h" + +#define X25519_PUBKEY_LEN 32 +#define SHA_DIGEST_SIZE 20 +#define AES_256_KEY_SIZE 32 +#define AES_BLOCK_SIZE 16 +#define AES_IV_SIZE 16 + +typedef uint8_t aes_256_key[AES_256_KEY_SIZE]; + +extern uint8_t local_pubkey[X25519_PUBKEY_LEN]; + +bool crypto_init (void); +ssize_t sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in); +bool hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out); +ssize_t aes_256_cbc_encrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt); +ssize_t aes_256_cbc_decrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt); + +#endif // INCLUDED_CRYPTO_H + +// crypto.h ends here diff --git a/05/src/dynamic-array.h b/05/src/dynamic-array.h new file mode 100644 index 0000000..ed5cb32 --- /dev/null +++ b/05/src/dynamic-array.h @@ -0,0 +1,68 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] + +#define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--] + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/05/src/gcm.c b/05/src/gcm.c new file mode 100644 index 0000000..7d3ab68 --- /dev/null +++ b/05/src/gcm.c @@ -0,0 +1,143 @@ +int +aes256_gcm_encrypt (const uint8_t *plaintext, int plaintext_len, + const uint8_t *aad, int aad_len, + const uint8_t key[AES_256_KEY_SIZE], + const uint8_t *nonce, int nonce_len, + uint8_t *ciphertext, + uint8_t tag[GCM_TAG_SIZE]) +{ + int len = 0; + int ciphertext_len = 0; + int ok = 0; + + if (!EVP_CIPHER_CTX_reset (cipher_ctx)) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + /* + Set nonce length before setting key/nonce if using a non-default length. + For GCM, 12 bytes is the common default and recommended size. + */ + if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN, + nonce_len, NULL) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (EVP_EncryptInit_ex (cipher_ctx, NULL, NULL, key, nonce) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + /* + AAD is authenticated but not encrypted. + Pass out=NULL for AAD. + */ + if (aad != NULL && aad_len > 0) { + if (EVP_EncryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + } + + if (EVP_EncryptUpdate (cipher_ctx, ciphertext, &len, + plaintext, plaintext_len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + ciphertext_len = len; + + /* + Final for GCM typically produces no extra ciphertext bytes, but it must + still be called. + */ + if (EVP_EncryptFinal_ex (cipher_ctx, ciphertext + ciphertext_len, &len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + ciphertext_len += len; + + /* + Get the authentication tag. + */ + if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_GET_TAG, + GCM_TAG_SIZE, tag) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + return ciphertext_len; +} + +int aes256_gcm_decrypt (const uint8_t *ciphertext, int ciphertext_len, + const uint8_t *aad, int aad_len, + const uint8_t tag[GCM_TAG_SIZE], + const uint8_t key[AES_256_KEY_SIZE], + const uint8_t *nonce, int nonce_len, + uint8_t *plaintext) +{ + int len = 0; + int plaintext_len = 0; + int ret = -1; + + if (EVP_CIPHER_CTX_reset (cipher_ctx)) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN, + nonce_len, NULL) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (EVP_DecryptInit_ex2 (cipher_ctx, NULL, key, nonce, NULL) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + if (aad != NULL && aad_len > 0) { + if (EVP_DecryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + } + + if (EVP_DecryptUpdate (cipher_ctx, plaintext, &len, + ciphertext, ciphertext_len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + plaintext_len = len; + + /* + Set expected tag before finalizing. + */ + if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_TAG, + GCM_TAG_SIZE, (void *)tag) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + + /* + Success only if tag verification passes. + */ + if (EVP_DecryptFinal_ex (cipher_ctx, plaintext + plaintext_len, &len) != 1) { + ERR_print_errors_fp (stderr); + return -1; + } + plaintext_len += len; + + return plaintext_len; +} diff --git a/05/src/server.c b/05/src/server.c new file mode 100644 index 0000000..971117c --- /dev/null +++ b/05/src/server.c @@ -0,0 +1,539 @@ +// server.c --- server component +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LOG(PRIORITY, FMT, ...) \ + syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \ + FMT __VA_OPT__ (,) __VA_ARGS__) + +#include "utils.h" +#include "common.h" +#include "crypto.h" +#include "dynamic-array.h" + +#define MAX_EVENTS 5 + +static bool should_stop = false; + +static bool salt = false; +static bool echo = false; +static bool check_integrity = false; +static bool bad_line = false; +static char *key_filename = NULL; +static enum key_kind key_kind = KK_PSK; +static aes_256_key key; + +struct client { + struct client *prev; + struct client *next; + struct sockaddr_in sin; + aes_256_key key; + int fd; + enum client_state { + CS_READY, + CS_WAITING_FOR_PUBKEY, + } state; +}; + +static struct client *clients = NULL; +static struct client *client_free_list = NULL; + +static int epoll_fd; + +void +accept_connections (int fd) +{ + again: + if (client_free_list == NULL) + client_free_list = calloc (1, sizeof (*client_free_list)); + struct client *client = client_free_list; + + socklen_t length = sizeof (client->sin); + client->fd = accept (fd, (struct sockaddr *) &client->sin, &length); + if (client->fd == -1) { + if (errno == EWOULDBLOCK) return; + ERROR ("Failed to accept connection: %s", strerror (errno)); + goto again; + } NOTICE ("Accepted connection from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + + if (fcntl (client->fd, F_SETFL, O_NONBLOCK) == -1) { + ERROR ("Failed to set nonblocking mode for client socket: %s", + strerror (errno)); + } + + struct epoll_event event; + event.events = EPOLLIN | EPOLLWAKEUP; + event.data.ptr = client; + if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, client->fd, &event)) { + ERROR ("Failed to add file descriptor to epoll: %s", strerror (errno)); + close (client->fd); + goto again; + } + + client_free_list = client_free_list->next; + if (clients) + clients->prev = client; + client->next = clients; + client->prev = NULL; + clients = client; + + if (key_kind == KK_DHKX) { + write (client->fd, local_pubkey, sizeof (local_pubkey)); + client->state = CS_WAITING_FOR_PUBKEY; + } else { + client->state = CS_READY; + } + + goto again; +} + +void +close_connection (struct client *client) +{ + INFO ("Connection closed " SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (client->sin)); + if (epoll_ctl (epoll_fd, EPOLL_CTL_DEL, client->fd, NULL)) + ERROR ("Failed to del file descriptor from epoll: %s", strerror (errno)); + close (client->fd); + + if (client->prev) client->prev->next = client->next; + if (client->next) client->next->prev = client->prev; + if (client == clients) clients = client->next; + client->next = client_free_list; + client_free_list = client; +} + +bool +send_to_plain (struct memory_view mv, struct client *to) +{ + uint8_t buffer[MAX_PACKET_SIZE]; + memcpy (buffer, mv.data, mv.size); + size_t size = mv.size; + if (check_integrity) { + uint8_t hash[SHA_DIGEST_SIZE]; + sha1_hash (hash, mv); + if (bad_line) { + for (int i = 0; i < SHA_DIGEST_SIZE; ++i) + hash[i] += i; + } + memcpy (&buffer[size], hash, sizeof (hash)); + size += sizeof (hash); + } + + again: + ssize_t bytes_written = write (to->fd, buffer, size); + if (bytes_written == -1) { + switch (errno) { + case EAGAIN: goto again; + default: + ERROR (SOCKADDR_IN_FMT ": write: %s", + SOCKADDR_IN_SPLIT (to->sin), strerror (errno)); + } return false; + } + + if (bytes_written == 0) { + return false; + } + + if ((size_t) bytes_written != size) { + ERROR (SOCKADDR_IN_FMT ": Failed to write whole buffer", + SOCKADDR_IN_SPLIT (to->sin)); + return false; + } + + return true; +} + +bool +send_to_encrypted (struct memory_view msg_mv, struct client *to) +{ + static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; + struct packet *packet = (void *) buffer; + struct memory_span packet_ms = { + .data = packet->data, + .size = MAX_PACKET_SIZE - sizeof (packet->size), + }; + ssize_t size = + aes_256_cbc_encrypt (packet_ms, msg_mv, + key_kind == KK_PSK ? key : to->key, salt); + if (size == -1) + return false; + packet->size = size; + + struct memory_view packet_mv = { + .data = (void *) packet, + .size = sizeof (packet->size) + packet->size, + }; + return send_to_plain (packet_mv, to); +} + +bool +send_message_to (const struct message *msg, struct client *to) +{ + INFO ("Sending message to " SOCKADDR_IN_FMT ": %.*s", + SOCKADDR_IN_SPLIT (to->sin), (int) msg->length, msg->data); + + bool ret; + if (key_kind == KK_NONE) { + struct memory_view mv = { + .data = (void *) msg, + .size = sizeof (msg->length) + msg->length, + }; + ret = send_to_plain (mv, to); + } else { + struct memory_view mv = { + .data = (void *) msg->data, + .size = msg->length, + }; + ret = send_to_encrypted (mv, to); + } + + INFO ("%s message to " SOCKADDR_IN_FMT, + ret ? "Sent" : "Failed to send", SOCKADDR_IN_SPLIT (to->sin)); + if (!ret) + close_connection (to); + + return ret; +} + +void +broadcast (const struct message *msg, const struct client *except) +{ + struct client *next; + for (struct client *client = clients; client; client = next) { + if (client == except) + continue; + + next = client->next; + send_message_to (msg, client); + } +} + +// FIXME(cmmm): don't expect to read whole (and sole) packet at once... +bool +handle_client (struct client *client) +{ + static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; + struct packet *packet = (void *) buffer; + + again: + switch (client->state) { + case CS_READY: { + ssize_t bytes_read = read (client->fd, packet, sizeof (*packet)); + if (bytes_read == -1) { + switch (errno) { + case EAGAIN: return true; + default: + ERROR (SOCKADDR_IN_FMT ": read: %s", + SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); + } return false; + } + + if (bytes_read == 0) + return false; + + if (bytes_read != sizeof (*packet)) { + ERROR ("Received malformed message from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read); + return false; + } + + bytes_read = read (client->fd, packet->data, packet->size); + if (bytes_read == -1) { + ERROR (SOCKADDR_IN_FMT ": read: %s", + SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); + return false; + } + + if (bytes_read == 0) + return false; + + if ((size_t) bytes_read != packet->size) { + ERROR ("Received malformed message from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + DEBUG ("expected %hhu, received %ld", packet->size, bytes_read); + return false; + } + + if (check_integrity) { + uint8_t hash1[SHA_DIGEST_SIZE]; + uint8_t hash2[SHA_DIGEST_SIZE]; + + bytes_read = read (client->fd, hash1, sizeof (hash1)); + if (bytes_read == -1) { + ERROR (SOCKADDR_IN_FMT ": read: %s", + SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); + return false; + } + + if (bytes_read == 0) + return false; + + if ((size_t) bytes_read != sizeof (hash1)) { + ERROR ("Received malformed message from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read); + return false; + } + + struct memory_view mv = { + .data = (void *) packet, + .size = sizeof (*packet) + packet->size, + }; + sha1_hash (hash2, mv); + if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) { + WARNING ("Received wrong hash from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + goto again; + } + } + + if (key_kind == KK_NONE) { + const struct message *msg = (void *) packet; + INFO ("Received plain text message from " SOCKADDR_IN_FMT ": %.*s", + SOCKADDR_IN_SPLIT (client->sin), (int) msg->length, msg->data); + broadcast (msg, echo ? NULL : client); + } else { + static struct message msg; + struct memory_span plain_ms = { + .data = (void *) &msg.data, + .size = sizeof (msg.data), + }; + struct memory_view enc_mv = { + .data = packet->data, + .size = packet->size, + }; + ssize_t size = + aes_256_cbc_decrypt (plain_ms, enc_mv, + key_kind == KK_PSK ? key : client->key, salt); + if (size == -1) { + ERROR ("Failed to decrypt received message from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + return false; + } + msg.length = size; + INFO ("Received encrypted message from " SOCKADDR_IN_FMT ": %.*s", + SOCKADDR_IN_SPLIT (client->sin), (int) msg.length, msg.data); + broadcast (&msg, echo ? NULL : client); + } + + } break; + case CS_WAITING_FOR_PUBKEY: { + if (read (client->fd, buffer, X25519_PUBKEY_LEN) != X25519_PUBKEY_LEN) { + ERROR ("Received public key of wrong size from " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + return false; + } + + if (!hkdf_sha256 (buffer, client->key)) { + ERROR ("Failed to make shared key for " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + return false; + } + + NOTICE ("Shared key established with " SOCKADDR_IN_FMT, + SOCKADDR_IN_SPLIT (client->sin)); + client->state = CS_READY; + return true; + } break; + default: break; + } + + goto again; +} + +void +usage (FILE *stream, const char *progname) +{ + fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname); + fprintf (stream, "\n"); + fprintf (stream, "Options:\n"); + fprintf (stream, " -h, --help display this help message and exit\n"); + fprintf (stream, " -e, --echo send messages to sender as well\n"); + fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n"); + fprintf (stream, " -p, --plain don't use encryption*\n"); + fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n"); + fprintf (stream, " -c, --check-integrity use message integrity checking*\n"); + fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n"); + fprintf (stream, "\n"); + fprintf (stream, "Notes:\n"); + fprintf (stream, " Options marked with (*) must match the ones use by the clients!\n"); + fprintf (stream, "\n"); +} + +void +test_aes_256_cbc (void) +{ + const char *data = "Hello, World!"; + puts (data); + struct memory_view mv = { + .data = (void *) data, + .size = strlen (data), + }; + + static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; + struct memory_span ms = { + .data = buffer, + .size = sizeof (buffer), + }; + + size_t size; + size = aes_256_cbc_encrypt (ms, mv, key, salt); + for (size_t i = 0; i < size; ++i) { + printf ("%02hhx ", ms.data[i]); + if ((i + 1) % 8 == 0) printf ("\n"); + } + + mv.data = ms.data; + mv.size = ms.size; + size = aes_256_cbc_decrypt (ms, mv, key, salt); + printf ("%.*s\n", (int) ms.size, ms.data); +} + +int +main (int argc, char *argv[]) +{ + char *progname = argv[0]; + + struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "echo", no_argument, NULL, 'e' }, + { "plain", no_argument, NULL, 'p' }, + { "key", required_argument, NULL, 'k' }, + { "salt", no_argument, NULL, 's' }, + { "key-exchange", no_argument, NULL, 'x' }, + { "check-integrity", no_argument, NULL, 'c' }, + { "bad-hash", no_argument, NULL, 'b' }, + {0} + }; + char ch; + while ((ch = getopt_long (argc, argv, ":hepk:sxcb", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + usage (stdout, progname); + exit (EXIT_SUCCESS); + case 'e': echo = true; break; + case 'p': key_kind = KK_NONE; break; + case 'k': key_kind = KK_PSK; key_filename = optarg; break; + case 's': salt = true; break; + case 'x': key_kind = KK_DHKX; break; + case 'c': check_integrity = true; break; + case 'b': bad_line = true; break; + case '?': DIE ("unknown option %s", argv[optind - 1]); + case ':': DIE ("missing argument for %s", argv[optind - 1]); + default: DIE ("unexpected opt error"); + } + } + + if (argc - optind != 2) { + usage (stderr, progname); + exit (EXIT_FAILURE); + } + + setlogmask (LOG_UPTO (LOG_DEBUG)); + // openlog (basename (progname), LOG_PID | LOG_PERROR, LOG_DAEMON); + openlog (basename (progname), LOG_PERROR, LOG_DAEMON); + + if (salt && key_kind == KK_NONE) + DIE ("Using --salt doesn't make sense with --plain"); + + if (key_kind == KK_PSK) { + if (!key_filename) + DIE ("When using PSK (the default), you need to specify --key"); + + if (!load_aes_256_key (key, key_filename)) + DIE ("Unable to load AES-256 key from '%s': %s", + key_filename, strerror (errno)); + } + + const char *addr = argv[optind + 0]; + char *tail = NULL; + unsigned long int port = strtoul (argv[optind + 1], &tail, 10); + if (!tail || *tail != '\0') + DIE ("Failed to parse port"); + + struct sockaddr_in sin = { + .sin_family = AF_INET, + .sin_port = htons (port), + }; + if (!inet_aton (addr, &sin.sin_addr)) + DIE ("Failed to convert address %s", addr); + + if (!crypto_init ()) + DIE ("Failed to initialize crypto"); + + epoll_fd = epoll_create1 (0); + if (epoll_fd == -1) + DIE ("Failed to create epoll file descriptor: %s", strerror (errno)); + + int listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listener == -1) + DIE ("Failed to create socket: %s", strerror (errno)); + + struct epoll_event event; + event.events = EPOLLIN | EPOLLWAKEUP; + event.data.ptr = NULL; + if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, listener, &event)) + DIE ("Failed to add file descriptor to epoll: %s", strerror (errno)); + + int reuseaddr = 1; + setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, + &reuseaddr, sizeof (reuseaddr)); + + if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) { + ERROR ("Failed to set nonblocking mode for listener socket: %s", + strerror (errno)); + } + + if (bind (listener, (struct sockaddr *) &sin, sizeof (sin)) == -1) { + DIE ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s", + SOCKADDR_IN_SPLIT (sin), strerror (errno)); + } + + if (listen (listener, 2)) { + DIE ("Failed to listen on "SOCKADDR_IN_FMT": %s", + SOCKADDR_IN_SPLIT (sin), strerror (errno)); + } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (sin)); + + NOTICE ("Server started..."); + while (!should_stop) { + DEBUG ("Polling..."); + struct epoll_event events[MAX_EVENTS]; + int event_count = epoll_wait (epoll_fd, events, MAX_EVENTS, -1); + DEBUG ("Got %d event%s", event_count, event_count > 1 ? "s" : ""); + for (int i = 0; i < event_count; ++i) { + if (events[i].data.ptr == NULL) { + accept_connections (listener); + continue; + } + + if (!handle_client (events[i].data.ptr)) + close_connection (events[i].data.ptr); + } + } + + NOTICE ("Server stopped..."); + return EXIT_SUCCESS; +} + +// server.c ends here diff --git a/05/src/utils.h b/05/src/utils.h new file mode 100644 index 0000000..a17eed6 --- /dev/null +++ b/05/src/utils.h @@ -0,0 +1,90 @@ +// utils.h --- utilities +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) +#define DEBUG( FMT, ...) \ + LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__) +#define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__) + +#define DIE(FMT, ...) do { \ + EMERGENCY (FMT __VA_OPT__ (,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) + +#define UNUSED(X) ((void) (X)) +#define UNREACHABLE() ASSERT (!"reached the unreachable...") +#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__) +// #define TODO(...) +#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__) + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +#define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu" +#define SOCKADDR_IN_SPLIT(ADDR) \ + ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 0*8, ntohs ((ADDR).sin_port) + +inline uint8_t +log10u8 (uint8_t n) +{ + return (n >= 100 ? 3 : + n >= 10 ? 2 : 1); +} + +// read-only borrowed +struct memory_view { + const unsigned char *data; + size_t size; +}; + +// writable borrowed +struct memory_span { + unsigned char *data; + size_t size; +}; + +// writable owning +struct memory_buffer { + unsigned char *data; + size_t size; +}; + +#define MEMORY_SPAN_TO_MEMORY_VIEW(MS) \ + ((struct memory_view) { \ + .data = (MS).data, \ + .size = (MS).size, \ + }) + +#endif + +// utils.h ends here -- cgit v1.3.1