aboutsummaryrefslogtreecommitdiff
path: root/05/src/client.c
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/client.c
downloadlab-01-05-master.tar.gz
publishHEADmaster
Diffstat (limited to '05/src/client.c')
-rw-r--r--05/src/client.c684
1 files changed, 684 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