1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
|
// client.c --- client component
//
// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
//
// SPDX-License-Identifier: MIT
//
// Commentary:
//
// Code:
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <getopt.h>
#include <unistd.h>
#include <fcntl.h>
#include <ncurses.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#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
|