From 9e1d304cac5367c3dbb1ca14700736680bd3a804 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Wed, 11 Nov 2026 08:31:06 +0300 Subject: publish --- 05/src/client.c | 684 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 684 insertions(+) create mode 100644 05/src/client.c (limited to '05/src/client.c') 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 -- cgit v1.3.1