/
a12.c
3462 lines (2969 loc) · 97.6 KB
/
a12.c
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright: Björn Ståhl
* Description: A12 protocol state machine, main translation unit.
* Maintains connection state, multiplex and demultiplex then routes
* to the corresponding decoding/encode stages.
* License: 3-Clause BSD, see COPYING file in arcan source repository.
* Reference: https://arcan-fe.com
*/
/* shared state machine structure */
#include <arcan_shmif.h>
#include <arcan_shmif_server.h>
#include <inttypes.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <ctype.h>
#include "a12.h"
#include "a12_int.h"
#include "net/a12_helper.h"
#include "a12_decode.h"
#include "a12_encode.h"
#include "arcan_mem.h"
#include "external/chacha.c"
#include "external/x25519.h"
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "external/zstd/zstd.h"
int a12_trace_targets = 0;
FILE* a12_trace_dst = NULL;
static int header_sizes[] = {
MAC_BLOCK_SZ + 8 + 1, /* The outer frame */
CONTROL_PACKET_SIZE,
0, /* EVENT size is filled in at first open */
1 + 4 + 2, /* VIDEO partial: ch, stream, len */
1 + 4 + 2, /* AUDIO partial: ch, stream, len */
1 + 4 + 2, /* BINARY partial: ch, stream, len */
MAC_BLOCK_SZ + 8 + 1, /* First packet server side */
0
};
extern void arcan_random(uint8_t* dst, size_t);
size_t a12int_header_size(int kind)
{
assert(kind < COUNT_OF(header_sizes));
return header_sizes[kind];
}
static void unlink_node(struct a12_state*, struct blob_out*);
static void dirstate_item(struct a12_state* S, struct appl_meta* C);
static uint8_t* grow_array(uint8_t* dst, size_t* cur_sz, size_t new_sz, int ind)
{
if (new_sz < *cur_sz)
return dst;
/* pick the nearest higher power of 2 for good measure */
size_t pow = 1;
while (pow < new_sz)
pow *= 2;
/* wrap around? give up */
if (pow < new_sz){
a12int_trace(A12_TRACE_SYSTEM, "error=grow_array:reason=limit");
DYNAMIC_FREE(dst);
*cur_sz = 0;
return NULL;
}
new_sz = pow;
a12int_trace(A12_TRACE_ALLOC,
"grow=queue:%d:from=%zu:to=%zu", ind, *cur_sz, new_sz);
uint8_t* res = DYNAMIC_REALLOC(dst, new_sz);
if (!res){
a12int_trace(A12_TRACE_SYSTEM, "error=grow_array:reason=malloc_fail");
DYNAMIC_FREE(dst);
*cur_sz = 0;
return NULL;
}
/* init the new region */
memset(&res[*cur_sz], '\0', new_sz - *cur_sz);
*cur_sz = new_sz;
return res;
}
/* never permit this to be traced in a normal build */
static void trace_crypto_key(bool srv, const char* domain, uint8_t* buf, size_t sz)
{
#ifdef _DEBUG
char conv[sz * 3 + 2];
for (size_t i = 0; i < sz; i++){
sprintf(&conv[i * 3], "%02X%s", buf[i], i == sz - 1 ? "" : "-");
}
a12int_trace(A12_TRACE_CRYPTO, "%s%s:key=%s", srv ? "server:" : "client:", domain, conv);
#endif
}
/* set the LAST SEEN sequence number in a CONTROL message */
static void step_sequence(struct a12_state* S, uint8_t* outb)
{
pack_u64(S->last_seen_seqnr, outb);
}
static void build_control_header(struct a12_state* S, uint8_t* outb, uint8_t cmd)
{
memset(outb, '\0', CONTROL_PACKET_SIZE);
step_sequence(S, outb);
arcan_random(&outb[8], 8);
outb[16] = S->out_channel;
outb[17] = cmd;
}
void
a12int_request_dirlist(struct a12_state* S, bool notify)
{
if (!S || S->cookie != 0xfeedface){
return;
}
uint8_t outb[CONTROL_PACKET_SIZE];
build_control_header(S, outb, COMMAND_DIRLIST);
outb[18] = notify;
a12int_trace(A12_TRACE_DIRECTORY, "request_list");
a12int_append_out(S, STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
struct appl_meta* a12int_get_directory(struct a12_state* S, uint64_t* clk)
{
if (clk)
*clk = S->directory_clk;
return S->directory;
}
/* linear search, set_directory is low N and infrequent so O^2 is ok */
static struct appl_meta* find_entry(struct a12_state* S, struct appl_meta* tgt)
{
struct appl_meta* cur = S->directory;
while (cur){
if (cur->identifier == tgt->identifier){
return cur;
}
cur = cur->next;
}
return NULL;
}
/* swapping out an existing directory is ok, the only 'requirement' is that
* identifiers for applname are retained without collision */
void a12int_set_directory(struct a12_state* S, struct appl_meta* M)
{
/* first synch the ones that have changed */
struct appl_meta* cur = M;
bool updated = false;
while (cur && S->directory){
struct appl_meta* C = find_entry(S, cur);
if (!C){
updated = true;
dirstate_item(S, cur);
}
else if (memcmp(C->hash, cur->hash, 4) != 0){
updated = true;
dirstate_item(S, cur);
}
cur = cur->next;
}
if (updated){
uint8_t outb[CONTROL_PACKET_SIZE] = {0};
memset(outb, '\0', CONTROL_PACKET_SIZE);
build_control_header(S, outb, COMMAND_DIRSTATE);
a12int_append_out(S,
STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
/* now free the old */
struct appl_meta* C = S->directory;
while (C){
struct appl_meta* old = C;
free(C->buf);
C = C->next;
DYNAMIC_FREE(old);
}
S->directory = M;
}
static void fail_state(struct a12_state* S)
{
#ifndef _DEBUG
/* overwrite all relevant state, dealloc mac/chacha - mark n random bytes for
* continuous transfer before shutting down to be even less useful as an oracle */
#endif
S->state = STATE_BROKEN;
}
static void send_hello_packet(struct a12_state* S,
int mode, uint8_t pubk[static 32], uint8_t entropy[static 8])
{
/* construct the reply with the proper public key */
uint8_t outb[CONTROL_PACKET_SIZE] = {0};
step_sequence(S, outb);
memcpy(&outb[8], entropy, 8);
memcpy(&outb[21], pubk, 32);
if (S->opts->local_role == ROLE_SOURCE){
outb[54] = 1;
}
else if (S->opts->local_role == ROLE_SINK){
outb[54] = 2;
}
else if (S->opts->local_role == ROLE_PROBE){
outb[54] = 3;
}
else if (S->opts->local_role == ROLE_DIR){
outb[54] = 4;
}
else {
fail_state(S);
a12int_trace(A12_TRACE_SYSTEM, "unknown_role");
return;
}
/* channel-id is empty */
outb[17] = COMMAND_HELLO;
outb[18] = ASHMIF_VERSION_MAJOR;
outb[19] = ASHMIF_VERSION_MINOR;
/* mode indicates if we have an ephemeral-Kp exchange first or if we go
* straight to the real one, it is also reserved as a migration path if
* a new ciphersuite will need to be added */
outb[20] = mode;
/* send it back to client */
a12int_append_out(S,
STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
/*
* Used when a full byte buffer for a packet has been prepared, important
* since it will also encrypt, generate MAC and add to buffer prestate.
*
* This is where more advanced and fair queueing should be made in order
* to not have the bandwidth hungry channels (i.e. video) consume everything.
* The rough idea is to have bins for a/v/b streams, with a priority on a/v
* unless it is getting too 'old'. There are some complications:
*
* 1. stream cancellation, can only be done on non-delta/non-compressed
* so mostly usable for binary then
* 2. control packets that are tied to an a/v/b frame
*
* Another issue is that the raw vframes are big and ugly, and here is the
* place where we perform an unavoidable copy unless we want interleaving (and
* then it becomes expensive to perform). Practically speaking it is not that
* bad to encrypt accordingly, it is a stream cipher afterall, BUT having a
* continous MAC screws with that. Now since we have a few bytes entropy and a
* counter as part of the message, replay attacks won't work BUT any
* reordering would then still need to account for rekeying.
*/
void a12int_append_out(struct a12_state* S, uint8_t type,
uint8_t* out, size_t out_sz, uint8_t* prepend, size_t prepend_sz)
{
if (S->state == STATE_BROKEN)
return;
/*
* QUEUE-slot here,
* should also have the ability to probe the size of the queue slots
* so that encoders can react on backpressure
*/
a12int_trace(A12_TRACE_CRYPTO,
"type=%d:size=%zu:prepend_size=%zu:ofs=%zu", type, out_sz, prepend_sz, S->buf_ofs);
/* grow write buffer if the block doesn't fit */
size_t required = S->buf_ofs +
header_sizes[STATE_NOPACKET] + out_sz + prepend_sz + 1;
S->bufs[S->buf_ind] = grow_array(
S->bufs[S->buf_ind],
&S->buf_sz[S->buf_ind],
required,
S->buf_ind
);
/* and if that didn't work, fatal */
if (S->buf_sz[S->buf_ind] < required){
a12int_trace(A12_TRACE_SYSTEM,
"realloc failed: size (%zu) vs required (%zu)", S->buf_sz[S->buf_ind], required);
fail_state(S);
return;
}
uint8_t* dst = S->bufs[S->buf_ind];
/* reserve space for the MAC and remember where it starts and ends */
size_t mac_pos = S->buf_ofs;
S->buf_ofs += MAC_BLOCK_SZ;
size_t data_pos = S->buf_ofs;
/* MISSING OPTIMIZATION, extract n bytes of the cipherstream and apply copy
* operation rather than in-place modification, align with MAC block size and
* continuously update as we fetch as well */
/* 8 byte sequence number */
pack_u64(S->current_seqnr++, &dst[S->buf_ofs]);
S->buf_ofs += 8;
/* 1 byte command data */
dst[S->buf_ofs++] = type;
/* any possible prepend-to-data block */
if (prepend_sz){
memcpy(&dst[S->buf_ofs], prepend, prepend_sz);
S->buf_ofs += prepend_sz;
}
/* and our data block */
memcpy(&dst[S->buf_ofs], out, out_sz);
S->buf_ofs += out_sz;
size_t used = S->buf_ofs - data_pos;
/*
* If we are the client and haven't sent the first authentication request
* yet, setup the nonce part of the cipher to random and shorten the MAC.
*
* Thus the first packet has a half-length MAC and use the other half to
* provide the nonce. This is mainly to reduce code complexity somewhat
* and not have a different pre-header length for the first packet.
*/
size_t mac_sz = MAC_BLOCK_SZ;
if (S->authentic != AUTH_FULL_PK && !S->server && !S->cl_firstout){
mac_sz >>= 1;
arcan_random(&dst[mac_sz], mac_sz);
S->cl_firstout = true;
chacha_set_nonce(S->dec_state, &dst[mac_sz]);
chacha_set_nonce(S->enc_state, &dst[mac_sz]);
a12int_trace(A12_TRACE_CRYPTO, "kind=cipher:status=init_nonce");
trace_crypto_key(S->server, "nonce", &dst[mac_sz], mac_sz);
/* don't forget to add the nonce to the first message MAC */
blake3_hasher_update(&S->out_mac, &dst[mac_sz], mac_sz);
}
/* apply stream-cipher to buffer contents - ETM */
chacha_apply(S->enc_state, &dst[data_pos], used);
/* update MAC with encrypted contents */
blake3_hasher_update(&S->out_mac, &dst[data_pos], used);
/* sample MAC and write to buffer pos, remember it for debugging - no need to
* chain separately as 'finalize' is not really finalized */
blake3_hasher_finalize(&S->out_mac, &dst[mac_pos], mac_sz);
a12int_trace(A12_TRACE_CRYPTO, "kind=mac_enc:position=%zu", S->out_mac.counter);
trace_crypto_key(S->server, "mac_enc", &dst[mac_pos], mac_sz);
S->stats.b_out += out_sz + prepend_sz;
/* if we have set a function that will get the buffer immediately then we set
* the internal buffering state, this is a short-path that can be used
* immediately and then we reset it. */
if (S->opts->sink){
if (!S->opts->sink(dst, S->buf_ofs, S->opts->sink_tag)){
fail_state(S);
}
S->buf_ofs = 0;
}
}
static void reset_state(struct a12_state* S)
{
S->left = header_sizes[STATE_NOPACKET];
if (S->state != STATE_1STSRV_PACKET && S->state != STATE_BROKEN)
S->state = STATE_NOPACKET;
S->decode_pos = 0;
S->in_channel = -1;
}
static void derive_encdec_key(
const char* ssecret, size_t secret_len,
uint8_t out_mac[static BLAKE3_KEY_LEN],
uint8_t out_srv[static BLAKE3_KEY_LEN],
uint8_t out_cl[static BLAKE3_KEY_LEN],
uint8_t* nonce)
{
blake3_hasher temp;
blake3_hasher_init_derive_key(&temp, "arcan-a12 init-packet");
blake3_hasher_update(&temp, ssecret, secret_len);
if (nonce){
blake3_hasher_update(&temp, nonce, NONCE_SIZE);
}
/* mac = H(ssecret_kdf) */
blake3_hasher_finalize(&temp, out_mac, BLAKE3_KEY_LEN);
/* client = H(H(ssecret_kdf)) */
blake3_hasher_update(&temp, out_mac, BLAKE3_KEY_LEN);
blake3_hasher_finalize(&temp, out_cl, BLAKE3_KEY_LEN);
/* server = H(H(H(ssecret_kdf))) */
blake3_hasher_update(&temp, out_cl, BLAKE3_KEY_LEN);
blake3_hasher_finalize(&temp, out_srv, BLAKE3_KEY_LEN);
}
static void update_keymaterial(
struct a12_state* S, char* secret, size_t len, uint8_t* nonce)
{
/* KDF mode for building the initial keys */
uint8_t mac_key[BLAKE3_KEY_LEN];
uint8_t srv_key[BLAKE3_KEY_LEN];
uint8_t cl_key[BLAKE3_KEY_LEN];
_Static_assert(BLAKE3_KEY_LEN >= MAC_BLOCK_SZ, "misconfigured blake3 size");
_Static_assert(BLAKE3_KEY_LEN == 16 || BLAKE3_KEY_LEN == 32, "misconfigured blake3 size");
/* the secret is only used for the first packet */
derive_encdec_key(secret, len, mac_key, srv_key, cl_key, nonce);
blake3_hasher_init_keyed(&S->out_mac, mac_key);
blake3_hasher_init_keyed(&S->in_mac, mac_key);
if (!S->dec_state){
S->dec_state = DYNAMIC_MALLOC(sizeof(struct chacha_ctx));
if (!S->dec_state){
fail_state(S);
return;
}
}
S->enc_state = DYNAMIC_MALLOC(sizeof(struct chacha_ctx));
if (!S->enc_state){
DYNAMIC_FREE(S->dec_state);
fail_state(S);
return;
}
/* depending on who initates the connection, the cipher key will be different,
*
* server encodes with srv_key and decodes with cl_key
* client encodes with cl_key and decodes with srv_key
*
* two keys derived from the same shared secret is preferred over different
* positions in the cipherstream to prevent bugs that could affect position
* stepping to accidentally cause multiple ciphertexts being produced from the
* same key at the same position.
*
* the cipher-state is incomplete as we still need to apply the nonce from the
* helo packet before the setup is complete. */
if (S->server){
trace_crypto_key(S->server, "enc_key", srv_key, BLAKE3_KEY_LEN);
trace_crypto_key(S->server, "dec_key", cl_key, BLAKE3_KEY_LEN);
chacha_setup(S->dec_state, cl_key, BLAKE3_KEY_LEN, 0, CIPHER_ROUNDS);
chacha_setup(S->enc_state, srv_key, BLAKE3_KEY_LEN, 0, CIPHER_ROUNDS);
}
else {
trace_crypto_key(S->server, "dec_key", srv_key, BLAKE3_KEY_LEN);
trace_crypto_key(S->server, "enc_key", cl_key, BLAKE3_KEY_LEN);
chacha_setup(S->enc_state, cl_key, BLAKE3_KEY_LEN, 0, CIPHER_ROUNDS);
chacha_setup(S->dec_state, srv_key, BLAKE3_KEY_LEN, 0, CIPHER_ROUNDS);
}
/* First setup won't have a nonce until one has been received. For that case,
* the key-dance is only to setup MAC - just reusing the same codepath for all
* keymanagement */
if (nonce){
trace_crypto_key(S->server, "state=set_nonce", nonce, NONCE_SIZE);
chacha_set_nonce(S->enc_state, nonce);
chacha_set_nonce(S->dec_state, nonce);
}
}
static struct a12_state* a12_setup(struct a12_context_options* opt, bool srv)
{
struct a12_state* res = DYNAMIC_MALLOC(sizeof(struct a12_state));
if (!res)
return NULL;
*res = (struct a12_state){
.server = srv
};
size_t len = 0;
res->opts = DYNAMIC_MALLOC(sizeof(struct a12_context_options));
if (!res->opts){
DYNAMIC_FREE(res);
return NULL;
}
memcpy(res->opts, opt, sizeof(struct a12_context_options));
if (!res->opts->secret[0]){
sprintf(res->opts->secret, "SETECASTRONOMY");
}
len = strlen(res->opts->secret);
update_keymaterial(res, res->opts->secret, len, NULL);
/* easy-dump for quick debugging (i.e. cmp side vs side to find offset,
* open/init/replay to step mac construction */
/* #define LOG_MAC_DATA */
#ifdef LOG_MAC_DATA
FILE* keys = fopen("macraw.key", "w");
fwrite(mac_key, BLAKE3_KEY_LEN, 1, keys);
fclose(keys);
if (srv){
res->out_mac.log = fopen("srv.macraw.out", "w");
res->in_mac.log = fopen("srv.macraw.in", "w");
}
else{
res->out_mac.log = fopen("cl.macraw.out", "w");
res->in_mac.log = fopen("cl.macraw.in", "w");
}
#endif
res->cookie = 0xfeedface;
res->out_stream = 1;
return res;
}
static void a12_init()
{
static bool init;
if (init)
return;
/* make one nonsense- call first to figure out the current packing size */
uint8_t outb[512];
ssize_t evsz = arcan_shmif_eventpack(
&(struct arcan_event){.category = EVENT_IO}, outb, 512);
header_sizes[STATE_EVENT_PACKET] = evsz + SEQUENCE_NUMBER_SIZE + 1;
init = true;
}
struct a12_state* a12_server(struct a12_context_options* opt)
{
if (!opt)
return NULL;
a12_init();
struct a12_state* res = a12_setup(opt, true);
if (!res)
return NULL;
res->state = STATE_1STSRV_PACKET;
res->left = header_sizes[res->state];
return res;
}
struct a12_state* a12_client(struct a12_context_options* opt)
{
if (!opt)
return NULL;
a12_init();
int mode = 0;
struct a12_state* S = a12_setup(opt, false);
if (!S)
return NULL;
/* use x25519? - pull out the public key from the supplied private and set
* one or two rounds of exchange state, otherwise just mark the connection
* as preauthenticated should the server reply use the correct PSK */
uint8_t empty[32] = {0};
uint8_t outpk[32];
/* client didn't provide an outbound key, generate one at random */
if (memcmp(empty, opt->priv_key, 32) == 0){
a12int_trace(A12_TRACE_SECURITY, "no_private_key:generating");
x25519_private_key(opt->priv_key);
}
memcpy(S->keys.real_priv, opt->priv_key, 32);
/* single round, use correct key immediately - drop the priv-key from the input
* arguments, keep it temporarily here until the shared secret can be
* calculated */
if (opt->disable_ephemeral_k){
mode = HELLO_MODE_REALPK;
S->authentic = AUTH_REAL_HELLO_SENT;
memset(opt->priv_key, '\0', 32);
x25519_public_key(S->keys.real_priv, outpk);
trace_crypto_key(S->server, "cl-priv", S->keys.real_priv, 32);
}
/* double-round, start by generating ephemeral key */
else {
mode = HELLO_MODE_EPHEMPK;
if (opt->force_ephemeral_k){
memcpy(S->keys.ephem_priv, opt->priv_ephem_key, 32);
}
else
x25519_private_key(S->keys.ephem_priv);
x25519_public_key(S->keys.ephem_priv, outpk);
S->authentic = AUTH_POLITE_HELLO_SENT;
}
/* the nonce in the outbound won't be used, but it should look random still */
uint8_t nonce[8];
arcan_random(nonce, 8);
trace_crypto_key(S->server, "hello-pub", outpk, 32);
send_hello_packet(S, mode, outpk, nonce);
return S;
}
void
a12_channel_shutdown(struct a12_state* S, const char* last_words)
{
if (!S || S->cookie != 0xfeedface){
return;
}
uint8_t outb[CONTROL_PACKET_SIZE] = {0};
step_sequence(S, outb);
outb[16] = S->out_channel;
outb[17] = COMMAND_SHUTDOWN;
snprintf((char*)(&outb[18]), CONTROL_PACKET_SIZE - 19, "%s", last_words);
a12int_trace(A12_TRACE_SYSTEM, "channel open, add control packet");
a12int_append_out(S, STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
void
a12_channel_close(struct a12_state* S)
{
if (!S || S->cookie != 0xfeedface){
return;
}
struct a12_channel* ch = &S->channels[S->out_channel];
a12int_encode_drop(S, S->out_channel, false);
a12int_decode_drop(S, S->out_channel, false);
if (ch->unpack_state.bframe.zstd){
ZSTD_freeDCtx(ch->unpack_state.bframe.zstd);
ch->unpack_state.bframe.zstd = NULL;
}
if (ch->active){
ch->cont = NULL;
ch->active = false;
}
/* closing the primary channel means no more operations are permitted */
if (S->out_channel == 0){
fail_state(S);
}
a12int_trace(A12_TRACE_SYSTEM, "closing channel (%d)", S->out_channel);
}
bool
a12_free(struct a12_state* S)
{
if (!S || S->cookie != 0xfeedface){
return false;
}
for (size_t i = 0; i < 256; i++){
if (S->channels[S->out_channel].active){
a12int_trace(A12_TRACE_SYSTEM, "free with channel (%zu) active", i);
return false;
}
}
a12int_set_directory(S, NULL);
if (S->prepend_unpack){
DYNAMIC_FREE(S->prepend_unpack);
S->prepend_unpack = NULL;
S->prepend_unpack_sz = 0;
}
a12int_trace(A12_TRACE_ALLOC, "a12-state machine freed");
DYNAMIC_FREE(S->bufs[0]);
DYNAMIC_FREE(S->bufs[1]);
DYNAMIC_FREE(S->opts);
*S = (struct a12_state){};
S->cookie = 0xdeadbeef;
DYNAMIC_FREE(S);
return true;
}
static void update_mac_and_decrypt(const char* source,
blake3_hasher* hash, struct chacha_ctx* ctx, uint8_t* buf, size_t sz)
{
a12int_trace(A12_TRACE_CRYPTO, "src=%s:mac_update=%zu", source, sz);
blake3_hasher_update(hash, buf, sz);
if (ctx)
chacha_apply(ctx, buf, sz);
}
/*
* NOPACKET:
* MAC
* command byte
*/
static void process_nopacket(struct a12_state* S)
{
/* save MAC tag for later comparison when we have the final packet */
memcpy(S->last_mac_in, S->decode, MAC_BLOCK_SZ);
trace_crypto_key(S->server, "ref_mac", S->last_mac_in, MAC_BLOCK_SZ);
update_mac_and_decrypt(__func__, &S->in_mac, S->dec_state, &S->decode[MAC_BLOCK_SZ], 9);
/* remember the last sequence number of the packet we processed */
unpack_u64(&S->last_seen_seqnr, &S->decode[MAC_BLOCK_SZ]);
if (S->last_seen_seqnr <= S->current_seqnr)
S->stats.packets_pending = S->last_seen_seqnr - S->current_seqnr;
/* and finally the actual type in the inner block */
int state_id = S->decode[MAC_BLOCK_SZ + 8];
if (state_id >= STATE_BROKEN){
a12int_trace(A12_TRACE_SYSTEM, "state=broken:unknown_command=%"PRIu8, S->state);
fail_state(S);
return;
}
/* transition to state based on type, from there we know how many bytes more
* we need to process before the MAC can be checked */
S->state = state_id;
a12int_trace(A12_TRACE_TRANSFER, "seq=%"PRIu64
":left=%"PRIu16":state=%"PRIu8, S->last_seen_seqnr, S->left, S->state);
S->left = header_sizes[S->state];
S->decode_pos = 0;
}
/*
* FIRST:
* MAC[8]
* Nonce[8]
* command byte (always control)
*/
static void process_srvfirst(struct a12_state* S)
{
/* only foul play could bring us here */
if (S->authentic > AUTH_REAL_HELLO_SENT){
fail_state(S);
return;
}
size_t mac_sz = MAC_BLOCK_SZ >> 1;
size_t nonce_sz = 8;
uint8_t nonce[nonce_sz];
a12int_trace(A12_TRACE_CRYPTO, "kind=mac:status=half_block");
memcpy(S->last_mac_in, S->decode, mac_sz);
memcpy(nonce, &S->decode[mac_sz], nonce_sz);
/* read the rest of the control packet */
S->authentic = AUTH_SERVER_HBLOCK;
S->left = CONTROL_PACKET_SIZE;
S->state = STATE_CONTROL_PACKET;
S->decode_pos = 0;
/* update MAC calculation with nonce and seqn+command byte */
blake3_hasher_update(&S->in_mac, nonce, nonce_sz);
blake3_hasher_update(&S->in_mac, &S->decode[mac_sz+nonce_sz], 8 + 1);
if (!S->dec_state){
a12int_trace(A12_TRACE_SECURITY, "srvfirst:no_decode");
fail_state(S);
return;
}
chacha_set_nonce(S->dec_state, nonce);
chacha_set_nonce(S->enc_state, nonce);
a12int_trace(A12_TRACE_CRYPTO, "kind=cipher:status=init_nonce");
trace_crypto_key(S->server, "nonce", nonce, nonce_sz);
/* decrypt command byte and seqn */
size_t base = mac_sz + nonce_sz;
chacha_apply(S->dec_state, &S->decode[base], 9);
if (S->decode[base + 8] != STATE_CONTROL_PACKET){
a12int_trace(A12_TRACE_CRYPTO, "kind=error:status=bad_key_or_nonce");
fail_state(S);
return;
}
}
static void fill_diropened(struct a12_state* S, struct a12_dynreq r)
{
uint8_t outb[CONTROL_PACKET_SIZE];
build_control_header(S, outb, COMMAND_DIROPENED);
outb[18] = r.proto;
memcpy(&outb[19], r.host, 46);
pack_u16(r.port, &outb[65]);
memcpy(&outb[67], r.authk, 12);
memcpy(&outb[79], r.pubk, 32);
a12int_append_out(S, STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
static void command_diropened(struct a12_state* S)
{
/* local- copy the members so the closure is allowed to queue a new one */
void(* oc)(struct a12_state*, struct a12_dynreq, void* tag) = S->pending_dynamic.closure;
void* tag = S->pending_dynamic.tag;
S->pending_dynamic.closure = NULL;
S->pending_dynamic.tag = NULL;
S->pending_dynamic.active = false;
struct a12_dynreq rep = {
.proto = S->decode[18]
};
memcpy(rep.host, &S->decode[19], 46);
unpack_u16(&rep.port, &S->decode[65]);
memcpy(rep.authk, &S->decode[67], 12);
/* this is used both for source and sink, for sink swap in the pubk of the request */
uint8_t nullk[32] = {0};
if (memcmp(nullk, &S->decode[79], 32) == 0)
memcpy(rep.pubk, S->pending_dynamic.req_key, 32);
else
memcpy(rep.pubk, &S->decode[79], 32);
oc(S, rep, tag);
}
static void command_diropen(
struct a12_state* S, uint8_t mode, uint8_t kpub_tgt[static 32])
{
/* a12.h misuse */
struct a12_unpack_cfg* C = &S->channels[0].raw;
if (!C->directory_open){
a12int_trace(A12_TRACE_SECURITY, "kind=warning:diropen_no_handler");
return;
}
/* forward the request */
struct a12_dynreq out = {0};
uint8_t outb[CONTROL_PACKET_SIZE];
/* the implementation is expected to set the authk as it might be outsourced
* to an external oracle that coordinates with the partner in question */
if (C->directory_open(S, kpub_tgt, mode, &out, C->tag)){
fill_diropened(S, out);
}
/* failure is just an empty command */
else {
build_control_header(S, outb, COMMAND_DIROPENED);
a12int_append_out(S, STATE_CONTROL_PACKET, outb, CONTROL_PACKET_SIZE, NULL, 0);
}
}
static void command_cancelstream(
struct a12_state* S, uint32_t streamid, uint8_t reason, uint8_t stype)
{
struct blob_out* node = S->pending;
a12int_trace(A12_TRACE_SYSTEM, "stream_cancel:%"PRIu32":%"PRIu8, streamid, reason);
/* the other end indicated that the current codec or data source is broken,
* propagate the error to the client (if in direct passing mode) otherwise just
* switch the encoder for next frame - any recoverable decode error should
* really be in h264 et al. now so assume that. There might also be a point
* in force-inserting a RESET/STEPFRAME */
if (stype == 0){
if (reason == STREAM_CANCEL_DECODE_ERROR){
a12int_trace(A12_TRACE_VIDEO,
"kind=decode_degrade:codec=h264:reason=sink rejected format");
S->advenc_broken = true;
}
/* other reasons means that the image contents is already known or too dated,
* currently just ignore that - when we implement proper image hashing and can
* use that for known types (cursor, ...) then reconsider */
return;
}
else if (stype == 1){
return;
}
/* try the blobs first */
while (node){
if (node->streamid == streamid){
a12int_trace(A12_TRACE_BTRANSFER,
"kind=cancelled:stream=%"PRIu32":source=remote", streamid);
unlink_node(S, node);
return;
}
node = node->next;
}
}
static void command_binarystream(struct a12_state* S)
{
/*
* unpack / validate header
*/
uint8_t channel = S->decode[16];
struct binary_frame* bframe = &S->channels[channel].unpack_state.bframe;
/*
* sign of a very broken client (or state tracking), starting a new binary
* stream on a channel where one already exists.
*/
if (bframe->active){
a12int_trace(A12_TRACE_SYSTEM,
"kind=error:source=binarystream:kind=EEXIST:ch=%d", (int) channel);
a12_stream_cancel(S, channel);
bframe->active = false;
if (bframe->tmp_fd > 0)
bframe->tmp_fd = -1;
return;
}
if (S->decode[52] == 1){
bframe->zstd = ZSTD_createDCtx();
if (!bframe->zstd){
a12_stream_cancel(S, channel);
a12int_trace(A12_TRACE_SYSTEM,
"kind=error:source=binarystream:kind=zstd_fail:ch=%d", (int) channel);
return;
}
}
uint32_t streamid;
unpack_u32(&streamid, &S->decode[18]);
bframe->streamid = streamid;
unpack_u64(&bframe->size, &S->decode[22]);
bframe->type = S->decode[30];
unpack_u32(&bframe->identifier, &S->decode[31]);
memcpy(bframe->checksum, &S->decode[35], 16);
bframe->tmp_fd = -1;
memcpy(bframe->extid, &S->decode[53], 16);
bframe->active = true;
a12int_trace(A12_TRACE_BTRANSFER,
"kind=header:stream=%"PRId64":left=%"PRIu64":ch=%d:compressed=%d",
bframe->streamid, bframe->size, channel, (int) S->decode[52]
);
/*
* If there is a checksum, ask the local cache process and see if we know about
* it already, if so, cancel the binary stream and substitute in the copy we
* get from the cache, but still need to process and discard incoming packages
* in the meanwhile.
*
* This is the point where, for non-streams, provide a table of hashes first
* and support resume at the first missing or broken hash
*/
int sc = A12_BHANDLER_DONTWANT;
struct a12_bhandler_meta bm = {
.state = A12_BHANDLER_INITIALIZE,
.known_size = bframe->size,
.streamid = bframe->streamid,
.identifier = bframe->identifier,
.type = bframe->type,
.dcont = S->channels[channel].cont,
.fd = -1
};
memcpy(bm.extid, bframe->extid, 16);
memcpy(bm.checksum, bframe->checksum, 16);
if (S->binary_handler){
struct a12_bhandler_res res = S->binary_handler(S, bm, S->binary_handler_tag);
bframe->tmp_fd = res.fd;
sc = res.flag;
}
if (sc == A12_BHANDLER_DONTWANT || sc == A12_BHANDLER_CACHED){
a12_stream_cancel(S, channel);
a12int_trace(A12_TRACE_BTRANSFER,
"kind=reject:stream=%"PRId64":ch=%d", bframe->streamid, channel);
}
}