forked from irungentoo/toxcore
-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathnet_crypto.c
3237 lines (2602 loc) · 102 KB
/
net_crypto.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
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright © 2016-2018 The TokTok team.
* Copyright © 2013 Tox project.
*/
/**
* Functions for the core network crypto.
*
* NOTE: This code has to be perfect. We don't mess around with encryption.
*/
#include "net_crypto.h"
#include <string.h>
#include "DHT.h"
#include "LAN_discovery.h"
#include "TCP_client.h"
#include "TCP_connection.h"
#include "ccompat.h"
#include "crypto_core.h"
#include "list.h"
#include "logger.h"
#include "mem.h"
#include "mono_time.h"
#include "network.h"
#include "util.h"
typedef struct Packet_Data {
uint64_t sent_time;
uint16_t length;
uint8_t data[MAX_CRYPTO_DATA_SIZE];
} Packet_Data;
typedef struct Packets_Array {
Packet_Data *buffer[CRYPTO_PACKET_BUFFER_SIZE];
uint32_t buffer_start;
uint32_t buffer_end; /* packet numbers in array: `{buffer_start, buffer_end)` */
} Packets_Array;
typedef enum Crypto_Conn_State {
/* the connection slot is free. This value is 0 so it is valid after
* `crypto_memzero(...)` of the parent struct
*/
CRYPTO_CONN_FREE = 0,
CRYPTO_CONN_NO_CONNECTION, /* the connection is allocated, but not yet used */
CRYPTO_CONN_COOKIE_REQUESTING, /* we are sending cookie request packets */
CRYPTO_CONN_HANDSHAKE_SENT, /* we are sending handshake packets */
/* we are sending handshake packets.
* we have received one from the other, but no data */
CRYPTO_CONN_NOT_CONFIRMED,
CRYPTO_CONN_ESTABLISHED, /* the connection is established */
} Crypto_Conn_State;
typedef struct Crypto_Connection {
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The real public key of the peer. */
uint8_t recv_nonce[CRYPTO_NONCE_SIZE]; /* Nonce of received packets. */
uint8_t sent_nonce[CRYPTO_NONCE_SIZE]; /* Nonce of sent packets. */
uint8_t sessionpublic_key[CRYPTO_PUBLIC_KEY_SIZE]; /* Our public key for this session. */
uint8_t sessionsecret_key[CRYPTO_SECRET_KEY_SIZE]; /* Our private key for this session. */
uint8_t peersessionpublic_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The public key of the peer. */
uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE]; /* The precomputed shared key from encrypt_precompute. */
Crypto_Conn_State status; /* See Crypto_Conn_State documentation */
uint64_t cookie_request_number; /* number used in the cookie request packets for this connection */
uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The dht public key of the peer */
uint8_t *temp_packet; /* Where the cookie request/handshake packet is stored while it is being sent. */
uint16_t temp_packet_length;
uint64_t temp_packet_sent_time; /* The time at which the last temp_packet was sent in ms. */
uint32_t temp_packet_num_sent;
IP_Port ip_portv4; /* The ip and port to contact this guy directly.*/
IP_Port ip_portv6;
uint64_t direct_lastrecv_timev4; /* The Time at which we last received a direct packet in ms. */
uint64_t direct_lastrecv_timev6;
uint64_t last_tcp_sent; /* Time the last TCP packet was sent. */
Packets_Array send_array;
Packets_Array recv_array;
connection_status_cb *connection_status_callback;
void *connection_status_callback_object;
int connection_status_callback_id;
connection_data_cb *connection_data_callback;
void *connection_data_callback_object;
int connection_data_callback_id;
connection_lossy_data_cb *connection_lossy_data_callback;
void *connection_lossy_data_callback_object;
int connection_lossy_data_callback_id;
uint64_t last_request_packet_sent;
uint64_t direct_send_attempt_time;
uint32_t packet_counter;
double packet_recv_rate;
uint64_t packet_counter_set;
double packet_send_rate;
uint32_t packets_left;
uint64_t last_packets_left_set;
double last_packets_left_rem;
double packet_send_rate_requested;
uint32_t packets_left_requested;
uint64_t last_packets_left_requested_set;
double last_packets_left_requested_rem;
uint32_t last_sendqueue_size[CONGESTION_QUEUE_ARRAY_SIZE];
uint32_t last_sendqueue_counter;
long signed int last_num_packets_sent[CONGESTION_LAST_SENT_ARRAY_SIZE];
long signed int last_num_packets_resent[CONGESTION_LAST_SENT_ARRAY_SIZE];
uint32_t packets_sent;
uint32_t packets_resent;
uint64_t last_congestion_event;
uint64_t rtt_time;
/* TCP_connection connection_number */
unsigned int connection_number_tcp;
bool maximum_speed_reached;
/* Must be a pointer, because the struct is moved in memory */
pthread_mutex_t *mutex;
dht_pk_cb *dht_pk_callback;
void *dht_pk_callback_object;
uint32_t dht_pk_callback_number;
} Crypto_Connection;
static const Crypto_Connection empty_crypto_connection = {{0}};
struct Net_Crypto {
const Logger *log;
const Memory *mem;
const Random *rng;
Mono_Time *mono_time;
const Network *ns;
DHT *dht;
TCP_Connections *tcp_c;
Crypto_Connection *crypto_connections;
pthread_mutex_t tcp_mutex;
pthread_mutex_t connections_mutex;
unsigned int connection_use_counter;
uint32_t crypto_connections_length; /* Length of connections array. */
/* Our public and secret keys. */
uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
/* The secret key used for cookies */
uint8_t secret_symmetric_key[CRYPTO_SYMMETRIC_KEY_SIZE];
new_connection_cb *new_connection_callback;
void *new_connection_callback_object;
/* The current optimal sleep time */
uint32_t current_sleep_time;
BS_List ip_port_list;
};
const uint8_t *nc_get_self_public_key(const Net_Crypto *c)
{
return c->self_public_key;
}
const uint8_t *nc_get_self_secret_key(const Net_Crypto *c)
{
return c->self_secret_key;
}
TCP_Connections *nc_get_tcp_c(const Net_Crypto *c)
{
return c->tcp_c;
}
DHT *nc_get_dht(const Net_Crypto *c)
{
return c->dht;
}
non_null()
static bool crypt_connection_id_is_valid(const Net_Crypto *c, int crypt_connection_id)
{
if ((uint32_t)crypt_connection_id >= c->crypto_connections_length) {
return false;
}
if (c->crypto_connections == nullptr) {
return false;
}
const Crypto_Conn_State status = c->crypto_connections[crypt_connection_id].status;
return status != CRYPTO_CONN_NO_CONNECTION && status != CRYPTO_CONN_FREE;
}
/** cookie timeout in seconds */
#define COOKIE_TIMEOUT 15
#define COOKIE_DATA_LENGTH (uint16_t)(CRYPTO_PUBLIC_KEY_SIZE * 2)
#define COOKIE_CONTENTS_LENGTH (uint16_t)(sizeof(uint64_t) + COOKIE_DATA_LENGTH)
#define COOKIE_LENGTH (uint16_t)(CRYPTO_NONCE_SIZE + COOKIE_CONTENTS_LENGTH + CRYPTO_MAC_SIZE)
#define COOKIE_REQUEST_PLAIN_LENGTH (uint16_t)(COOKIE_DATA_LENGTH + sizeof(uint64_t))
#define COOKIE_REQUEST_LENGTH (uint16_t)(1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE)
#define COOKIE_RESPONSE_LENGTH (uint16_t)(1 + CRYPTO_NONCE_SIZE + COOKIE_LENGTH + sizeof(uint64_t) + CRYPTO_MAC_SIZE)
/** @brief Create a cookie request packet and put it in packet.
*
* dht_public_key is the dht public key of the other
*
* packet must be of size COOKIE_REQUEST_LENGTH or bigger.
*
* @retval -1 on failure.
* @retval COOKIE_REQUEST_LENGTH on success.
*/
non_null()
static int create_cookie_request(const Net_Crypto *c, uint8_t *packet, const uint8_t *dht_public_key,
uint64_t number, uint8_t *shared_key)
{
uint8_t plain[COOKIE_REQUEST_PLAIN_LENGTH];
memcpy(plain, c->self_public_key, CRYPTO_PUBLIC_KEY_SIZE);
memzero(plain + CRYPTO_PUBLIC_KEY_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(plain + (CRYPTO_PUBLIC_KEY_SIZE * 2), &number, sizeof(uint64_t));
const uint8_t *tmp_shared_key = dht_get_shared_key_sent(c->dht, dht_public_key);
memcpy(shared_key, tmp_shared_key, CRYPTO_SHARED_KEY_SIZE);
uint8_t nonce[CRYPTO_NONCE_SIZE];
random_nonce(c->rng, nonce);
packet[0] = NET_PACKET_COOKIE_REQUEST;
memcpy(packet + 1, dht_get_self_public_key(c->dht), CRYPTO_PUBLIC_KEY_SIZE);
memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, nonce, CRYPTO_NONCE_SIZE);
const int len = encrypt_data_symmetric(shared_key, nonce, plain, sizeof(plain),
packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE);
if (len != COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE) {
return -1;
}
return 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + len;
}
/** @brief Create cookie of length COOKIE_LENGTH from bytes of length COOKIE_DATA_LENGTH using encryption_key
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int create_cookie(const Random *rng, const Mono_Time *mono_time, uint8_t *cookie, const uint8_t *bytes,
const uint8_t *encryption_key)
{
uint8_t contents[COOKIE_CONTENTS_LENGTH];
const uint64_t temp_time = mono_time_get(mono_time);
memcpy(contents, &temp_time, sizeof(temp_time));
memcpy(contents + sizeof(temp_time), bytes, COOKIE_DATA_LENGTH);
random_nonce(rng, cookie);
const int len = encrypt_data_symmetric(encryption_key, cookie, contents, sizeof(contents), cookie + CRYPTO_NONCE_SIZE);
if (len != COOKIE_LENGTH - CRYPTO_NONCE_SIZE) {
return -1;
}
return 0;
}
/** @brief Open cookie of length COOKIE_LENGTH to bytes of length COOKIE_DATA_LENGTH using encryption_key
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int open_cookie(const Mono_Time *mono_time, uint8_t *bytes, const uint8_t *cookie,
const uint8_t *encryption_key)
{
uint8_t contents[COOKIE_CONTENTS_LENGTH];
const int len = decrypt_data_symmetric(encryption_key, cookie, cookie + CRYPTO_NONCE_SIZE,
COOKIE_LENGTH - CRYPTO_NONCE_SIZE, contents);
if (len != sizeof(contents)) {
return -1;
}
uint64_t cookie_time;
memcpy(&cookie_time, contents, sizeof(cookie_time));
const uint64_t temp_time = mono_time_get(mono_time);
if (cookie_time + COOKIE_TIMEOUT < temp_time || temp_time < cookie_time) {
return -1;
}
memcpy(bytes, contents + sizeof(cookie_time), COOKIE_DATA_LENGTH);
return 0;
}
/** @brief Create a cookie response packet and put it in packet.
* @param request_plain must be COOKIE_REQUEST_PLAIN_LENGTH bytes.
* @param packet must be of size COOKIE_RESPONSE_LENGTH or bigger.
*
* @retval -1 on failure.
* @retval COOKIE_RESPONSE_LENGTH on success.
*/
non_null()
static int create_cookie_response(const Net_Crypto *c, uint8_t *packet, const uint8_t *request_plain,
const uint8_t *shared_key, const uint8_t *dht_public_key)
{
uint8_t cookie_plain[COOKIE_DATA_LENGTH];
memcpy(cookie_plain, request_plain, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, dht_public_key, CRYPTO_PUBLIC_KEY_SIZE);
uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
if (create_cookie(c->rng, c->mono_time, plain, cookie_plain, c->secret_symmetric_key) != 0) {
return -1;
}
memcpy(plain + COOKIE_LENGTH, request_plain + COOKIE_DATA_LENGTH, sizeof(uint64_t));
packet[0] = NET_PACKET_COOKIE_RESPONSE;
random_nonce(c->rng, packet + 1);
const int len = encrypt_data_symmetric(shared_key, packet + 1, plain, sizeof(plain), packet + 1 + CRYPTO_NONCE_SIZE);
if (len != COOKIE_RESPONSE_LENGTH - (1 + CRYPTO_NONCE_SIZE)) {
return -1;
}
return COOKIE_RESPONSE_LENGTH;
}
/** @brief Handle the cookie request packet of length length.
* Put what was in the request in request_plain (must be of size COOKIE_REQUEST_PLAIN_LENGTH)
* Put the key used to decrypt the request into shared_key (of size CRYPTO_SHARED_KEY_SIZE) for use in the response.
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int handle_cookie_request(const Net_Crypto *c, uint8_t *request_plain, uint8_t *shared_key,
uint8_t *dht_public_key, const uint8_t *packet, uint16_t length)
{
if (length != COOKIE_REQUEST_LENGTH) {
return -1;
}
memcpy(dht_public_key, packet + 1, CRYPTO_PUBLIC_KEY_SIZE);
const uint8_t *tmp_shared_key = dht_get_shared_key_sent(c->dht, dht_public_key);
memcpy(shared_key, tmp_shared_key, CRYPTO_SHARED_KEY_SIZE);
const int len = decrypt_data_symmetric(shared_key, packet + 1 + CRYPTO_PUBLIC_KEY_SIZE,
packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE, COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE,
request_plain);
if (len != COOKIE_REQUEST_PLAIN_LENGTH) {
return -1;
}
return 0;
}
/** Handle the cookie request packet (for raw UDP) */
non_null(1, 2, 3) nullable(5)
static int udp_handle_cookie_request(void *object, const IP_Port *source, const uint8_t *packet, uint16_t length,
void *userdata)
{
const Net_Crypto *c = (const Net_Crypto *)object;
uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE];
if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
return 1;
}
uint8_t data[COOKIE_RESPONSE_LENGTH];
if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
return 1;
}
if ((uint32_t)sendpacket(dht_get_net(c->dht), source, data, sizeof(data)) != sizeof(data)) {
return 1;
}
return 0;
}
/** Handle the cookie request packet (for TCP) */
non_null()
static int tcp_handle_cookie_request(const Net_Crypto *c, int connections_number, const uint8_t *packet,
uint16_t length)
{
uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE];
if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
return -1;
}
uint8_t data[COOKIE_RESPONSE_LENGTH];
if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
return -1;
}
const int ret = send_packet_tcp_connection(c->tcp_c, connections_number, data, sizeof(data));
return ret;
}
/** Handle the cookie request packet (for TCP oob packets) */
non_null()
static int tcp_oob_handle_cookie_request(const Net_Crypto *c, unsigned int tcp_connections_number,
const uint8_t *dht_public_key, const uint8_t *packet, uint16_t length)
{
uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
uint8_t dht_public_key_temp[CRYPTO_PUBLIC_KEY_SIZE];
if (handle_cookie_request(c, request_plain, shared_key, dht_public_key_temp, packet, length) != 0) {
return -1;
}
if (!pk_equal(dht_public_key, dht_public_key_temp)) {
return -1;
}
uint8_t data[COOKIE_RESPONSE_LENGTH];
if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
return -1;
}
const int ret = tcp_send_oob_packet(c->tcp_c, tcp_connections_number, dht_public_key, data, sizeof(data));
return ret;
}
/** @brief Handle a cookie response packet of length encrypted with shared_key.
* put the cookie in the response in cookie
*
* @param cookie must be of length COOKIE_LENGTH.
*
* @retval -1 on failure.
* @retval COOKIE_LENGTH on success.
*/
non_null()
static int handle_cookie_response(uint8_t *cookie, uint64_t *number,
const uint8_t *packet, uint16_t length,
const uint8_t *shared_key)
{
if (length != COOKIE_RESPONSE_LENGTH) {
return -1;
}
uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
const int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + CRYPTO_NONCE_SIZE,
length - (1 + CRYPTO_NONCE_SIZE), plain);
if (len != sizeof(plain)) {
return -1;
}
memcpy(cookie, plain, COOKIE_LENGTH);
memcpy(number, plain + COOKIE_LENGTH, sizeof(uint64_t));
return COOKIE_LENGTH;
}
#define HANDSHAKE_PACKET_LENGTH (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH + CRYPTO_MAC_SIZE)
/** @brief Create a handshake packet and put it in packet.
* @param cookie must be COOKIE_LENGTH bytes.
* @param packet must be of size HANDSHAKE_PACKET_LENGTH or bigger.
*
* @retval -1 on failure.
* @retval HANDSHAKE_PACKET_LENGTH on success.
*/
non_null()
static int create_crypto_handshake(const Net_Crypto *c, uint8_t *packet, const uint8_t *cookie, const uint8_t *nonce,
const uint8_t *session_pk, const uint8_t *peer_real_pk, const uint8_t *peer_dht_pubkey)
{
uint8_t plain[CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH];
memcpy(plain, nonce, CRYPTO_NONCE_SIZE);
memcpy(plain + CRYPTO_NONCE_SIZE, session_pk, CRYPTO_PUBLIC_KEY_SIZE);
crypto_sha512(plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE, cookie, COOKIE_LENGTH);
uint8_t cookie_plain[COOKIE_DATA_LENGTH];
memcpy(cookie_plain, peer_real_pk, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, peer_dht_pubkey, CRYPTO_PUBLIC_KEY_SIZE);
if (create_cookie(c->rng, c->mono_time, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE,
cookie_plain, c->secret_symmetric_key) != 0) {
return -1;
}
random_nonce(c->rng, packet + 1 + COOKIE_LENGTH);
const int len = encrypt_data(peer_real_pk, c->self_secret_key, packet + 1 + COOKIE_LENGTH, plain, sizeof(plain),
packet + 1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE);
if (len != HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE)) {
return -1;
}
packet[0] = NET_PACKET_CRYPTO_HS;
memcpy(packet + 1, cookie, COOKIE_LENGTH);
return HANDSHAKE_PACKET_LENGTH;
}
/** @brief Handle a crypto handshake packet of length.
* put the nonce contained in the packet in nonce,
* the session public key in session_pk
* the real public key of the peer in peer_real_pk
* the dht public key of the peer in dht_public_key and
* the cookie inside the encrypted part of the packet in cookie.
*
* if expected_real_pk isn't NULL it denotes the real public key
* the packet should be from.
*
* nonce must be at least CRYPTO_NONCE_SIZE
* session_pk must be at least CRYPTO_PUBLIC_KEY_SIZE
* peer_real_pk must be at least CRYPTO_PUBLIC_KEY_SIZE
* cookie must be at least COOKIE_LENGTH
*
* @retval false on failure.
* @retval true on success.
*/
non_null(1, 2, 3, 4, 5, 6, 7) nullable(9)
static bool handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t *session_pk, uint8_t *peer_real_pk,
uint8_t *dht_public_key, uint8_t *cookie, const uint8_t *packet, uint16_t length, const uint8_t *expected_real_pk)
{
if (length != HANDSHAKE_PACKET_LENGTH) {
return false;
}
uint8_t cookie_plain[COOKIE_DATA_LENGTH];
if (open_cookie(c->mono_time, cookie_plain, packet + 1, c->secret_symmetric_key) != 0) {
return false;
}
if (expected_real_pk != nullptr && !pk_equal(cookie_plain, expected_real_pk)) {
return false;
}
uint8_t cookie_hash[CRYPTO_SHA512_SIZE];
crypto_sha512(cookie_hash, packet + 1, COOKIE_LENGTH);
uint8_t plain[CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH];
const int len = decrypt_data(cookie_plain, c->self_secret_key, packet + 1 + COOKIE_LENGTH,
packet + 1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE,
HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE), plain);
if (len != sizeof(plain)) {
return false;
}
if (!crypto_sha512_eq(cookie_hash, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE)) {
return false;
}
memcpy(nonce, plain, CRYPTO_NONCE_SIZE);
memcpy(session_pk, plain + CRYPTO_NONCE_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(cookie, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE, COOKIE_LENGTH);
memcpy(peer_real_pk, cookie_plain, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(dht_public_key, cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
return true;
}
non_null()
static Crypto_Connection *get_crypto_connection(const Net_Crypto *c, int crypt_connection_id)
{
if (!crypt_connection_id_is_valid(c, crypt_connection_id)) {
return nullptr;
}
return &c->crypto_connections[crypt_connection_id];
}
/** @brief Associate an ip_port to a connection.
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int add_ip_port_connection(Net_Crypto *c, int crypt_connection_id, const IP_Port *ip_port)
{
Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
if (conn == nullptr) {
return -1;
}
if (net_family_is_ipv4(ip_port->ip.family)) {
if (!ipport_equal(ip_port, &conn->ip_portv4) && !ip_is_lan(&conn->ip_portv4.ip)) {
if (!bs_list_add(&c->ip_port_list, (const uint8_t *)ip_port, crypt_connection_id)) {
return -1;
}
bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv4, crypt_connection_id);
conn->ip_portv4 = *ip_port;
return 0;
}
} else if (net_family_is_ipv6(ip_port->ip.family)) {
if (!ipport_equal(ip_port, &conn->ip_portv6)) {
if (!bs_list_add(&c->ip_port_list, (const uint8_t *)ip_port, crypt_connection_id)) {
return -1;
}
bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv6, crypt_connection_id);
conn->ip_portv6 = *ip_port;
return 0;
}
}
return -1;
}
/** @brief Return the IP_Port that should be used to send packets to the other peer.
*
* @retval IP_Port with family 0 on failure.
* @return IP_Port on success.
*/
non_null()
static IP_Port return_ip_port_connection(const Net_Crypto *c, int crypt_connection_id)
{
const IP_Port empty = {{{0}}};
const Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
if (conn == nullptr) {
return empty;
}
const uint64_t current_time = mono_time_get(c->mono_time);
bool v6 = false;
bool v4 = false;
if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev4) > current_time) {
v4 = true;
}
if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev6) > current_time) {
v6 = true;
}
/* Prefer IP_Ports which haven't timed out to those which have.
* To break ties, prefer ipv4 lan, then ipv6, then non-lan ipv4.
*/
if (v4 && ip_is_lan(&conn->ip_portv4.ip)) {
return conn->ip_portv4;
}
if (v6 && net_family_is_ipv6(conn->ip_portv6.ip.family)) {
return conn->ip_portv6;
}
if (v4 && net_family_is_ipv4(conn->ip_portv4.ip.family)) {
return conn->ip_portv4;
}
if (ip_is_lan(&conn->ip_portv4.ip)) {
return conn->ip_portv4;
}
if (net_family_is_ipv6(conn->ip_portv6.ip.family)) {
return conn->ip_portv6;
}
if (net_family_is_ipv4(conn->ip_portv4.ip.family)) {
return conn->ip_portv4;
}
return empty;
}
/** @brief Sends a packet to the peer using the fastest route.
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int send_packet_to(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
{
// TODO(irungentoo): TCP, etc...
Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
if (conn == nullptr) {
return -1;
}
bool direct_send_attempt = false;
pthread_mutex_lock(conn->mutex);
IP_Port ip_port = return_ip_port_connection(c, crypt_connection_id);
// TODO(irungentoo): on bad networks, direct connections might not last indefinitely.
if (!net_family_is_unspec(ip_port.ip.family)) {
bool direct_connected = false;
// FIXME(sudden6): handle return value
crypto_connection_status(c, crypt_connection_id, &direct_connected, nullptr);
if (direct_connected) {
if ((uint32_t)sendpacket(dht_get_net(c->dht), &ip_port, data, length) == length) {
pthread_mutex_unlock(conn->mutex);
return 0;
}
pthread_mutex_unlock(conn->mutex);
LOGGER_WARNING(c->log, "sending packet of length %d failed", length);
return -1;
}
// TODO(irungentoo): a better way of sending packets directly to confirm the others ip.
const uint64_t current_time = mono_time_get(c->mono_time);
if ((((UDP_DIRECT_TIMEOUT / 2) + conn->direct_send_attempt_time) < current_time && length < 96)
|| data[0] == NET_PACKET_COOKIE_REQUEST || data[0] == NET_PACKET_CRYPTO_HS) {
if ((uint32_t)sendpacket(dht_get_net(c->dht), &ip_port, data, length) == length) {
direct_send_attempt = true;
conn->direct_send_attempt_time = mono_time_get(c->mono_time);
}
}
}
pthread_mutex_unlock(conn->mutex);
pthread_mutex_lock(&c->tcp_mutex);
const int ret = send_packet_tcp_connection(c->tcp_c, conn->connection_number_tcp, data, length);
pthread_mutex_unlock(&c->tcp_mutex);
pthread_mutex_lock(conn->mutex);
if (ret == 0) {
conn->last_tcp_sent = current_time_monotonic(c->mono_time);
}
pthread_mutex_unlock(conn->mutex);
if (direct_send_attempt) {
return 0;
}
return ret;
}
/*** START: Array Related functions */
/** @brief Return number of packets in array
* Note that holes are counted too.
*/
non_null()
static uint32_t num_packets_array(const Packets_Array *array)
{
return array->buffer_end - array->buffer_start;
}
/** @brief Add data with packet number to array.
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int add_data_to_buffer(const Memory *mem, Packets_Array *array, uint32_t number, const Packet_Data *data)
{
if (number - array->buffer_start >= CRYPTO_PACKET_BUFFER_SIZE) {
return -1;
}
const uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
if (array->buffer[num] != nullptr) {
return -1;
}
Packet_Data *new_d = (Packet_Data *)mem_alloc(mem, sizeof(Packet_Data));
if (new_d == nullptr) {
return -1;
}
*new_d = *data;
array->buffer[num] = new_d;
if (number - array->buffer_start >= num_packets_array(array)) {
array->buffer_end = number + 1;
}
return 0;
}
/** @brief Get pointer of data with packet number.
*
* @retval -1 on failure.
* @retval 0 if data at number is empty.
* @retval 1 if data pointer was put in data.
*/
non_null()
static int get_data_pointer(const Packets_Array *array, Packet_Data **data, uint32_t number)
{
const uint32_t num_spots = num_packets_array(array);
if (array->buffer_end - number > num_spots || number - array->buffer_start >= num_spots) {
return -1;
}
const uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
if (array->buffer[num] == nullptr) {
return 0;
}
*data = array->buffer[num];
return 1;
}
/** @brief Add data to end of array.
*
* @retval -1 on failure.
* @return packet number on success.
*/
non_null()
static int64_t add_data_end_of_buffer(const Logger *logger, const Memory *mem, Packets_Array *array, const Packet_Data *data)
{
const uint32_t num_spots = num_packets_array(array);
if (num_spots >= CRYPTO_PACKET_BUFFER_SIZE) {
LOGGER_WARNING(logger, "crypto packet buffer size exceeded; rejecting packet of length %d", data->length);
return -1;
}
Packet_Data *new_d = (Packet_Data *)mem_alloc(mem, sizeof(Packet_Data));
if (new_d == nullptr) {
LOGGER_ERROR(logger, "packet data allocation failed");
return -1;
}
*new_d = *data;
const uint32_t id = array->buffer_end;
array->buffer[id % CRYPTO_PACKET_BUFFER_SIZE] = new_d;
++array->buffer_end;
return id;
}
/** @brief Read data from beginning of array.
*
* @retval -1 on failure.
* @return packet number on success.
*/
non_null()
static int64_t read_data_beg_buffer(const Memory *mem, Packets_Array *array, Packet_Data *data)
{
if (array->buffer_end == array->buffer_start) {
return -1;
}
const uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE;
if (array->buffer[num] == nullptr) {
return -1;
}
*data = *array->buffer[num];
const uint32_t id = array->buffer_start;
++array->buffer_start;
mem_delete(mem, array->buffer[num]);
array->buffer[num] = nullptr;
return id;
}
/** @brief Delete all packets in array before number (but not number)
*
* @retval -1 on failure.
* @retval 0 on success
*/
non_null()
static int clear_buffer_until(const Memory *mem, Packets_Array *array, uint32_t number)
{
const uint32_t num_spots = num_packets_array(array);
if (array->buffer_end - number >= num_spots || number - array->buffer_start > num_spots) {
return -1;
}
uint32_t i;
for (i = array->buffer_start; i != number; ++i) {
const uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
if (array->buffer[num] != nullptr) {
mem_delete(mem, array->buffer[num]);
array->buffer[num] = nullptr;
}
}
array->buffer_start = i;
return 0;
}
non_null()
static int clear_buffer(const Memory *mem, Packets_Array *array)
{
uint32_t i;
for (i = array->buffer_start; i != array->buffer_end; ++i) {
const uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
if (array->buffer[num] != nullptr) {
mem_delete(mem, array->buffer[num]);
array->buffer[num] = nullptr;
}
}
array->buffer_start = i;
return 0;
}
/** @brief Set array buffer end to number.
*
* @retval -1 on failure.
* @retval 0 on success.
*/
non_null()
static int set_buffer_end(Packets_Array *array, uint32_t number)
{
if (number - array->buffer_start > CRYPTO_PACKET_BUFFER_SIZE) {
return -1;
}
if (number - array->buffer_end > CRYPTO_PACKET_BUFFER_SIZE) {
return -1;
}
array->buffer_end = number;
return 0;
}
/**
* @brief Create a packet request packet from recv_array and send_buffer_end into
* data of length.
*
* @retval -1 on failure.
* @return length of packet on success.
*/
non_null()
static int generate_request_packet(uint8_t *data, uint16_t length, const Packets_Array *recv_array)
{
if (length == 0) {
return -1;
}
data[0] = PACKET_ID_REQUEST;
uint16_t cur_len = 1;
if (recv_array->buffer_start == recv_array->buffer_end) {
return cur_len;
}
if (length <= cur_len) {
return cur_len;
}
uint32_t n = 1;
for (uint32_t i = recv_array->buffer_start; i != recv_array->buffer_end; ++i) {
const uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
if (recv_array->buffer[num] == nullptr) {
data[cur_len] = n;
n = 0;
++cur_len;
if (length <= cur_len) {
return cur_len;
}
} else if (n == 255) {
data[cur_len] = 0;
n = 0;
++cur_len;
if (length <= cur_len) {
return cur_len;
}
}
++n;
}
return cur_len;
}
/** @brief Handle a request data packet.
* Remove all the packets the other received from the array.
*
* @retval -1 on failure.