aboutsummaryrefslogtreecommitdiff
path: root/05/src
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 05:31:06 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 06:14:42 +0000
commit9e1d304cac5367c3dbb1ca14700736680bd3a804 (patch)
tree31f328747acb934d365d423adfda144818ff5ad4 /05/src
downloadlab-01-05-master.tar.gz
publishHEADmaster
Diffstat (limited to '05/src')
-rw-r--r--05/src/client.c684
-rw-r--r--05/src/common.c39
-rw-r--r--05/src/common.h40
-rw-r--r--05/src/crypto.c239
-rw-r--r--05/src/crypto.h37
-rw-r--r--05/src/dynamic-array.h68
-rw-r--r--05/src/gcm.c143
-rw-r--r--05/src/server.c539
-rw-r--r--05/src/utils.h90
9 files changed, 1879 insertions, 0 deletions
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 @@
1// client.c --- client component
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#include <stdlib.h>
12#include <stdbool.h>
13#include <stdio.h>
14#include <string.h>
15#include <errno.h>
16#include <ctype.h>
17#include <getopt.h>
18#include <unistd.h>
19#include <fcntl.h>
20#include <ncurses.h>
21#include <sys/epoll.h>
22#include <netinet/in.h>
23#include <arpa/inet.h>
24
25#define LOG(PRIORITY, FMT, ...) \
26 fprintf (stderr, FMT "\n" __VA_OPT__ (,) __VA_ARGS__)
27
28#include "utils.h"
29#include "common.h"
30#include "dynamic-array.h"
31#include "crypto.h"
32
33static bool should_stop = false;
34
35static bool salt = false;
36static bool check_integrity = false;
37static bool bad_line = false;
38static char *key_filename = NULL;
39static enum key_kind key_kind = KK_PSK;
40static aes_256_key key;
41
42static int epoll_fd;
43static int server;
44
45enum color {
46 COLOR_NORMAL,
47 COLOR_WARNING,
48 COLOR_ERROR,
49};
50
51struct history_item {
52 char *message;
53 short color_pair;
54};
55
56static struct history {
57 struct history_item *items;
58 int count;
59 int capacity;
60} history = {0};
61
62static struct kill_ring {
63 char *items;
64 int count;
65 int capacity;
66 bool active;
67 bool killed;
68} kill_ring = {0};
69
70void
71usage (FILE *stream, const char *progname)
72{
73 fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname);
74 fprintf (stream, "\n");
75 fprintf (stream, "Options:\n");
76 fprintf (stream, " -h, --help display this help message and exit\n");
77 fprintf (stream, " -l, --login LOGIN use LOGIN instead of system login\n");
78 fprintf (stream, " -p, --plain don't use encryption*\n");
79 fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n");
80 fprintf (stream, " -s, --salt add salt to encrypted messages*\n");
81 fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n");
82 fprintf (stream, " -c, --check-integrity use message integrity checking*\n");
83 fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n");
84 fprintf (stream, "\n");
85 fprintf (stream, "Notes:\n");
86 fprintf (stream, " Options marked with (*) must match the ones use by the server!\n");
87 fprintf (stream, "\n");
88}
89
90void
91send_plain (struct memory_view mv)
92{
93 uint8_t buffer[MAX_PACKET_SIZE];
94 memcpy (buffer, mv.data, mv.size);
95 size_t size = mv.size;
96 if (check_integrity) {
97 uint8_t hash[SHA_DIGEST_SIZE];
98 sha1_hash (hash, mv);
99 if (bad_line) {
100 for (int i = 0; i < SHA_DIGEST_SIZE; ++i)
101 hash[i] += i;
102 }
103 memcpy (&buffer[size], hash, sizeof (hash));
104 size += sizeof (hash);
105 }
106
107 again:
108 ssize_t bytes_written = write (server, buffer, size);
109 if (bytes_written == -1) {
110 switch (errno) {
111 case EAGAIN: goto again;
112 default: ERROR ("write: %s", strerror (errno));
113 }
114 }
115
116 if (bytes_written == 0) {
117 endwin ();
118 DIE ("Connection to server lost while sending message!");
119 }
120
121 if ((size_t) bytes_written != size) {
122 endwin ();
123 DIE ("Failed to write whole buffer");
124 }
125}
126
127void
128send_encrypted (struct memory_view msg_mv)
129{
130 static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE];
131 struct packet *packet = (void *) buffer;
132 struct memory_span packet_ms = {
133 .data = packet->data,
134 .size = MAX_PACKET_SIZE,
135 };
136 ssize_t size = aes_256_cbc_encrypt (packet_ms, msg_mv, key, salt);
137 if (size == -1) {
138 endwin ();
139 DIE ("Failed to decrypt message");
140 }
141 packet->size = size;
142
143 struct memory_view packet_mv = {
144 .data = (void *) packet,
145 .size = sizeof (packet->size) + packet->size,
146 };
147 return send_plain (packet_mv);
148}
149
150void
151send_message (const struct message *msg)
152{
153 struct history_item item = {
154 .message = malloc (msg->length + 1),
155 };
156 memcpy (item.message, msg->data, msg->length);
157 item.message[(int) msg->length] = '\0';
158 DYNAMIC_ARRAY_APPEND (history, item);
159
160 if (key_kind == KK_NONE) {
161 struct memory_view mv = {
162 .data = (void *) msg,
163 .size = sizeof (msg->length) + msg->length,
164 };
165 return send_plain (mv);
166 } else {
167 struct memory_view mv = {
168 .data = (void *) msg->data,
169 .size = msg->length,
170 };
171 return send_encrypted (mv);
172 }
173}
174
175void
176send_shell_output (const struct message *orig, int base_msg_length)
177{
178 static char *line = NULL;
179 static size_t line_length = 0;
180
181 struct message msg;
182 memcpy (msg.data, orig->data, base_msg_length);
183
184 if (line_length < (size_t) orig->length - base_msg_length - 4 + 6) {
185 line_length = orig->length - base_msg_length - 4 + 6;
186 line = realloc (line, line_length);
187 }
188 memcpy (line, orig->data + base_msg_length + 4,
189 orig->length - base_msg_length - 4);
190 strcpy (line + orig->length - base_msg_length - 4, " 2>&1");
191
192 FILE *stream = popen (line, "r");
193 ssize_t bytes_read;
194 while ((bytes_read = getline (&line, &line_length, stream)) != -1) {
195 ssize_t length = base_msg_length + bytes_read - 1;
196 msg.length = length > MAX_MESSAGE_LENGTH ? MAX_MESSAGE_LENGTH : length;
197 memcpy (&msg.data[base_msg_length], line, msg.length - base_msg_length);
198 send_message (&msg);
199 } pclose (stream);
200}
201
202void
203process_message (const struct message *msg, int base_msg_length)
204{
205 if (msg->length > base_msg_length && msg->data[base_msg_length] == '/') {
206 if (msg->length >= base_msg_length + 4 &&
207 strncmp (&msg->data[base_msg_length], "/sh ", 4) == 0) {
208 send_shell_output (msg, base_msg_length);
209 return;
210 }
211 DYNAMIC_ARRAY_APPEND (history, ((struct history_item) {
212 .message = "error: No such command",
213 .color_pair = COLOR_ERROR,
214 }));
215 return;
216 }
217
218 send_message (msg);
219}
220
221void
222receive_messages (void)
223{
224 static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE];
225 struct packet *packet = (void *) buffer;
226
227 again:
228 ssize_t bytes_read = read (server, packet, sizeof (*packet));
229 if (bytes_read == -1) {
230 if (errno == EAGAIN)
231 return;
232
233 endwin ();
234 DIE ("read: %s", strerror (errno));
235 }
236
237 if (bytes_read == 0) {
238 endwin ();
239 DIE ("Connection to server lost while receiving message!");
240 }
241
242 if (bytes_read != sizeof (*packet)) {
243 endwin ();
244 DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read);
245 DIE ("Received malformed message!");
246 }
247
248 bytes_read = read (server, packet->data, packet->size);
249 if (bytes_read == -1) {
250 if (errno == EAGAIN)
251 return;
252
253 endwin ();
254 DIE ("read: %s", strerror (errno));
255 }
256
257 if (bytes_read == 0) {
258 endwin ();
259 DIE ("Connection to server lost while receiving message!");
260 }
261
262 if ((size_t) bytes_read != packet->size) {
263 endwin ();
264 DEBUG ("expected %hhu, received %ld", packet->size, bytes_read);
265 DIE ("Received malformed message!");
266 }
267
268 if (check_integrity) {
269 uint8_t hash1[SHA_DIGEST_SIZE];
270 uint8_t hash2[SHA_DIGEST_SIZE];
271
272 bytes_read = read (server, hash1, sizeof (hash1));
273 if (bytes_read == -1) {
274 if (errno == EAGAIN)
275 return;
276
277 endwin ();
278 DIE ("read: %s", strerror (errno));
279 }
280
281 if (bytes_read == 0) {
282 endwin ();
283 DIE ("Connection to server lost while receiving message!");
284 }
285
286 if ((size_t) bytes_read != sizeof (hash1)) {
287 endwin ();
288 DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read);
289 DIE ("Received malformed message!");
290 }
291
292 struct memory_view mv = {
293 .data = (void *) packet,
294 .size = sizeof (*packet) + packet->size,
295 };
296 sha1_hash (hash2, mv);
297 if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) {
298 struct history_item item = {
299 .message = "warning: Received wrong hash from server",
300 .color_pair = COLOR_WARNING,
301 };
302 DYNAMIC_ARRAY_APPEND (history, item);
303 }
304 }
305
306 if (key_kind == KK_NONE) {
307 struct message *msg = (void *) packet;
308 if (msg->length > MAX_MESSAGE_LENGTH)
309 goto again;
310
311 struct history_item item = {
312 .message = malloc (msg->length + 1),
313 };
314 if (item.message == NULL)
315 goto again;
316 memcpy (item.message, msg->data, msg->length);
317 item.message[(int) msg->length] = '\0';
318 DYNAMIC_ARRAY_APPEND (history, item);
319 } else {
320 static struct message msg;
321 struct memory_span plain_ms = {
322 .data = (void *) &msg.data,
323 .size = sizeof (msg.data),
324 };
325 struct memory_view enc_mv = {
326 .data = packet->data,
327 .size = packet->size,
328 };
329 ssize_t size = aes_256_cbc_decrypt (plain_ms, enc_mv, key, salt);
330 if (size == -1) {
331 struct history_item item = {
332 .message = "warning: Failed to decrypt message",
333 .color_pair = COLOR_WARNING,
334 };
335 DYNAMIC_ARRAY_APPEND (history, item);
336 goto again;
337 }
338
339 struct history_item item = {
340 .message = malloc (size + 1),
341 };
342 if (item.message == NULL)
343 goto again;
344 memcpy (item.message, msg.data, size);
345 item.message[size] = '\0';
346 DYNAMIC_ARRAY_APPEND (history, item);
347 }
348
349 goto again;
350}
351
352void
353kill (char *start, int len)
354{
355 if (!kill_ring.active)
356 DYNAMIC_ARRAY_RESET (kill_ring);
357
358 DYNAMIC_ARRAY_APPEND_MANY (kill_ring, start, len);
359
360 kill_ring.active = true;
361 kill_ring.killed = true;
362}
363
364int
365main (int argc, char *argv[])
366{
367 char *progname = argv[0];
368
369 char *login = getlogin ();
370
371 struct option longopts[] = {
372 { "help", no_argument, NULL, 'h' },
373 { "login", required_argument, NULL, 'l' },
374 { "plain", no_argument, NULL, 'p' },
375 { "key", required_argument, NULL, 'k' },
376 { "salt", no_argument, NULL, 's' },
377 { "key-exchange", no_argument, NULL, 'x' },
378 { "check-integrity", no_argument, NULL, 'c' },
379 { "bad-hash", no_argument, NULL, 'b' },
380 {0}
381 };
382 char ch;
383 while ((ch = getopt_long (argc, argv, ":hl:pk:sxcb", longopts, NULL)) != -1) {
384 switch (ch) {
385 case 'h':
386 usage (stdout, progname);
387 exit (EXIT_SUCCESS);
388 case 'l': login = optarg; break;
389 case 'p': key_kind = KK_NONE; break;
390 case 'k': key_kind = KK_PSK; key_filename = optarg; break;
391 case 's': salt = true; break;
392 case 'x': key_kind = KK_DHKX; break;
393 case 'c': check_integrity = true; break;
394 case 'b': bad_line = true; break;
395 case '?': DIE ("Unknown option %s", argv[optind - 1]);
396 case ':': DIE ("Missing argument for %s", argv[optind - 1]);
397 default: DIE ("Unexpected opt error");
398 }
399 }
400
401 if (argc - optind != 2) {
402 usage (stderr, argv[0]);
403 exit (EXIT_FAILURE);
404 }
405
406 if (salt && key_kind == KK_NONE)
407 DIE ("Using --salt doesn't make sense with --plain");
408
409 if (key_kind == KK_PSK) {
410 if (!key_filename)
411 DIE ("When using PSK (the default), you need to specify --key");
412
413 if (!load_aes_256_key (key, key_filename))
414 DIE ("Unable to load AES-256 key from '%s': %s",
415 key_filename, strerror (errno));
416 }
417
418 const char *addr = argv[optind + 0];
419 char *tail = NULL;
420 unsigned long int port = strtoul (argv[optind + 1], &tail, 10);
421 if (!tail || *tail != '\0')
422 DIE ("Failed to parse port");
423
424 struct sockaddr_in sin = {
425 .sin_family = AF_INET,
426 .sin_port = htons (port),
427 };
428 if (!inet_aton (addr, &sin.sin_addr))
429 DIE ("Failed to convert address %s", addr);
430
431 if (!crypto_init ())
432 DIE ("Failed to initialize crypto");
433
434 epoll_fd = epoll_create1 (0);
435 if (epoll_fd == -1)
436 DIE ("Failed to create epoll file descriptor: %s", strerror (errno));
437
438 struct epoll_event event;
439 event.events = EPOLLIN | EPOLLWAKEUP;
440 event.data.fd = STDIN_FILENO;
441 if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event))
442 DIE ("Failed to add stdin file descriptor to epoll: %s", strerror (errno));
443
444 server = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
445 if (server == -1)
446 DIE ("Failed to create socket: %s", strerror (errno));
447
448 if (connect (server, (struct sockaddr *) &sin, sizeof (sin)) == -1)
449 DIE ("connect: %s", strerror (errno));
450
451 if (key_kind == KK_DHKX) {
452 if (write (server, local_pubkey, sizeof (local_pubkey)) !=
453 sizeof (local_pubkey)) {
454 DIE ("write: %s", strerror (errno));
455 }
456 uint8_t server_pubkey[X25519_PUBKEY_LEN];
457 if (read (server, server_pubkey, sizeof (server_pubkey)) !=
458 sizeof (server_pubkey)) {
459 DIE ("read: %s", strerror (errno));
460 }
461 if (!hkdf_sha256 (server_pubkey, key))
462 DIE ("Failed to create shared key");
463 }
464
465 if (fcntl (server, F_SETFL, O_NONBLOCK) == -1)
466 WARNING ("Failed to set nonblocking mode for socket: %s", strerror (errno));
467
468 event.events = EPOLLIN | EPOLLWAKEUP;
469 event.data.fd = server;
470 if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, server, &event))
471 DIE ("Failed to add socket file descriptor to epoll: %s", strerror (errno));
472
473 struct message msg;
474 int base_msg_length = sprintf (msg.data, "<%s> ", login);
475 int cursor = msg.length = base_msg_length;
476 int scroll = 0;
477
478 initscr ();
479 start_color ();
480 use_default_colors ();
481 init_pair (COLOR_NORMAL, -1, -1);
482 init_pair (COLOR_WARNING, COLOR_YELLOW, -1);
483 init_pair (COLOR_ERROR, COLOR_RED, -1);
484 noecho ();
485 cbreak ();
486 keypad (stdscr, TRUE);
487 nodelay (stdscr, TRUE);
488 curs_set (1);
489
490 int maxy = 0;
491 int maxx = 0;
492 while (!should_stop) {
493 struct epoll_event events[2];
494 int event_count = epoll_wait (epoll_fd, events, 2, 250);
495 for (int i = 0; i < event_count; ++i) {
496 if (events[i].data.fd == server) {
497 receive_messages ();
498 continue;
499 }
500
501 if (events[i].data.fd == STDIN_FILENO) {
502 int ch;
503 while ((ch = getch ()) != ERR) {
504 kill_ring.killed = false;
505 if (isprint (ch)) {
506 if (msg.length >= MAX_MESSAGE_LENGTH)
507 continue;
508
509 memmove (msg.data + cursor + 1,
510 msg.data + cursor, msg.length - cursor);
511 msg.data[cursor++] = ch;
512 msg.length += 1;
513 continue;
514 }
515 switch (ch) {
516 case 'h' & ~0x60:
517 case KEY_BACKSPACE: {
518 if (cursor <= base_msg_length)
519 continue;
520 if (cursor != msg.length) {
521 memmove (msg.data + cursor - 1,
522 msg.data + cursor, msg.length - cursor);
523 }
524
525 msg.length -= 1;
526 cursor -= 1;
527 } break;
528 case 'd' & ~0x60: {
529 if (cursor >= msg.length)
530 continue;
531 if (cursor != msg.length - 1) {
532 memmove (msg.data + cursor,
533 msg.data + cursor + 1, msg.length - cursor);
534 }
535
536 msg.length -= 1;
537 } break;
538 case '\n': {
539 process_message (&msg, base_msg_length);
540 scroll = 0;
541 cursor = msg.length = base_msg_length;
542 } break;
543 case KEY_LEFT:
544 case 'b' & ~0x60: {
545 if (cursor > base_msg_length)
546 cursor -= 1;
547 } break;
548 case KEY_RIGHT:
549 case 'f' & ~0x60: {
550 if (cursor < msg.length)
551 cursor += 1;
552 } break;
553 case KEY_UP:
554 case 'p' & ~0x60: {
555 if (scroll < history.count - 1)
556 scroll += 1;
557 } break;
558 case KEY_DOWN:
559 case 'n' & ~0x60: {
560 if (scroll > 0)
561 scroll -= 1;
562 } break;
563 case 'v' & ~0x60: {
564 scroll -= maxy/2;
565 if (scroll < 0)
566 scroll = 0;
567 } break;
568 case 'l' & ~0x60: {
569 scroll = 0;
570 } break;
571 case 'a' & ~0x60: {
572 cursor = base_msg_length;
573 } break;
574 case 'e' & ~0x60: {
575 cursor = msg.length;
576 } break;
577 case 'u' & ~0x60: {
578 kill (msg.data + base_msg_length, cursor - base_msg_length);
579 memmove (msg.data + base_msg_length,
580 msg.data + cursor, msg.length - cursor);
581 msg.length -= cursor - base_msg_length;
582 cursor = base_msg_length;
583 } break;
584 case 'k' & ~0x60: {
585 kill (msg.data + cursor, msg.length - cursor);
586 msg.length = cursor;
587 } break;
588 case 't' & ~0x60: {
589 if (cursor == base_msg_length)
590 break;
591
592 if (cursor == msg.length) {
593 if (msg.length - base_msg_length < 2)
594 break;
595
596 char tmp = msg.data[cursor - 2];
597 msg.data[cursor - 2] = msg.data[cursor - 1];
598 msg.data[cursor - 1] = tmp;
599 break;
600 }
601
602 char tmp = msg.data[cursor - 1];
603 msg.data[cursor - 1] = msg.data[cursor + 0];
604 msg.data[cursor + 0] = tmp;
605 cursor += 1;
606 } break;
607 case 'y' & ~0x60: {
608 int count = msg.length + kill_ring.count > MAX_MESSAGE_LENGTH
609 ? MAX_MESSAGE_LENGTH - msg.length : kill_ring.count;
610 memmove (msg.data + cursor + count,
611 msg.data + cursor, msg.length - cursor);
612 memcpy (msg.data + cursor, kill_ring.items, count);
613 msg.length += count;
614 cursor += count;
615 } break;
616 case '\e':
617 timeout (100);
618 nodelay (stdscr, FALSE);
619 switch (getch ()) {
620 case 'b': {
621 while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1;
622 while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1;
623 } break;
624 case 'f': {
625 while (msg.data[cursor] == ' ' && cursor < msg.length) cursor += 1;
626 while (msg.data[cursor] != ' ' && cursor < msg.length) cursor += 1;
627 } break;
628 case KEY_BACKSPACE:
629 case 'h': {
630 int to = cursor;
631 while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1;
632 while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1;
633 kill (msg.data + cursor, to - cursor);
634 memmove (&msg.data[cursor], &msg.data[to], msg.length - to);
635 msg.length -= to - cursor;
636 } break;
637 case 'd': {
638 int to = cursor;
639 while (msg.data[to] == ' ' && to < msg.length) to += 1;
640 while (msg.data[to] != ' ' && to < msg.length) to += 1;
641 kill (msg.data + cursor, to - cursor);
642 memmove (&msg.data[cursor], &msg.data[to], msg.length - to);
643 msg.length -= to - cursor;
644 } break;
645 case 'v': {
646 scroll += maxy/2;
647 if (scroll >= history.count - 1)
648 scroll = history.count - 1;
649 } break;
650 // TODO(cmmm): M+t
651 }
652 nodelay (stdscr, TRUE);
653 break;
654 }
655
656 kill_ring.active &= kill_ring.killed;
657 }
658 }
659 }
660
661 erase ();
662 getmaxyx (stdscr, maxy, maxx);
663 int y = maxy - 3;
664 for (uint32_t i = history.count - scroll; y >= 0 && i > 0; y -= 1) {
665 i -= 1;
666 color_set (history.items[i].color_pair, NULL);
667 mvaddstr (y, 0, history.items[i].message);
668 } color_set (COLOR_NORMAL, NULL);
669 mvhline (maxy - 2, 0, 0, maxx);
670 mvaddnstr (maxy - 1, 0, msg.data, msg.length);
671 if (scroll) {
672 int width = snprintf (NULL, 0, "[%u/%u]", scroll + 1, history.count);
673 mvprintw (0, maxx - width, "[%u/%u]", scroll + 1, history.count);
674 }
675 move (maxy - 1, cursor);
676 refresh ();
677 }
678
679 endwin ();
680
681 return EXIT_SUCCESS;
682}
683
684// 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 @@
1// common.c --- shared between client and server
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#include "common.h"
12#include "utils.h"
13
14bool
15load_aes_256_key (aes_256_key key, const char *filename)
16{
17 FILE *stream = fopen (filename, "r");
18 if (stream == NULL)
19 return false;
20
21 // TODO(cmmm): handle wrong format better...
22 int assignments = 0;
23 for (int i = 0; i < AES_256_KEY_SIZE; ++i)
24 assignments += fscanf (stream, "%02hhx", &key[i]);
25 fclose (stream);
26
27 return assignments == AES_256_KEY_SIZE;
28}
29
30void
31print_hex (uint8_t *data, size_t size)
32{
33 for (size_t i = 0; i < size; ++i) {
34 if (i && i % 2 == 0) printf (" ");
35 printf ("%02x", data[i]);
36 } printf ("\n");
37}
38
39// 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 @@
1// common.h --- shared between client and server
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#ifndef INCLUDED_COMMON_H
12#define INCLUDED_COMMON_H
13
14#include "stdint.h"
15#include "crypto.h"
16
17struct packet {
18 uint8_t size;
19 uint8_t data[];
20};
21#define MAX_PACKET_SIZE (256 - sizeof (struct packet))
22
23#define MAX_MESSAGE_LENGTH 80
24struct message {
25 char length;
26 char data[MAX_MESSAGE_LENGTH];
27};
28
29enum key_kind {
30 KK_NONE,
31 KK_PSK,
32 KK_DHKX,
33};
34
35bool load_aes_256_key (aes_256_key, const char *filename);
36void print_hex (uint8_t *data, size_t size);
37
38#endif // INCLUDED_COMMON_H
39
40// 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 @@
1// crypto.c --- cryptography utilities
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#include "crypto.h"
12
13#include <openssl/evp.h>
14#include <openssl/kdf.h>
15#include <openssl/err.h>
16#include <openssl/rand.h>
17#include <openssl/crypto.h>
18#include <openssl/core_names.h>
19
20#include "common.h"
21
22static EVP_PKEY *pkey_local = NULL;
23static EVP_PKEY_CTX *pkey_derive_ctx = NULL;
24
25uint8_t local_pubkey[X25519_PUBKEY_LEN];
26
27static EVP_MD *md_sha1 = NULL;
28static EVP_MD_CTX *md_sha1_ctx = NULL;
29
30static EVP_KDF *hkdf = NULL;
31static EVP_KDF_CTX *hkdf_ctx = NULL;
32
33static EVP_CIPHER *cipher_aes_cbc = NULL;
34static EVP_CIPHER_CTX *cipher_ctx = NULL;
35
36bool
37crypto_init (void)
38{
39 EVP_PKEY_CTX *pkey_gen_ctx =
40 EVP_PKEY_CTX_new_from_name (NULL, "X25519", NULL);
41 if (pkey_gen_ctx == NULL) goto error;
42
43 if (EVP_PKEY_keygen_init (pkey_gen_ctx) <= 0) {
44 EVP_PKEY_CTX_free (pkey_gen_ctx);
45 goto error;
46 }
47
48 if (EVP_PKEY_keygen (pkey_gen_ctx, &pkey_local) <= 0) {
49 EVP_PKEY_CTX_free (pkey_gen_ctx);
50 goto error;
51 } EVP_PKEY_CTX_free (pkey_gen_ctx);
52
53 pkey_derive_ctx = EVP_PKEY_CTX_new_from_pkey (NULL, pkey_local, NULL);
54 if (pkey_derive_ctx == NULL) goto error;
55
56 size_t len;
57 if (EVP_PKEY_get_raw_public_key (pkey_local, local_pubkey, &len) <= 0)
58 goto error;
59 if (len != X25519_PUBKEY_LEN) goto error_pkey_derive_ctx;
60
61 md_sha1 = EVP_MD_fetch (NULL, "SHA-1", NULL);
62 if (md_sha1 == NULL) goto error_pkey_derive_ctx;
63
64 md_sha1_ctx = EVP_MD_CTX_new ();
65 if (md_sha1_ctx == NULL) goto error_md_sha1;
66
67 if (!EVP_DigestInit_ex2 (md_sha1_ctx, md_sha1, NULL))
68 goto error_md_sha1_ctx;
69
70 hkdf = EVP_KDF_fetch (NULL, "HKDF", NULL);
71 if (!hkdf) goto error_md_sha1_ctx;
72
73 hkdf_ctx = EVP_KDF_CTX_new (hkdf);
74 if (!hkdf_ctx) goto error_hkdf;
75
76 cipher_aes_cbc = EVP_CIPHER_fetch (NULL, "AES-256-CBC", NULL);
77 if (cipher_aes_cbc == NULL) goto error_hkdf_ctx;
78
79 cipher_ctx = EVP_CIPHER_CTX_new ();
80 if (cipher_ctx == NULL) goto error_cipher_aes_cbc;
81
82 return true;
83
84 error_cipher_aes_cbc:
85 EVP_CIPHER_free (cipher_aes_cbc);
86 error_hkdf_ctx:
87 EVP_KDF_CTX_free (hkdf_ctx);
88 error_hkdf:
89 EVP_KDF_free (hkdf);
90 error_pkey_derive_ctx:
91 EVP_PKEY_CTX_free (pkey_derive_ctx);
92 error_md_sha1_ctx:
93 EVP_MD_CTX_free (md_sha1_ctx);
94 error_md_sha1:
95 EVP_MD_free (md_sha1);
96 error:
97 ERR_print_errors_fp (stderr);
98 return false;
99}
100
101ssize_t
102sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in)
103{
104 unsigned int length;
105
106 if (EVP_DigestInit_ex2 (md_sha1_ctx, NULL, NULL) != 1) goto error;
107 if (EVP_DigestUpdate (md_sha1_ctx, in.data, in.size) != 1) goto error;
108 if (EVP_DigestFinal_ex (md_sha1_ctx, out, &length) != 1) goto error;
109
110 return length;
111
112 error:
113 ERR_reason_error_string (ERR_get_error ());
114 return -1;
115}
116
117bool
118hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out)
119{
120 EVP_PKEY *peer_pkey =
121 EVP_PKEY_new_raw_public_key_ex (NULL, "X25519", NULL,
122 peer_pubkey, X25519_PUBKEY_LEN);
123 if (peer_pkey == NULL) goto error;
124
125 if (EVP_PKEY_derive_init (pkey_derive_ctx) <= 0)
126 goto error;
127 if (EVP_PKEY_derive_set_peer (pkey_derive_ctx, peer_pkey) <= 0)
128 goto error;
129
130 size_t ikm_len = 0;
131 if (EVP_PKEY_derive (pkey_derive_ctx, NULL, &ikm_len) <= 0) goto error;
132
133 uint8_t *ikm = OPENSSL_malloc (ikm_len);
134 if (!ikm) goto error;
135
136 if (EVP_PKEY_derive (pkey_derive_ctx, ikm, &ikm_len) <= 0) goto error;
137 EVP_PKEY_free (peer_pkey);
138
139 uint8_t salt[] = { 0xcd };
140 size_t salt_len = sizeof (salt);
141 uint8_t info[] = { 0xcd };
142 size_t info_len = sizeof (info);
143
144 OSSL_PARAM params[] = {
145 OSSL_PARAM_construct_utf8_string (OSSL_KDF_PARAM_DIGEST, "SHA256", 0),
146 OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_KEY, (void *) ikm, ikm_len),
147 OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_SALT, (void *) salt, salt_len),
148 OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_INFO, (void *) info, info_len),
149 OSSL_PARAM_construct_end (),
150 };
151
152 EVP_KDF_CTX_reset (hkdf_ctx);
153 if (EVP_KDF_derive (hkdf_ctx, out, AES_256_KEY_SIZE, params) <= 0)
154 goto error;
155 OPENSSL_free (ikm);
156
157 return true;
158
159 error:
160 EVP_PKEY_free (peer_pkey);
161 OPENSSL_free (ikm);
162 ERR_print_errors_fp (stderr);
163 return false;
164}
165
166ssize_t
167aes_256_cbc_encrypt (struct memory_span out,
168 struct memory_view in, const aes_256_key key, bool salt)
169{
170 ASSERT (out.size >= AES_IV_SIZE + in.size + AES_BLOCK_SIZE - 1);
171
172 uint8_t *head = out.data;
173
174 uint8_t *iv = NULL;
175 if (salt) {
176 iv = head;
177 if (RAND_bytes (iv, AES_IV_SIZE) != 1)
178 goto error;
179 head += AES_IV_SIZE;
180 }
181
182 if (!EVP_CIPHER_CTX_reset (cipher_ctx))
183 goto error;
184
185 if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1)
186 goto error;
187
188 int bytes_written = 0;
189 if (EVP_EncryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1)
190 goto error;
191 head += bytes_written;
192
193 if (EVP_EncryptFinal_ex (cipher_ctx, head, &bytes_written) != 1)
194 goto error;
195 head += bytes_written;
196
197 return head - out.data;
198
199error:
200 ERR_print_errors_fp (stderr);
201 return -1;
202}
203
204ssize_t
205aes_256_cbc_decrypt (struct memory_span out,
206 struct memory_view in, const aes_256_key key, bool salt)
207{
208 uint8_t *head = out.data;
209
210 const uint8_t *iv = NULL;
211 if (salt) {
212 const uint8_t *iv = in.data;
213 in.data += AES_IV_SIZE;
214 in.size -= AES_IV_SIZE;
215 }
216
217 if (!EVP_CIPHER_CTX_reset (cipher_ctx))
218 goto error;
219
220 if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1)
221 goto error;
222
223 int bytes_written = 0;
224 if (EVP_DecryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1)
225 goto error;
226 head += bytes_written;
227
228 if (EVP_DecryptFinal_ex (cipher_ctx, head, &bytes_written) != 1)
229 goto error;
230 head += bytes_written;
231
232 return head - out.data;
233
234error:
235 // ERR_print_errors_fp (stderr);
236 return -1;
237}
238
239// 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 @@
1// crypto.h --- cryptography utilities
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#ifndef INCLUDED_CRYPTO_H
12#define INCLUDED_CRYPTO_H
13
14#include <stdint.h>
15#include <stdbool.h>
16
17#include "utils.h"
18
19#define X25519_PUBKEY_LEN 32
20#define SHA_DIGEST_SIZE 20
21#define AES_256_KEY_SIZE 32
22#define AES_BLOCK_SIZE 16
23#define AES_IV_SIZE 16
24
25typedef uint8_t aes_256_key[AES_256_KEY_SIZE];
26
27extern uint8_t local_pubkey[X25519_PUBKEY_LEN];
28
29bool crypto_init (void);
30ssize_t sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in);
31bool hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out);
32ssize_t aes_256_cbc_encrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt);
33ssize_t aes_256_cbc_decrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt);
34
35#endif // INCLUDED_CRYPTO_H
36
37// 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 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include <stdlib.h>
5#include <assert.h>
6
7#define MALLOC malloc
8#define REALLOC realloc
9#define FREE free
10#define ASSERT assert
11
12#ifndef DYNAMIC_ARRAY_INIT_CAP
13#define DYNAMIC_ARRAY_INIT_CAP 256
14#endif
15
16#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
17 ({ \
18 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
19 if ((DYNAMIC_ARRAY).capacity == 0) \
20 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
21 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
22 (DYNAMIC_ARRAY).capacity *= 2; \
23 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
24 (DYNAMIC_ARRAY).capacity * \
25 sizeof (*(DYNAMIC_ARRAY).items)); \
26 ASSERT((DYNAMIC_ARRAY).items); \
27 } \
28 })
29
30#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
31 ({ \
32 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
33 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
34 (DYNAMIC_ARRAY).capacity * \
35 sizeof (*(DYNAMIC_ARRAY).items)); \
36 ASSERT((DYNAMIC_ARRAY).items); \
37 \
38 })
39
40#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
43 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
44 })
45
46#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
47 ({ \
48 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
49 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
50 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
51 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
52 })
53
54#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
55 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
56
57#define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \
58 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--]
59
60#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
61
62#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
63
64#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
65 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
66 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
67
68#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 @@
1int
2aes256_gcm_encrypt (const uint8_t *plaintext, int plaintext_len,
3 const uint8_t *aad, int aad_len,
4 const uint8_t key[AES_256_KEY_SIZE],
5 const uint8_t *nonce, int nonce_len,
6 uint8_t *ciphertext,
7 uint8_t tag[GCM_TAG_SIZE])
8{
9 int len = 0;
10 int ciphertext_len = 0;
11 int ok = 0;
12
13 if (!EVP_CIPHER_CTX_reset (cipher_ctx)) {
14 ERR_print_errors_fp (stderr);
15 return -1;
16 }
17
18 if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) {
19 ERR_print_errors_fp (stderr);
20 return -1;
21 }
22
23 /*
24 Set nonce length before setting key/nonce if using a non-default length.
25 For GCM, 12 bytes is the common default and recommended size.
26 */
27 if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN,
28 nonce_len, NULL) != 1) {
29 ERR_print_errors_fp (stderr);
30 return -1;
31 }
32
33 if (EVP_EncryptInit_ex (cipher_ctx, NULL, NULL, key, nonce) != 1) {
34 ERR_print_errors_fp (stderr);
35 return -1;
36 }
37
38 /*
39 AAD is authenticated but not encrypted.
40 Pass out=NULL for AAD.
41 */
42 if (aad != NULL && aad_len > 0) {
43 if (EVP_EncryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) {
44 ERR_print_errors_fp (stderr);
45 return -1;
46 }
47 }
48
49 if (EVP_EncryptUpdate (cipher_ctx, ciphertext, &len,
50 plaintext, plaintext_len) != 1) {
51 ERR_print_errors_fp (stderr);
52 return -1;
53 }
54 ciphertext_len = len;
55
56 /*
57 Final for GCM typically produces no extra ciphertext bytes, but it must
58 still be called.
59 */
60 if (EVP_EncryptFinal_ex (cipher_ctx, ciphertext + ciphertext_len, &len) != 1) {
61 ERR_print_errors_fp (stderr);
62 return -1;
63 }
64 ciphertext_len += len;
65
66 /*
67 Get the authentication tag.
68 */
69 if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_GET_TAG,
70 GCM_TAG_SIZE, tag) != 1) {
71 ERR_print_errors_fp (stderr);
72 return -1;
73 }
74
75 return ciphertext_len;
76}
77
78int aes256_gcm_decrypt (const uint8_t *ciphertext, int ciphertext_len,
79 const uint8_t *aad, int aad_len,
80 const uint8_t tag[GCM_TAG_SIZE],
81 const uint8_t key[AES_256_KEY_SIZE],
82 const uint8_t *nonce, int nonce_len,
83 uint8_t *plaintext)
84{
85 int len = 0;
86 int plaintext_len = 0;
87 int ret = -1;
88
89 if (EVP_CIPHER_CTX_reset (cipher_ctx)) {
90 ERR_print_errors_fp (stderr);
91 return -1;
92 }
93
94 if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) {
95 ERR_print_errors_fp (stderr);
96 return -1;
97 }
98
99 if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN,
100 nonce_len, NULL) != 1) {
101 ERR_print_errors_fp (stderr);
102 return -1;
103 }
104
105 if (EVP_DecryptInit_ex2 (cipher_ctx, NULL, key, nonce, NULL) != 1) {
106 ERR_print_errors_fp (stderr);
107 return -1;
108 }
109
110 if (aad != NULL && aad_len > 0) {
111 if (EVP_DecryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) {
112 ERR_print_errors_fp (stderr);
113 return -1;
114 }
115 }
116
117 if (EVP_DecryptUpdate (cipher_ctx, plaintext, &len,
118 ciphertext, ciphertext_len) != 1) {
119 ERR_print_errors_fp (stderr);
120 return -1;
121 }
122 plaintext_len = len;
123
124 /*
125 Set expected tag before finalizing.
126 */
127 if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_TAG,
128 GCM_TAG_SIZE, (void *)tag) != 1) {
129 ERR_print_errors_fp (stderr);
130 return -1;
131 }
132
133 /*
134 Success only if tag verification passes.
135 */
136 if (EVP_DecryptFinal_ex (cipher_ctx, plaintext + plaintext_len, &len) != 1) {
137 ERR_print_errors_fp (stderr);
138 return -1;
139 }
140 plaintext_len += len;
141
142 return plaintext_len;
143}
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 @@
1// server.c --- server component
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#include <stdlib.h>
12#include <stdbool.h>
13#include <stdio.h>
14#include <string.h>
15#include <errno.h>
16#include <getopt.h>
17#include <libgen.h>
18#include <unistd.h>
19#include <fcntl.h>
20#include <sys/epoll.h>
21#include <netinet/in.h>
22#include <arpa/inet.h>
23
24#define LOG(PRIORITY, FMT, ...) \
25 syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \
26 FMT __VA_OPT__ (,) __VA_ARGS__)
27
28#include "utils.h"
29#include "common.h"
30#include "crypto.h"
31#include "dynamic-array.h"
32
33#define MAX_EVENTS 5
34
35static bool should_stop = false;
36
37static bool salt = false;
38static bool echo = false;
39static bool check_integrity = false;
40static bool bad_line = false;
41static char *key_filename = NULL;
42static enum key_kind key_kind = KK_PSK;
43static aes_256_key key;
44
45struct client {
46 struct client *prev;
47 struct client *next;
48 struct sockaddr_in sin;
49 aes_256_key key;
50 int fd;
51 enum client_state {
52 CS_READY,
53 CS_WAITING_FOR_PUBKEY,
54 } state;
55};
56
57static struct client *clients = NULL;
58static struct client *client_free_list = NULL;
59
60static int epoll_fd;
61
62void
63accept_connections (int fd)
64{
65 again:
66 if (client_free_list == NULL)
67 client_free_list = calloc (1, sizeof (*client_free_list));
68 struct client *client = client_free_list;
69
70 socklen_t length = sizeof (client->sin);
71 client->fd = accept (fd, (struct sockaddr *) &client->sin, &length);
72 if (client->fd == -1) {
73 if (errno == EWOULDBLOCK) return;
74 ERROR ("Failed to accept connection: %s", strerror (errno));
75 goto again;
76 } NOTICE ("Accepted connection from " SOCKADDR_IN_FMT,
77 SOCKADDR_IN_SPLIT (client->sin));
78
79 if (fcntl (client->fd, F_SETFL, O_NONBLOCK) == -1) {
80 ERROR ("Failed to set nonblocking mode for client socket: %s",
81 strerror (errno));
82 }
83
84 struct epoll_event event;
85 event.events = EPOLLIN | EPOLLWAKEUP;
86 event.data.ptr = client;
87 if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, client->fd, &event)) {
88 ERROR ("Failed to add file descriptor to epoll: %s", strerror (errno));
89 close (client->fd);
90 goto again;
91 }
92
93 client_free_list = client_free_list->next;
94 if (clients)
95 clients->prev = client;
96 client->next = clients;
97 client->prev = NULL;
98 clients = client;
99
100 if (key_kind == KK_DHKX) {
101 write (client->fd, local_pubkey, sizeof (local_pubkey));
102 client->state = CS_WAITING_FOR_PUBKEY;
103 } else {
104 client->state = CS_READY;
105 }
106
107 goto again;
108}
109
110void
111close_connection (struct client *client)
112{
113 INFO ("Connection closed " SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (client->sin));
114 if (epoll_ctl (epoll_fd, EPOLL_CTL_DEL, client->fd, NULL))
115 ERROR ("Failed to del file descriptor from epoll: %s", strerror (errno));
116 close (client->fd);
117
118 if (client->prev) client->prev->next = client->next;
119 if (client->next) client->next->prev = client->prev;
120 if (client == clients) clients = client->next;
121 client->next = client_free_list;
122 client_free_list = client;
123}
124
125bool
126send_to_plain (struct memory_view mv, struct client *to)
127{
128 uint8_t buffer[MAX_PACKET_SIZE];
129 memcpy (buffer, mv.data, mv.size);
130 size_t size = mv.size;
131 if (check_integrity) {
132 uint8_t hash[SHA_DIGEST_SIZE];
133 sha1_hash (hash, mv);
134 if (bad_line) {
135 for (int i = 0; i < SHA_DIGEST_SIZE; ++i)
136 hash[i] += i;
137 }
138 memcpy (&buffer[size], hash, sizeof (hash));
139 size += sizeof (hash);
140 }
141
142 again:
143 ssize_t bytes_written = write (to->fd, buffer, size);
144 if (bytes_written == -1) {
145 switch (errno) {
146 case EAGAIN: goto again;
147 default:
148 ERROR (SOCKADDR_IN_FMT ": write: %s",
149 SOCKADDR_IN_SPLIT (to->sin), strerror (errno));
150 } return false;
151 }
152
153 if (bytes_written == 0) {
154 return false;
155 }
156
157 if ((size_t) bytes_written != size) {
158 ERROR (SOCKADDR_IN_FMT ": Failed to write whole buffer",
159 SOCKADDR_IN_SPLIT (to->sin));
160 return false;
161 }
162
163 return true;
164}
165
166bool
167send_to_encrypted (struct memory_view msg_mv, struct client *to)
168{
169 static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE];
170 struct packet *packet = (void *) buffer;
171 struct memory_span packet_ms = {
172 .data = packet->data,
173 .size = MAX_PACKET_SIZE - sizeof (packet->size),
174 };
175 ssize_t size =
176 aes_256_cbc_encrypt (packet_ms, msg_mv,
177 key_kind == KK_PSK ? key : to->key, salt);
178 if (size == -1)
179 return false;
180 packet->size = size;
181
182 struct memory_view packet_mv = {
183 .data = (void *) packet,
184 .size = sizeof (packet->size) + packet->size,
185 };
186 return send_to_plain (packet_mv, to);
187}
188
189bool
190send_message_to (const struct message *msg, struct client *to)
191{
192 INFO ("Sending message to " SOCKADDR_IN_FMT ": %.*s",
193 SOCKADDR_IN_SPLIT (to->sin), (int) msg->length, msg->data);
194
195 bool ret;
196 if (key_kind == KK_NONE) {
197 struct memory_view mv = {
198 .data = (void *) msg,
199 .size = sizeof (msg->length) + msg->length,
200 };
201 ret = send_to_plain (mv, to);
202 } else {
203 struct memory_view mv = {
204 .data = (void *) msg->data,
205 .size = msg->length,
206 };
207 ret = send_to_encrypted (mv, to);
208 }
209
210 INFO ("%s message to " SOCKADDR_IN_FMT,
211 ret ? "Sent" : "Failed to send", SOCKADDR_IN_SPLIT (to->sin));
212 if (!ret)
213 close_connection (to);
214
215 return ret;
216}
217
218void
219broadcast (const struct message *msg, const struct client *except)
220{
221 struct client *next;
222 for (struct client *client = clients; client; client = next) {
223 if (client == except)
224 continue;
225
226 next = client->next;
227 send_message_to (msg, client);
228 }
229}
230
231// FIXME(cmmm): don't expect to read whole (and sole) packet at once...
232bool
233handle_client (struct client *client)
234{
235 static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE];
236 struct packet *packet = (void *) buffer;
237
238 again:
239 switch (client->state) {
240 case CS_READY: {
241 ssize_t bytes_read = read (client->fd, packet, sizeof (*packet));
242 if (bytes_read == -1) {
243 switch (errno) {
244 case EAGAIN: return true;
245 default:
246 ERROR (SOCKADDR_IN_FMT ": read: %s",
247 SOCKADDR_IN_SPLIT (client->sin), strerror (errno));
248 } return false;
249 }
250
251 if (bytes_read == 0)
252 return false;
253
254 if (bytes_read != sizeof (*packet)) {
255 ERROR ("Received malformed message from " SOCKADDR_IN_FMT,
256 SOCKADDR_IN_SPLIT (client->sin));
257 DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read);
258 return false;
259 }
260
261 bytes_read = read (client->fd, packet->data, packet->size);
262 if (bytes_read == -1) {
263 ERROR (SOCKADDR_IN_FMT ": read: %s",
264 SOCKADDR_IN_SPLIT (client->sin), strerror (errno));
265 return false;
266 }
267
268 if (bytes_read == 0)
269 return false;
270
271 if ((size_t) bytes_read != packet->size) {
272 ERROR ("Received malformed message from " SOCKADDR_IN_FMT,
273 SOCKADDR_IN_SPLIT (client->sin));
274 DEBUG ("expected %hhu, received %ld", packet->size, bytes_read);
275 return false;
276 }
277
278 if (check_integrity) {
279 uint8_t hash1[SHA_DIGEST_SIZE];
280 uint8_t hash2[SHA_DIGEST_SIZE];
281
282 bytes_read = read (client->fd, hash1, sizeof (hash1));
283 if (bytes_read == -1) {
284 ERROR (SOCKADDR_IN_FMT ": read: %s",
285 SOCKADDR_IN_SPLIT (client->sin), strerror (errno));
286 return false;
287 }
288
289 if (bytes_read == 0)
290 return false;
291
292 if ((size_t) bytes_read != sizeof (hash1)) {
293 ERROR ("Received malformed message from " SOCKADDR_IN_FMT,
294 SOCKADDR_IN_SPLIT (client->sin));
295 DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read);
296 return false;
297 }
298
299 struct memory_view mv = {
300 .data = (void *) packet,
301 .size = sizeof (*packet) + packet->size,
302 };
303 sha1_hash (hash2, mv);
304 if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) {
305 WARNING ("Received wrong hash from " SOCKADDR_IN_FMT,
306 SOCKADDR_IN_SPLIT (client->sin));
307 goto again;
308 }
309 }
310
311 if (key_kind == KK_NONE) {
312 const struct message *msg = (void *) packet;
313 INFO ("Received plain text message from " SOCKADDR_IN_FMT ": %.*s",
314 SOCKADDR_IN_SPLIT (client->sin), (int) msg->length, msg->data);
315 broadcast (msg, echo ? NULL : client);
316 } else {
317 static struct message msg;
318 struct memory_span plain_ms = {
319 .data = (void *) &msg.data,
320 .size = sizeof (msg.data),
321 };
322 struct memory_view enc_mv = {
323 .data = packet->data,
324 .size = packet->size,
325 };
326 ssize_t size =
327 aes_256_cbc_decrypt (plain_ms, enc_mv,
328 key_kind == KK_PSK ? key : client->key, salt);
329 if (size == -1) {
330 ERROR ("Failed to decrypt received message from " SOCKADDR_IN_FMT,
331 SOCKADDR_IN_SPLIT (client->sin));
332 return false;
333 }
334 msg.length = size;
335 INFO ("Received encrypted message from " SOCKADDR_IN_FMT ": %.*s",
336 SOCKADDR_IN_SPLIT (client->sin), (int) msg.length, msg.data);
337 broadcast (&msg, echo ? NULL : client);
338 }
339
340 } break;
341 case CS_WAITING_FOR_PUBKEY: {
342 if (read (client->fd, buffer, X25519_PUBKEY_LEN) != X25519_PUBKEY_LEN) {
343 ERROR ("Received public key of wrong size from " SOCKADDR_IN_FMT,
344 SOCKADDR_IN_SPLIT (client->sin));
345 return false;
346 }
347
348 if (!hkdf_sha256 (buffer, client->key)) {
349 ERROR ("Failed to make shared key for " SOCKADDR_IN_FMT,
350 SOCKADDR_IN_SPLIT (client->sin));
351 return false;
352 }
353
354 NOTICE ("Shared key established with " SOCKADDR_IN_FMT,
355 SOCKADDR_IN_SPLIT (client->sin));
356 client->state = CS_READY;
357 return true;
358 } break;
359 default: break;
360 }
361
362 goto again;
363}
364
365void
366usage (FILE *stream, const char *progname)
367{
368 fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname);
369 fprintf (stream, "\n");
370 fprintf (stream, "Options:\n");
371 fprintf (stream, " -h, --help display this help message and exit\n");
372 fprintf (stream, " -e, --echo send messages to sender as well\n");
373 fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n");
374 fprintf (stream, " -p, --plain don't use encryption*\n");
375 fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n");
376 fprintf (stream, " -c, --check-integrity use message integrity checking*\n");
377 fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n");
378 fprintf (stream, "\n");
379 fprintf (stream, "Notes:\n");
380 fprintf (stream, " Options marked with (*) must match the ones use by the clients!\n");
381 fprintf (stream, "\n");
382}
383
384void
385test_aes_256_cbc (void)
386{
387 const char *data = "Hello, World!";
388 puts (data);
389 struct memory_view mv = {
390 .data = (void *) data,
391 .size = strlen (data),
392 };
393
394 static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE];
395 struct memory_span ms = {
396 .data = buffer,
397 .size = sizeof (buffer),
398 };
399
400 size_t size;
401 size = aes_256_cbc_encrypt (ms, mv, key, salt);
402 for (size_t i = 0; i < size; ++i) {
403 printf ("%02hhx ", ms.data[i]);
404 if ((i + 1) % 8 == 0) printf ("\n");
405 }
406
407 mv.data = ms.data;
408 mv.size = ms.size;
409 size = aes_256_cbc_decrypt (ms, mv, key, salt);
410 printf ("%.*s\n", (int) ms.size, ms.data);
411}
412
413int
414main (int argc, char *argv[])
415{
416 char *progname = argv[0];
417
418 struct option longopts[] = {
419 { "help", no_argument, NULL, 'h' },
420 { "echo", no_argument, NULL, 'e' },
421 { "plain", no_argument, NULL, 'p' },
422 { "key", required_argument, NULL, 'k' },
423 { "salt", no_argument, NULL, 's' },
424 { "key-exchange", no_argument, NULL, 'x' },
425 { "check-integrity", no_argument, NULL, 'c' },
426 { "bad-hash", no_argument, NULL, 'b' },
427 {0}
428 };
429 char ch;
430 while ((ch = getopt_long (argc, argv, ":hepk:sxcb", longopts, NULL)) != -1) {
431 switch (ch) {
432 case 'h':
433 usage (stdout, progname);
434 exit (EXIT_SUCCESS);
435 case 'e': echo = true; break;
436 case 'p': key_kind = KK_NONE; break;
437 case 'k': key_kind = KK_PSK; key_filename = optarg; break;
438 case 's': salt = true; break;
439 case 'x': key_kind = KK_DHKX; break;
440 case 'c': check_integrity = true; break;
441 case 'b': bad_line = true; break;
442 case '?': DIE ("unknown option %s", argv[optind - 1]);
443 case ':': DIE ("missing argument for %s", argv[optind - 1]);
444 default: DIE ("unexpected opt error");
445 }
446 }
447
448 if (argc - optind != 2) {
449 usage (stderr, progname);
450 exit (EXIT_FAILURE);
451 }
452
453 setlogmask (LOG_UPTO (LOG_DEBUG));
454 // openlog (basename (progname), LOG_PID | LOG_PERROR, LOG_DAEMON);
455 openlog (basename (progname), LOG_PERROR, LOG_DAEMON);
456
457 if (salt && key_kind == KK_NONE)
458 DIE ("Using --salt doesn't make sense with --plain");
459
460 if (key_kind == KK_PSK) {
461 if (!key_filename)
462 DIE ("When using PSK (the default), you need to specify --key");
463
464 if (!load_aes_256_key (key, key_filename))
465 DIE ("Unable to load AES-256 key from '%s': %s",
466 key_filename, strerror (errno));
467 }
468
469 const char *addr = argv[optind + 0];
470 char *tail = NULL;
471 unsigned long int port = strtoul (argv[optind + 1], &tail, 10);
472 if (!tail || *tail != '\0')
473 DIE ("Failed to parse port");
474
475 struct sockaddr_in sin = {
476 .sin_family = AF_INET,
477 .sin_port = htons (port),
478 };
479 if (!inet_aton (addr, &sin.sin_addr))
480 DIE ("Failed to convert address %s", addr);
481
482 if (!crypto_init ())
483 DIE ("Failed to initialize crypto");
484
485 epoll_fd = epoll_create1 (0);
486 if (epoll_fd == -1)
487 DIE ("Failed to create epoll file descriptor: %s", strerror (errno));
488
489 int listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
490 if (listener == -1)
491 DIE ("Failed to create socket: %s", strerror (errno));
492
493 struct epoll_event event;
494 event.events = EPOLLIN | EPOLLWAKEUP;
495 event.data.ptr = NULL;
496 if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, listener, &event))
497 DIE ("Failed to add file descriptor to epoll: %s", strerror (errno));
498
499 int reuseaddr = 1;
500 setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
501 &reuseaddr, sizeof (reuseaddr));
502
503 if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) {
504 ERROR ("Failed to set nonblocking mode for listener socket: %s",
505 strerror (errno));
506 }
507
508 if (bind (listener, (struct sockaddr *) &sin, sizeof (sin)) == -1) {
509 DIE ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s",
510 SOCKADDR_IN_SPLIT (sin), strerror (errno));
511 }
512
513 if (listen (listener, 2)) {
514 DIE ("Failed to listen on "SOCKADDR_IN_FMT": %s",
515 SOCKADDR_IN_SPLIT (sin), strerror (errno));
516 } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (sin));
517
518 NOTICE ("Server started...");
519 while (!should_stop) {
520 DEBUG ("Polling...");
521 struct epoll_event events[MAX_EVENTS];
522 int event_count = epoll_wait (epoll_fd, events, MAX_EVENTS, -1);
523 DEBUG ("Got %d event%s", event_count, event_count > 1 ? "s" : "");
524 for (int i = 0; i < event_count; ++i) {
525 if (events[i].data.ptr == NULL) {
526 accept_connections (listener);
527 continue;
528 }
529
530 if (!handle_client (events[i].data.ptr))
531 close_connection (events[i].data.ptr);
532 }
533 }
534
535 NOTICE ("Server stopped...");
536 return EXIT_SUCCESS;
537}
538
539// 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 @@
1// utils.h --- utilities
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#ifndef INCLUDED_UTILS_H
12#define INCLUDED_UTILS_H
13
14#include <stdarg.h>
15#include <stdlib.h>
16#include <stdio.h>
17#include <assert.h>
18#include <syslog.h>
19
20#define STRINGIFY(ARG) #ARG
21#define TO_STRING(ARG) STRINGIFY (ARG)
22#define DEBUG( FMT, ...) \
23 LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__)
24#define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__)
25#define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__)
26#define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__)
27#define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__)
28#define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__)
29#define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__)
30#define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__)
31
32#define DIE(FMT, ...) do { \
33 EMERGENCY (FMT __VA_OPT__ (,) __VA_ARGS__); \
34 exit (EXIT_FAILURE); \
35 } while (0)
36
37#define UNUSED(X) ((void) (X))
38#define UNREACHABLE() ASSERT (!"reached the unreachable...")
39#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__)
40// #define TODO(...)
41#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
42
43#define MALLOC malloc
44#define REALLOC realloc
45#define FREE free
46#define ASSERT assert
47
48#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
49
50#define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu"
51#define SOCKADDR_IN_SPLIT(ADDR) \
52 ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \
53 ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \
54 ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \
55 ntohl ((ADDR).sin_addr.s_addr) >> 0*8, ntohs ((ADDR).sin_port)
56
57inline uint8_t
58log10u8 (uint8_t n)
59{
60 return (n >= 100 ? 3 :
61 n >= 10 ? 2 : 1);
62}
63
64// read-only borrowed
65struct memory_view {
66 const unsigned char *data;
67 size_t size;
68};
69
70// writable borrowed
71struct memory_span {
72 unsigned char *data;
73 size_t size;
74};
75
76// writable owning
77struct memory_buffer {
78 unsigned char *data;
79 size_t size;
80};
81
82#define MEMORY_SPAN_TO_MEMORY_VIEW(MS) \
83 ((struct memory_view) { \
84 .data = (MS).data, \
85 .size = (MS).size, \
86 })
87
88#endif
89
90// utils.h ends here