summaryrefslogtreecommitdiff
path: root/toxcore/net_crypto.c
diff options
context:
space:
mode:
Diffstat (limited to 'toxcore/net_crypto.c')
-rw-r--r--toxcore/net_crypto.c1800
1 files changed, 1295 insertions, 505 deletions
diff --git a/toxcore/net_crypto.c b/toxcore/net_crypto.c
index 6e5b8c82..049e2690 100644
--- a/toxcore/net_crypto.c
+++ b/toxcore/net_crypto.c
@@ -35,439 +35,1024 @@ static uint8_t crypt_connection_id_not_valid(Net_Crypto *c, int crypt_connection
35 return (uint32_t)crypt_connection_id >= c->crypto_connections_length; 35 return (uint32_t)crypt_connection_id >= c->crypto_connections_length;
36} 36}
37 37
38/* Use this instead of memcmp; not vulnerable to timing attacks. */ 38/* return 0 if connection is dead.
39uint8_t crypto_iszero(uint8_t *mem, uint32_t length) 39 * return 1 if connection is alive.
40 */
41static int is_alive(uint8_t status)
40{ 42{
41 uint8_t check = 0; 43 if (status == CRYPTO_CONN_COOKIE_REQUESTING ||
42 uint32_t i; 44 status == CRYPTO_CONN_HANDSHAKE_SENT ||
43 45 status == CRYPTO_CONN_NOT_CONFIRMED ||
44 for (i = 0; i < length; ++i) { 46 status == CRYPTO_CONN_ESTABLISHED) {
45 check |= mem[i]; 47 return 1;
46 } 48 }
47 49
48 return check; // We return zero if mem is made out of zeroes. 50 return 0;
49} 51}
50 52
51/* Precomputes the shared key from their public_key and our secret_key. 53/* cookie timeout in seconds */
52 * This way we can avoid an expensive elliptic curve scalar multiply for each 54#define COOKIE_TIMEOUT 10
53 * encrypt/decrypt operation. 55#define COOKIE_DATA_LENGTH (crypto_box_PUBLICKEYBYTES * 2)
54 * enc_key has to be crypto_box_BEFORENMBYTES bytes long. 56#define COOKIE_CONTENTS_LENGTH (sizeof(uint64_t) + COOKIE_DATA_LENGTH)
57#define COOKIE_LENGTH (crypto_box_NONCEBYTES + COOKIE_CONTENTS_LENGTH + crypto_box_MACBYTES)
58
59#define COOKIE_REQUEST_PLAIN_LENGTH (COOKIE_DATA_LENGTH + sizeof(uint64_t))
60#define COOKIE_REQUEST_LENGTH (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES)
61#define COOKIE_RESPONSE_LENGTH (1 + crypto_box_NONCEBYTES + COOKIE_LENGTH + sizeof(uint64_t) + crypto_box_MACBYTES)
62
63/* Create a cookie request packet and put it in packet.
64 * dht_public_key is the dht public key of the other
65 * real_public_key is the real public key of the other.
66 *
67 * packet must be of size COOKIE_REQUEST_LENGTH or bigger.
68 *
69 * return -1 on failure.
70 * return COOKIE_REQUEST_LENGTH on success.
55 */ 71 */
56void encrypt_precompute(uint8_t *public_key, uint8_t *secret_key, uint8_t *enc_key) 72static int create_cookie_request(Net_Crypto *c, uint8_t *packet, uint8_t *dht_public_key, uint8_t *real_public_key,
73 uint64_t number, uint8_t *shared_key)
57{ 74{
58 crypto_box_beforenm(enc_key, public_key, secret_key); 75 uint8_t plain[COOKIE_REQUEST_PLAIN_LENGTH];
76
77 memcpy(plain, c->self_public_key, crypto_box_PUBLICKEYBYTES);
78 memcpy(plain + crypto_box_PUBLICKEYBYTES, real_public_key, crypto_box_PUBLICKEYBYTES);
79 memcpy(plain + (crypto_box_PUBLICKEYBYTES * 2), &number, sizeof(uint64_t));
80
81 DHT_get_shared_key_sent(c->dht, shared_key, dht_public_key);
82 uint8_t nonce[crypto_box_NONCEBYTES];
83 new_nonce(nonce);
84 packet[0] = NET_PACKET_COOKIE_REQUEST;
85 memcpy(packet + 1, c->dht->self_public_key, crypto_box_PUBLICKEYBYTES);
86 memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES, nonce, crypto_box_NONCEBYTES);
87 int len = encrypt_data_symmetric(shared_key, nonce, plain, sizeof(plain),
88 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
89
90 if (len != COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES)
91 return -1;
92
93 return (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + len);
59} 94}
60 95
61/* Fast encrypt. Depends on enc_key from encrypt_precompute. */ 96/* Create cookie of length COOKIE_LENGTH from bytes of length COOKIE_DATA_LENGTH using encryption_key
62int encrypt_data_fast(uint8_t *enc_key, uint8_t *nonce, 97 *
63 uint8_t *plain, uint32_t length, uint8_t *encrypted) 98 * return -1 on failure.
99 * return 0 on success.
100 */
101static int create_cookie(uint8_t *cookie, uint8_t *bytes, uint8_t *encryption_key)
64{ 102{
65 if (length + crypto_box_MACBYTES > MAX_DATA_SIZE || length == 0) 103 uint8_t contents[COOKIE_CONTENTS_LENGTH];
104 uint64_t temp_time = unix_time();
105 memcpy(contents, &temp_time, sizeof(temp_time));
106 memcpy(contents + sizeof(temp_time), bytes, COOKIE_DATA_LENGTH);
107 new_nonce(cookie);
108 int len = encrypt_data_symmetric(encryption_key, cookie, contents, sizeof(contents), cookie + crypto_box_NONCEBYTES);
109
110 if (len != COOKIE_LENGTH - crypto_box_NONCEBYTES)
66 return -1; 111 return -1;
67 112
68 uint8_t temp_plain[MAX_DATA_SIZE + crypto_box_ZEROBYTES] = {0}; 113 return 0;
69 uint8_t temp_encrypted[MAX_DATA_SIZE + crypto_box_BOXZEROBYTES]; 114}
115
116/* Open cookie of length COOKIE_LENGTH to bytes of length COOKIE_DATA_LENGTH using encryption_key
117 *
118 * return -1 on failure.
119 * return 0 on success.
120 */
121static int open_cookie(uint8_t *bytes, uint8_t *cookie, uint8_t *encryption_key)
122{
123 uint8_t contents[COOKIE_CONTENTS_LENGTH];
124 int len = decrypt_data_symmetric(encryption_key, cookie, cookie + crypto_box_NONCEBYTES,
125 COOKIE_LENGTH - crypto_box_NONCEBYTES, contents);
70 126
71 memcpy(temp_plain + crypto_box_ZEROBYTES, plain, length); // Pad the message with 32 0 bytes. 127 if (len != sizeof(contents))
128 return -1;
72 129
73 crypto_box_afternm(temp_encrypted, temp_plain, length + crypto_box_ZEROBYTES, nonce, enc_key); 130 uint64_t cookie_time;
131 memcpy(&cookie_time, contents, sizeof(cookie_time));
132 uint64_t temp_time = unix_time();
74 133
75 if (crypto_iszero(temp_encrypted, crypto_box_BOXZEROBYTES) != 0) 134 if (cookie_time + COOKIE_TIMEOUT < temp_time || temp_time < cookie_time)
76 return -1; 135 return -1;
77 136
78 /* Unpad the encrypted message. */ 137 memcpy(bytes, contents + sizeof(cookie_time), COOKIE_DATA_LENGTH);
79 memcpy(encrypted, temp_encrypted + crypto_box_BOXZEROBYTES, length + crypto_box_MACBYTES); 138 return 0;
80 return length + crypto_box_MACBYTES;
81} 139}
82 140
83/* Fast decrypt. Depends on enc_ley from encrypt_precompute. */ 141
84int decrypt_data_fast(uint8_t *enc_key, uint8_t *nonce, 142/* Create a cookie response packet and put it in packet.
85 uint8_t *encrypted, uint32_t length, uint8_t *plain) 143 * request_plain must be COOKIE_REQUEST_PLAIN_LENGTH bytes.
144 * packet must be of size COOKIE_RESPONSE_LENGTH or bigger.
145 *
146 * return -1 on failure.
147 * return COOKIE_RESPONSE_LENGTH on success.
148 */
149static int create_cookie_response(Net_Crypto *c, uint8_t *packet, uint8_t *request_plain, uint8_t *shared_key)
86{ 150{
87 if (length > MAX_DATA_SIZE || length <= crypto_box_BOXZEROBYTES) 151 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
152
153 if (create_cookie(plain, request_plain, c->secret_symmetric_key) != 0)
88 return -1; 154 return -1;
89 155
90 uint8_t temp_plain[MAX_DATA_SIZE + crypto_box_ZEROBYTES]; 156 memcpy(plain + COOKIE_LENGTH, request_plain + COOKIE_DATA_LENGTH, sizeof(uint64_t));
91 uint8_t temp_encrypted[MAX_DATA_SIZE + crypto_box_BOXZEROBYTES] = {0}; 157 packet[0] = NET_PACKET_COOKIE_RESPONSE;
158 new_nonce(packet + 1);
159 int len = encrypt_data_symmetric(shared_key, packet + 1, plain, sizeof(plain), packet + 1 + crypto_box_NONCEBYTES);
160
161 if (len != COOKIE_RESPONSE_LENGTH - (1 + crypto_box_NONCEBYTES))
162 return -1;
92 163
93 memcpy(temp_encrypted + crypto_box_BOXZEROBYTES, encrypted, length); // Pad the message with 16 0 bytes. 164 return COOKIE_RESPONSE_LENGTH;
165}
94 166
95 if (crypto_box_open_afternm(temp_plain, temp_encrypted, length + crypto_box_BOXZEROBYTES, 167/* Handle the cookie request packet of length length.
96 nonce, enc_key) == -1) 168 * Put what was in the request in request_plain (must be of size COOKIE_REQUEST_PLAIN_LENGTH)
169 * Put the key used to decrypt the request into shared_key (of size crypto_box_BEFORENMBYTES) for use in the response.
170 *
171 * return -1 on failure.
172 * return 0 on success.
173 */
174static int handle_cookie_request(Net_Crypto *c, uint8_t *request_plain, uint8_t *shared_key, uint8_t *packet,
175 uint16_t length)
176{
177 if (length != COOKIE_REQUEST_LENGTH)
97 return -1; 178 return -1;
98 179
99 /* If decryption is successful the first crypto_box_ZEROBYTES of the message will be zero. 180 DHT_get_shared_key_sent(c->dht, shared_key, packet + 1);
100 * Apparently memcmp should not be used so we do this instead: 181 int len = decrypt_data_symmetric(shared_key, packet + 1 + crypto_box_PUBLICKEYBYTES,
101 */ 182 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES,
102 if (crypto_iszero(temp_plain, crypto_box_ZEROBYTES) != 0) 183 request_plain);
184
185 if (len != COOKIE_REQUEST_PLAIN_LENGTH)
103 return -1; 186 return -1;
104 187
105 /* Unpad the plain message. */ 188 return 0;
106 memcpy(plain, temp_plain + crypto_box_ZEROBYTES, length - crypto_box_MACBYTES);
107 return length - crypto_box_MACBYTES;
108} 189}
109 190
110int encrypt_data(uint8_t *public_key, uint8_t *secret_key, uint8_t *nonce, 191/* Handle the cookie request packet (for raw UDP)
111 uint8_t *plain, uint32_t length, uint8_t *encrypted) 192 */
193static int udp_handle_cookie_request(void *object, IP_Port source, uint8_t *packet, uint32_t length)
112{ 194{
113 uint8_t k[crypto_box_BEFORENMBYTES]; 195 Net_Crypto *c = object;
114 encrypt_precompute(public_key, secret_key, k); 196 uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
115 return encrypt_data_fast(k, nonce, plain, length, encrypted); 197 uint8_t shared_key[crypto_box_BEFORENMBYTES];
198
199 if (handle_cookie_request(c, request_plain, shared_key, packet, length) != 0)
200 return 1;
201
202 uint8_t data[COOKIE_RESPONSE_LENGTH];
203
204 if (create_cookie_response(c, data, request_plain, shared_key) != sizeof(data))
205 return 1;
206
207 if ((uint32_t)sendpacket(c->dht->net, source, data, sizeof(data)) != sizeof(data))
208 return 1;
209
210 return 0;
116} 211}
117 212
118int decrypt_data(uint8_t *public_key, uint8_t *secret_key, uint8_t *nonce, 213/* Handle a cookie response packet of length encrypted with shared_key.
119 uint8_t *encrypted, uint32_t length, uint8_t *plain) 214 * put the cookie in the response in cookie
215 *
216 * cookie must be of length COOKIE_LENGTH.
217 *
218 * return -1 on failure.
219 * return COOKIE_LENGTH on success.
220 */
221static int handle_cookie_response(uint8_t *cookie, uint64_t *number, uint8_t *packet, uint32_t length,
222 uint8_t *shared_key)
120{ 223{
121 uint8_t k[crypto_box_BEFORENMBYTES]; 224 if (length != COOKIE_RESPONSE_LENGTH)
122 encrypt_precompute(public_key, secret_key, k); 225 return -1;
123 return decrypt_data_fast(k, nonce, encrypted, length, plain); 226
227 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
228 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES,
229 length - (1 + crypto_box_NONCEBYTES), plain);
230
231 if (len != sizeof(plain))
232 return -1;
233
234 memcpy(cookie, plain, COOKIE_LENGTH);
235 memcpy(number, plain + COOKIE_LENGTH, sizeof(uint64_t));
236 return COOKIE_LENGTH;
124} 237}
125 238
126int encrypt_data_symmetric(uint8_t *secret_key, uint8_t *nonce, uint8_t *plain, uint32_t length, uint8_t *encrypted) 239#define HANDSHAKE_PACKET_LENGTH (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES + COOKIE_LENGTH + crypto_box_MACBYTES)
240
241/* Create a handshake packet and put it in packet.
242 * cookie must be COOKIE_LENGTH bytes.
243 * packet must be of size HANDSHAKE_PACKET_LENGTH or bigger.
244 *
245 * return -1 on failure.
246 * return HANDSHAKE_PACKET_LENGTH on success.
247 */
248static int create_crypto_handshake(Net_Crypto *c, uint8_t *packet, uint8_t *cookie, uint8_t *nonce, uint8_t *session_pk,
249 uint8_t *peer_real_pk)
127{ 250{
128 if (length == 0) 251 uint8_t plain[crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES + COOKIE_LENGTH];
252 memcpy(plain, nonce, crypto_box_NONCEBYTES);
253 memcpy(plain + crypto_box_NONCEBYTES, session_pk, crypto_box_PUBLICKEYBYTES);
254 crypto_hash_sha512(plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, cookie, COOKIE_LENGTH);
255 uint8_t cookie_plain[COOKIE_DATA_LENGTH];
256 memcpy(cookie_plain, peer_real_pk, crypto_box_PUBLICKEYBYTES);
257 memcpy(cookie_plain + crypto_box_PUBLICKEYBYTES, c->self_public_key, crypto_box_PUBLICKEYBYTES);
258
259 if (create_cookie(plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES, cookie_plain,
260 c->secret_symmetric_key) != 0)
129 return -1; 261 return -1;
130 262
131 uint8_t temp_plain[length + crypto_secretbox_ZEROBYTES]; 263 new_nonce(packet + 1 + COOKIE_LENGTH);
132 uint8_t temp_encrypted[length + crypto_secretbox_MACBYTES + crypto_secretbox_BOXZEROBYTES]; 264 int len = encrypt_data(peer_real_pk, c->self_secret_key, packet + 1 + COOKIE_LENGTH, plain, sizeof(plain),
265 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES);
266
267 if (len != HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES))
268 return -1;
133 269
134 memset(temp_plain, 0, crypto_secretbox_ZEROBYTES); 270 packet[0] = NET_PACKET_CRYPTO_HS;
135 memcpy(temp_plain + crypto_secretbox_ZEROBYTES, plain, length); // Pad the message with 32 0 bytes. 271 memcpy(packet + 1, cookie, COOKIE_LENGTH);
136 272
137 crypto_secretbox(temp_encrypted, temp_plain, length + crypto_secretbox_ZEROBYTES, nonce, secret_key); 273 return HANDSHAKE_PACKET_LENGTH;
138 /* Unpad the encrypted message. */
139 memcpy(encrypted, temp_encrypted + crypto_secretbox_BOXZEROBYTES, length + crypto_secretbox_MACBYTES);
140 return length + crypto_secretbox_MACBYTES;
141} 274}
142 275
143int decrypt_data_symmetric(uint8_t *secret_key, uint8_t *nonce, uint8_t *encrypted, uint32_t length, uint8_t *plain) 276/* Handle a crypto handshake packet of length.
277 * put the nonce contained in the packet in nonce,
278 * the session public key in session_pk
279 * the real public key of the peer in peer_real_pk and
280 * the cookie inside the encrypted part of the packet in cookie.
281 *
282 * if expected_real_pk isn't NULL it denotes the real public key
283 * the packet should be from.
284 *
285 * nonce must be at least crypto_box_NONCEBYTES
286 * session_pk must be at least crypto_box_PUBLICKEYBYTES
287 * peer_real_pk must be at least crypto_box_PUBLICKEYBYTES
288 * cookie must be at least COOKIE_LENGTH
289 *
290 * return -1 on failure.
291 * return 0 on success.
292 */
293static int handle_crypto_handshake(Net_Crypto *c, uint8_t *nonce, uint8_t *session_pk, uint8_t *peer_real_pk,
294 uint8_t *cookie, uint8_t *packet, uint32_t length, uint8_t *expected_real_pk)
144{ 295{
145 if (length <= crypto_secretbox_BOXZEROBYTES) 296 if (length != HANDSHAKE_PACKET_LENGTH)
146 return -1; 297 return -1;
147 298
148 uint8_t temp_plain[length + crypto_secretbox_ZEROBYTES]; 299 uint8_t cookie_plain[COOKIE_DATA_LENGTH];
149 uint8_t temp_encrypted[length + crypto_secretbox_BOXZEROBYTES];
150 300
151 memset(temp_plain, 0, crypto_secretbox_BOXZEROBYTES); 301 if (open_cookie(cookie_plain, packet + 1, c->secret_symmetric_key) != 0)
152 memcpy(temp_encrypted + crypto_secretbox_BOXZEROBYTES, encrypted, length); // Pad the message with 16 0 bytes. 302 return -1;
153 303
154 if (crypto_secretbox_open(temp_plain, temp_encrypted, length + crypto_secretbox_BOXZEROBYTES, nonce, secret_key) == -1) 304 if (expected_real_pk)
305 if (crypto_cmp(cookie_plain, expected_real_pk, crypto_box_PUBLICKEYBYTES) != 0)
306 return -1;
307
308 if (crypto_cmp(cookie_plain + crypto_box_PUBLICKEYBYTES, c->self_public_key, crypto_box_PUBLICKEYBYTES) != 0)
155 return -1; 309 return -1;
156 310
157 memcpy(plain, temp_plain + crypto_secretbox_ZEROBYTES, length - crypto_secretbox_MACBYTES); 311 uint8_t cookie_hash[crypto_hash_sha512_BYTES];
158 return length - crypto_secretbox_MACBYTES; 312 crypto_hash_sha512(cookie_hash, packet + 1, COOKIE_LENGTH);
313
314 uint8_t plain[crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES + COOKIE_LENGTH];
315 int len = decrypt_data(cookie_plain, c->self_secret_key, packet + 1 + COOKIE_LENGTH,
316 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES,
317 HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES), plain);
318
319 if (len != sizeof(plain))
320 return -1;
321
322 if (memcmp(cookie_hash, plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, crypto_hash_sha512_BYTES) != 0)
323 return -1;
324
325 memcpy(nonce, plain, crypto_box_NONCEBYTES);
326 memcpy(session_pk, plain + crypto_box_NONCEBYTES, crypto_box_PUBLICKEYBYTES);
327 memcpy(cookie, plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES, COOKIE_LENGTH);
328 memcpy(peer_real_pk, cookie_plain, crypto_box_PUBLICKEYBYTES);
329 return 0;
330}
331
332
333static Crypto_Connection *get_crypto_connection(Net_Crypto *c, int crypt_connection_id)
334{
335 if (crypt_connection_id_not_valid(c, crypt_connection_id))
336 return 0;
337
338 return &c->crypto_connections[crypt_connection_id];
159} 339}
160 340
161/* Increment the given nonce by 1. */ 341
162void increment_nonce(uint8_t *nonce) 342/* Sends a packet to the peer using the fastest route.
343 *
344 * return -1 on failure.
345 * return 0 on success.
346 */
347static int send_packet_to(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint16_t length)
163{ 348{
164 uint32_t i; 349//TODO TCP, etc...
350 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
165 351
166 for (i = 0; i < crypto_box_NONCEBYTES; ++i) { 352 if (conn == 0)
167 ++nonce[i]; 353 return -1;
168 354
169 if (nonce[i] != 0) 355 if ((uint32_t)sendpacket(c->dht->net, conn->ip_port, data, length) != length)
170 break; 356 return -1;
171 } 357
358 return 0;
172} 359}
173 360
174#if crypto_box_NONCEBYTES != crypto_secretbox_NONCEBYTES 361/** START: Array Related functions **/
175/*if they no longer equal each other, this function must be split into two.*/ 362
176#error random_nonce(): crypto_box_NONCEBYTES must equal crypto_secretbox_NONCEBYTES. 363
177#endif 364/* Return number of packets in array
178/* Fill the given nonce with random bytes. */ 365 * Note that holes are counted too.
179void random_nonce(uint8_t *nonce) 366 */
367static uint32_t num_packets_array(Packets_Array *array)
180{ 368{
181 randombytes(nonce, crypto_box_NONCEBYTES); 369 return array->buffer_end - array->buffer_start;
182} 370}
183 371
184/* Fill a key crypto_secretbox_KEYBYTES big with random bytes */ 372/* Add data with packet number to array.
185void new_symmetric_key(uint8_t *key) 373 *
374 * return -1 on failure.
375 * return 0 on success.
376 */
377static int add_data_to_buffer(Packets_Array *array, uint32_t number, Packet_Data *data)
186{ 378{
187 randombytes(key, crypto_secretbox_KEYBYTES); 379 if (number - array->buffer_start > CRYPTO_PACKET_BUFFER_SIZE)
380 return -1;
381
382 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
383
384 if (array->buffer[num])
385 return -1;
386
387 Packet_Data *new_d = malloc(sizeof(Packet_Data));
388
389 if (new_d == NULL)
390 return -1;
391
392 memcpy(new_d, data, sizeof(Packet_Data));
393 array->buffer[num] = new_d;
394
395 if ((number - array->buffer_start) >= (array->buffer_end - array->buffer_start))
396 array->buffer_end = number + 1;
397
398 return 0;
188} 399}
189 400
190static uint8_t base_nonce[crypto_box_NONCEBYTES]; 401/* Get pointer of data with packet number.
191static uint8_t nonce_set = 0; 402 *
403 * return -1 on failure.
404 * return 0 if data at number is empty.
405 * return 1 if data pointer was put in data.
406 */
407static int get_data_pointer(Packets_Array *array, Packet_Data **data, uint32_t number)
408{
409 uint32_t num_spots = array->buffer_end - array->buffer_start;
410
411 if (array->buffer_end - number > num_spots || number - array->buffer_start >= num_spots)
412 return -1;
192 413
193#if crypto_box_NONCEBYTES != crypto_secretbox_NONCEBYTES 414 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
194/*if they no longer equal each other, this function must be split into two.*/ 415
195#error new_nonce(): crypto_box_NONCEBYTES must equal crypto_secretbox_NONCEBYTES. 416 if (!array->buffer[num])
196#endif 417 return 0;
197/* Gives a nonce guaranteed to be different from previous ones.*/ 418
198void new_nonce(uint8_t *nonce) 419 *data = array->buffer[num];
420 return 1;
421}
422
423/* Add data to end of array.
424 *
425 * return -1 on failure.
426 * return packet number on success.
427 */
428static int64_t add_data_end_of_buffer(Packets_Array *array, Packet_Data *data)
199{ 429{
200 if (nonce_set == 0) { 430 if (num_packets_array(array) >= CRYPTO_PACKET_BUFFER_SIZE)
201 random_nonce(base_nonce); 431 return -1;
202 nonce_set = 1;
203 }
204 432
205 increment_nonce(base_nonce); 433 Packet_Data *new_d = malloc(sizeof(Packet_Data));
206 memcpy(nonce, base_nonce, crypto_box_NONCEBYTES); 434
435 if (new_d == NULL)
436 return -1;
437
438 memcpy(new_d, data, sizeof(Packet_Data));
439 uint32_t id = array->buffer_end;
440 array->buffer[id % CRYPTO_PACKET_BUFFER_SIZE] = new_d;
441 ++array->buffer_end;
442 return id;
207} 443}
208 444
445/* Read data from begginning of array.
446 *
447 * return -1 on failure.
448 * return packet number on success.
449 */
450static int64_t read_data_beg_buffer(Packets_Array *array, Packet_Data *data)
451{
452 if (array->buffer_end == array->buffer_start)
453 return -1;
454
455 uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE;
456
457 if (!array->buffer[num])
458 return -1;
209 459
210/* return 0 if there is no received data in the buffer. 460 memcpy(data, array->buffer[num], sizeof(Packet_Data));
211 * return -1 if the packet was discarded. 461 uint32_t id = array->buffer_start;
212 * return length of received data if successful. 462 ++array->buffer_start;
463 free(array->buffer[num]);
464 array->buffer[num] = NULL;
465 return id;
466}
467
468/* Delete all packets in array before number (but not number)
469 *
470 * return -1 on failure.
471 * return 0 on success
213 */ 472 */
214int read_cryptpacket(Net_Crypto *c, int crypt_connection_id, uint8_t *data) 473static int clear_buffer_until(Packets_Array *array, uint32_t number)
215{ 474{
216 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 475 uint32_t num_spots = array->buffer_end - array->buffer_start;
217 return 0;
218 476
219 if (c->crypto_connections[crypt_connection_id].status != CRYPTO_CONN_ESTABLISHED) 477 if (array->buffer_end - number >= num_spots || number - array->buffer_start > num_spots)
220 return 0; 478 return -1;
221 479
222 uint8_t temp_data[MAX_DATA_SIZE]; 480 uint32_t i;
223 int length = read_packet(c->lossless_udp, c->crypto_connections[crypt_connection_id].number, temp_data);
224 481
225 if (length == 0) 482 for (i = array->buffer_start; i != number; ++i) {
226 return 0; 483 uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
227 484
228 if (temp_data[0] != 3) 485 if (array->buffer[num]) {
486 free(array->buffer[num]);
487 array->buffer[num] = NULL;
488 }
489 }
490
491 array->buffer_start = i;
492 return 0;
493}
494
495/* Create a packet request packet from recv_array and send_buffer_end into
496 * data of length.
497 *
498 * return -1 on failure.
499 * return length of packet on success.
500 */
501static int generate_request_packet(uint8_t *data, uint16_t length, Packets_Array *recv_array, uint32_t send_buffer_end)
502{
503 if (length <= (sizeof(uint32_t) * 2))
229 return -1; 504 return -1;
230 505
231 int len = decrypt_data_fast(c->crypto_connections[crypt_connection_id].shared_key, 506 uint32_t recv_buffer_start = htonl(recv_array->buffer_start);
232 c->crypto_connections[crypt_connection_id].recv_nonce, 507 send_buffer_end = htonl(send_buffer_end);
233 temp_data + 1, length - 1, data); 508 memcpy(data, &recv_buffer_start, sizeof(uint32_t));
509 memcpy(data + sizeof(uint32_t), &send_buffer_end, sizeof(uint32_t));
510 data[sizeof(uint32_t) * 2] = PACKET_ID_REQUEST;
234 511
235 if (len != -1) { 512 uint16_t cur_len = sizeof(uint32_t) * 2 + 1;
236 increment_nonce(c->crypto_connections[crypt_connection_id].recv_nonce); 513
237 return len; 514 if (recv_array->buffer_start == recv_array->buffer_end)
515 return cur_len;
516
517 if (length <= cur_len)
518 return cur_len;
519
520 uint32_t i, n = 1;
521
522 for (i = recv_array->buffer_start; i != recv_array->buffer_end; ++i) {
523 uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
524
525 if (!recv_array->buffer[num]) {
526 data[cur_len] = n;
527 n = 0;
528 ++cur_len;
529
530 if (length <= cur_len)
531 return cur_len;
532
533 } else if (n == 255) {
534 data[cur_len] = 0;
535 n = 0;
536 ++cur_len;
537
538 if (length <= cur_len)
539 return cur_len;
540 }
541
542 ++n;
238 } 543 }
239 544
240 return -1; 545 return cur_len;
241} 546}
242 547
243/* returns the number of packet slots left in the sendbuffer. 548/* Handle a request data packet.
244 * return 0 if failure. 549 * Remove all the packets the other recieved from the array.
550 *
551 * return -1 on failure.
552 * return 0 on success.
245 */ 553 */
246uint32_t crypto_num_free_sendqueue_slots(Net_Crypto *c, int crypt_connection_id) 554static int handle_request_packet(Packets_Array *send_array, uint8_t *data, uint16_t length)
247{ 555{
248 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 556 if (length < 1)
557 return -1;
558
559 if (data[0] != PACKET_ID_REQUEST)
560 return -1;
561
562 if (length == 1)
249 return 0; 563 return 0;
250 564
251 return num_free_sendqueue_slots(c->lossless_udp, c->crypto_connections[crypt_connection_id].number); 565 ++data;
566 --length;
567
568 uint32_t i, n = 1;
569
570 for (i = send_array->buffer_start; i != send_array->buffer_end; ++i) {
571 if (length == 0)
572 break;
573
574 uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
575
576 if (n == data[0]) {
577 if (send_array->buffer[num]) {
578 send_array->buffer[num]->time = 0;
579 }
580
581 ++data;
582 --length;
583 n = 0;
584 } else {
585 free(send_array->buffer[num]);
586 send_array->buffer[num] = NULL;
587 }
588
589 if (n == 255) {
590 n = 1;
591
592 if (data[0] != 0)
593 return -1;
594
595 ++data;
596 --length;
597 } else {
598 ++n;
599 }
600 }
601
602 return 0;
252} 603}
253 604
254/* return 0 if data could not be put in packet queue. 605/** END: Array Related functions **/
255 * return 1 if data was put into the queue. 606
607#define MAX_DATA_DATA_PACKET_SIZE (MAX_CRYPTO_PACKET_SIZE - (1 + sizeof(uint16_t) + crypto_box_MACBYTES))
608
609/* Creates and sends a data packet to the peer using the fastest route.
610 *
611 * return -1 on failure.
612 * return 0 on success.
256 */ 613 */
257int write_cryptpacket(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint32_t length) 614static int send_data_packet(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint16_t length)
258{ 615{
259 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 616 if (length == 0 || length + (1 + sizeof(uint16_t) + crypto_box_MACBYTES) > MAX_CRYPTO_PACKET_SIZE)
260 return 0; 617 return -1;
261 618
262 if (length - crypto_box_BOXZEROBYTES + crypto_box_ZEROBYTES > MAX_DATA_SIZE - 1) 619 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
263 return 0;
264 620
265 if (c->crypto_connections[crypt_connection_id].status != CRYPTO_CONN_ESTABLISHED) 621 if (conn == 0)
266 return 0; 622 return -1;
267 623
268 uint8_t temp_data[MAX_DATA_SIZE]; 624 uint8_t packet[1 + sizeof(uint16_t) + length + crypto_box_MACBYTES];
269 int len = encrypt_data_fast(c->crypto_connections[crypt_connection_id].shared_key, 625 packet[0] = NET_PACKET_CRYPTO_DATA;
270 c->crypto_connections[crypt_connection_id].sent_nonce, 626 memcpy(packet + 1, conn->sent_nonce + (crypto_box_NONCEBYTES - sizeof(uint16_t)), sizeof(uint16_t));
271 data, length, temp_data + 1); 627 int len = encrypt_data_symmetric(conn->shared_key, conn->sent_nonce, data, length, packet + 1 + sizeof(uint16_t));
272 628
273 if (len == -1) 629 if (len + 1 + sizeof(uint16_t) != sizeof(packet))
274 return 0; 630 return -1;
275 631
276 temp_data[0] = 3; 632 increment_nonce(conn->sent_nonce);
633 conn->last_data_packet_sent = current_time_monotonic(); //TODO remove this.
634 return send_packet_to(c, crypt_connection_id, packet, sizeof(packet));
635}
277 636
278 if (write_packet(c->lossless_udp, c->crypto_connections[crypt_connection_id].number, temp_data, len + 1) == 0) 637/* Creates and sends a data packet with buffer_start and num to the peer using the fastest route.
279 return 0; 638 *
639 * return -1 on failure.
640 * return 0 on success.
641 */
642static int send_data_packet_helper(Net_Crypto *c, int crypt_connection_id, uint32_t buffer_start, uint32_t num,
643 uint8_t *data, uint32_t length)
644{
645 num = htonl(num);
646 buffer_start = htonl(buffer_start);
647 uint8_t packet[sizeof(uint32_t) + sizeof(uint32_t) + length];
648 memcpy(packet, &buffer_start, sizeof(uint32_t));
649 memcpy(packet + sizeof(uint32_t), &num, sizeof(uint32_t));
650 memcpy(packet + (sizeof(uint32_t) * 2), data, length);
651
652 return send_data_packet(c, crypt_connection_id, packet, sizeof(packet));
653}
280 654
281 increment_nonce(c->crypto_connections[crypt_connection_id].sent_nonce); 655/* return -1 if data could not be put in packet queue.
282 return 1; 656 * return positive packet number if data was put into the queue.
657 */
658static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint32_t length)
659{
660 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE)
661 return -1;
662
663 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
664
665 if (conn == 0)
666 return -1;
667
668 Packet_Data dt;
669 dt.time = current_time_monotonic();
670 dt.length = length;
671 memcpy(dt.data, data, length);
672 int64_t packet_num = add_data_end_of_buffer(&conn->send_array, &dt);
673
674 if (packet_num == -1)
675 return -1;
676
677 if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, data, length) != 0)
678 printf("send_data_packet failed\n");
679
680 return packet_num;
283} 681}
284 682
285/* Create a request to peer. 683/* Get the lowest 2 bytes from the nonce and convert
286 * send_public_key and send_secret_key are the pub/secret keys of the sender. 684 * them to host byte format before returning them.
287 * recv_public_key is public key of receiver. 685 */
288 * packet must be an array of MAX_DATA_SIZE big. 686static uint16_t get_nonce_uint16(uint8_t *nonce)
289 * Data represents the data we send with the request with length being the length of the data. 687{
290 * request_id is the id of the request (32 = friend request, 254 = ping request). 688 uint16_t num;
689 memcpy(&num, nonce + (crypto_box_NONCEBYTES - sizeof(uint16_t)), sizeof(uint16_t));
690 return ntohs(num);
691}
692
693#define DATA_NUM_THRESHOLD 21845
694
695/* Handle a data packet.
696 * Decrypt packet of length and put it into data.
697 * data must be at least MAX_DATA_DATA_PACKET_SIZE big.
291 * 698 *
292 * return -1 on failure. 699 * return -1 on failure.
293 * return the length of the created packet on success. 700 * return length of data on success.
294 */ 701 */
295int create_request(uint8_t *send_public_key, uint8_t *send_secret_key, uint8_t *packet, uint8_t *recv_public_key, 702static int handle_data_packet(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint8_t *packet, uint16_t length)
296 uint8_t *data, uint32_t length, uint8_t request_id)
297{ 703{
298 if (MAX_DATA_SIZE < length + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES) 704 if (length <= (1 + sizeof(uint16_t) + crypto_box_MACBYTES) || length > MAX_CRYPTO_PACKET_SIZE)
705 return -1;
706
707 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
708
709 if (conn == 0)
299 return -1; 710 return -1;
300 711
301 uint8_t nonce[crypto_box_NONCEBYTES]; 712 uint8_t nonce[crypto_box_NONCEBYTES];
302 uint8_t temp[MAX_DATA_SIZE]; 713 memcpy(nonce, conn->recv_nonce, crypto_box_NONCEBYTES);
303 memcpy(temp + 1, data, length); 714 uint16_t num_cur_nonce = get_nonce_uint16(nonce);
304 temp[0] = request_id; 715 uint16_t num;
305 new_nonce(nonce); 716 memcpy(&num, packet + 1, sizeof(uint16_t));
306 int len = encrypt_data(recv_public_key, send_secret_key, nonce, temp, length + 1, 717 num = ntohs(num);
307 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + packet); 718 uint16_t diff = num - num_cur_nonce;
719 increment_nonce_number(nonce, diff);
720 int len = decrypt_data_symmetric(conn->shared_key, nonce, packet + 1 + sizeof(uint16_t),
721 length - (1 + sizeof(uint16_t)), data);
722
723 if ((unsigned int)len != length - (1 + sizeof(uint16_t) + crypto_box_MACBYTES))
724 return -1;
308 725
309 if (len == -1) 726 if (diff > DATA_NUM_THRESHOLD * 2) {
727 increment_nonce_number(conn->recv_nonce, DATA_NUM_THRESHOLD);
728 }
729
730 return len;
731}
732
733/* Send a request packet.
734 *
735 * return -1 on failure.
736 * return 0 on success.
737 */
738static int send_request_packet(Net_Crypto *c, int crypt_connection_id)
739{
740 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
741
742 if (conn == 0)
310 return -1; 743 return -1;
311 744
312 packet[0] = NET_PACKET_CRYPTO; 745 uint8_t packet[MAX_DATA_DATA_PACKET_SIZE];
313 memcpy(packet + 1, recv_public_key, crypto_box_PUBLICKEYBYTES); 746 int len = generate_request_packet(packet, sizeof(packet), &conn->recv_array, conn->send_array.buffer_end);
314 memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES, send_public_key, crypto_box_PUBLICKEYBYTES); 747
315 memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES * 2, nonce, crypto_box_NONCEBYTES); 748 if (len == -1)
749 return -1;
316 750
317 return len + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES; 751 return send_data_packet(c, crypt_connection_id, packet, len);
318} 752}
319 753
320/* Puts the senders public key in the request in public_key, the data from the request 754/* Send up to max num previously requested data packets.
321 * in data if a friend or ping request was sent to us and returns the length of the data.
322 * packet is the request packet and length is its length.
323 * 755 *
324 * return -1 if not valid request. 756 * return -1 on failure.
757 * return 0 on success.
325 */ 758 */
326int handle_request(uint8_t *self_public_key, uint8_t *self_secret_key, uint8_t *public_key, uint8_t *data, 759static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint16_t max_num)
327 uint8_t *request_id, uint8_t *packet, uint16_t length)
328{ 760{
329 if (length > crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES && 761 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
330 length <= MAX_DATA_SIZE) {
331 if (memcmp(packet + 1, self_public_key, crypto_box_PUBLICKEYBYTES) == 0) {
332 memcpy(public_key, packet + 1 + crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES);
333 uint8_t nonce[crypto_box_NONCEBYTES];
334 uint8_t temp[MAX_DATA_SIZE];
335 memcpy(nonce, packet + 1 + crypto_box_PUBLICKEYBYTES * 2, crypto_box_NONCEBYTES);
336 int len1 = decrypt_data(public_key, self_secret_key, nonce,
337 packet + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES,
338 length - (crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1), temp);
339 762
340 if (len1 == -1 || len1 == 0) 763 if (conn == 0)
341 return -1; 764 return -1;
765
766 uint32_t i;
767
768 for (i = 0; i < max_num; ++i) {
769 Packet_Data *dt;
770 uint32_t packet_num = (i + conn->send_array.buffer_start);
771 int ret = get_data_pointer(&conn->send_array, &dt, packet_num);
342 772
343 request_id[0] = temp[0]; 773 if (ret == -1) {
344 --len1; 774 return -1;
345 memcpy(data, temp + 1, len1); 775 } else if (ret == 0) {
346 return len1; 776 continue;
347 } 777 }
348 }
349 778
350 return -1; 779 if (dt->time != 0) {
780 continue;
781 }
782
783 dt->time = current_time_monotonic();
784
785 if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, dt->data,
786 dt->length) != 0)
787 printf("send_data_packet failed\n");
788 }
351} 789}
352 790
353void cryptopacket_registerhandler(Net_Crypto *c, uint8_t byte, cryptopacket_handler_callback cb, void *object) 791
792/* Add a new temp packet to send repeatedly.
793 *
794 * return -1 on failure.
795 * return 0 on success.
796 */
797static int new_temp_packet(Net_Crypto *c, int crypt_connection_id, uint8_t *packet, uint16_t length)
354{ 798{
355 c->cryptopackethandlers[byte].function = cb; 799 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE)
356 c->cryptopackethandlers[byte].object = object; 800 return -1;
801
802 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
803
804 if (conn == 0)
805 return -1;
806
807 uint8_t *temp_packet = malloc(length);
808
809 if (temp_packet == 0)
810 return -1;
811
812 if (conn->temp_packet)
813 free(conn->temp_packet);
814
815 memcpy(temp_packet, packet, length);
816 conn->temp_packet = temp_packet;
817 conn->temp_packet_length = length;
818 conn->temp_packet_sent_time = 0;
819 conn->temp_packet_num_sent = 0;
820 return 0;
357} 821}
358 822
359static int cryptopacket_handle(void *object, IP_Port source, uint8_t *packet, uint32_t length) 823/* Clear the temp packet.
824 *
825 * return -1 on failure.
826 * return 0 on success.
827 */
828static int clear_temp_packet(Net_Crypto *c, int crypt_connection_id)
360{ 829{
361 DHT *dht = object; 830 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
362 831
363 if (packet[0] == NET_PACKET_CRYPTO) { 832 if (conn == 0)
364 if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES || 833 return -1;
365 length > MAX_DATA_SIZE + crypto_box_MACBYTES)
366 return 1;
367 834
368 if (memcmp(packet + 1, dht->self_public_key, crypto_box_PUBLICKEYBYTES) == 0) { // Check if request is for us. 835 if (conn->temp_packet)
369 uint8_t public_key[crypto_box_PUBLICKEYBYTES]; 836 free(conn->temp_packet);
370 uint8_t data[MAX_DATA_SIZE];
371 uint8_t number;
372 int len = handle_request(dht->self_public_key, dht->self_secret_key, public_key, data, &number, packet, length);
373 837
374 if (len == -1 || len == 0) 838 conn->temp_packet = 0;
375 return 1; 839 conn->temp_packet_length = 0;
840 conn->temp_packet_sent_time = 0;
841 conn->temp_packet_num_sent = 0;
842 return 0;
843}
376 844
377 if (!dht->c->cryptopackethandlers[number].function) return 1;
378 845
379 return dht->c->cryptopackethandlers[number].function(dht->c->cryptopackethandlers[number].object, source, public_key, 846/* Send the temp packet.
380 data, len); 847 *
848 * return -1 on failure.
849 * return 0 on success.
850 */
851static int send_temp_packet(Net_Crypto *c, int crypt_connection_id)
852{
853 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
381 854
382 } else { /* If request is not for us, try routing it. */ 855 if (conn == 0)
383 int retval = route_packet(dht, packet + 1, packet, length); 856 return -1;
384 857
385 if ((unsigned int)retval == length) 858 if (!conn->temp_packet)
386 return 0; 859 return -1;
387 }
388 }
389 860
390 return 1; 861 if (send_packet_to(c, crypt_connection_id, conn->temp_packet, conn->temp_packet_length) != 0)
862 return -1;
863
864 conn->temp_packet_sent_time = current_time_monotonic();
865 ++conn->temp_packet_num_sent;
866 return 0;
391} 867}
392 868
393/* Send a crypto handshake packet containing an encrypted secret nonce and session public key 869/* Create a handshake packet and set it as a temp packet.
394 * to peer with connection_id and public_key. 870 * cookie must be COOKIE_LENGTH.
395 * The packet is encrypted with a random nonce which is sent in plain text with the packet. 871 *
872 * return -1 on failure.
873 * return 0 on success.
396 */ 874 */
397static int send_cryptohandshake(Net_Crypto *c, int connection_id, uint8_t *public_key, uint8_t *secret_nonce, 875static int create_send_handshake(Net_Crypto *c, int crypt_connection_id, uint8_t *cookie)
398 uint8_t *session_key)
399{ 876{
400 uint8_t temp_data[MAX_DATA_SIZE]; 877 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
401 uint8_t temp[crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES];
402 uint8_t nonce[crypto_box_NONCEBYTES];
403 878
404 new_nonce(nonce); 879 if (conn == 0)
405 memcpy(temp, secret_nonce, crypto_box_NONCEBYTES); 880 return -1;
406 memcpy(temp + crypto_box_NONCEBYTES, session_key, crypto_box_PUBLICKEYBYTES);
407 881
408 int len = encrypt_data(public_key, c->self_secret_key, nonce, temp, crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 882 uint8_t handshake_packet[HANDSHAKE_PACKET_LENGTH];
409 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + temp_data);
410 883
411 if (len == -1) 884 if (create_crypto_handshake(c, handshake_packet, cookie, conn->sent_nonce, conn->sessionpublic_key,
412 return 0; 885 conn->public_key) != sizeof(handshake_packet))
886 return -1;
887
888 if (new_temp_packet(c, crypt_connection_id, handshake_packet, sizeof(handshake_packet)) != 0)
889 return -1;
413 890
414 temp_data[0] = 2; 891 send_temp_packet(c, crypt_connection_id);
415 memcpy(temp_data + 1, c->self_public_key, crypto_box_PUBLICKEYBYTES); 892 return 0;
416 memcpy(temp_data + 1 + crypto_box_PUBLICKEYBYTES, nonce, crypto_box_NONCEBYTES);
417 return write_packet(c->lossless_udp, connection_id, temp_data,
418 len + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
419} 893}
420 894
421/* Extract secret nonce, session public key and public_key from a packet(data) with length length. 895/* Handle a recieved data packet.
422 * 896 *
423 * return 1 if successful. 897 * return -1 on failure.
424 * return 0 if failure. 898 * return 0 on success.
425 */ 899 */
426static int handle_cryptohandshake(Net_Crypto *c, uint8_t *public_key, uint8_t *secret_nonce, 900static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, uint8_t *packet, uint16_t length)
427 uint8_t *session_key, uint8_t *data, uint16_t length)
428{ 901{
429 int pad = (- crypto_box_BOXZEROBYTES + crypto_box_ZEROBYTES); 902 if (length > MAX_CRYPTO_PACKET_SIZE || length <= CRYPTO_DATA_PACKET_MIN_SIZE)
903 return -1;
430 904
431 if (length != 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES 905 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
432 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + pad) { 906
433 return 0; 907 if (conn == 0)
908 return -1;
909
910 uint8_t data[MAX_DATA_DATA_PACKET_SIZE];
911 int len = handle_data_packet(c, crypt_connection_id, data, packet, length);
912
913 if (len <= (int)(sizeof(uint32_t) * 2))
914 return -1;
915
916 uint32_t buffer_start, num;
917 memcpy(&buffer_start, data, sizeof(uint32_t));
918 memcpy(&num, data + sizeof(uint32_t), sizeof(uint32_t));
919 buffer_start = ntohl(buffer_start);
920 num = ntohl(num);
921
922 if (buffer_start != conn->send_array.buffer_start && clear_buffer_until(&conn->send_array, buffer_start) != 0)
923 return -1;
924
925 uint8_t *real_data = data + (sizeof(uint32_t) * 2);
926 uint16_t real_length = len - (sizeof(uint32_t) * 2);
927
928 while (real_data[0] == 0) { /* Remove Padding */
929 ++real_data;
930 --real_length;
931
932 if (real_length == 0)
933 return -1;
434 } 934 }
435 935
436 if (data[0] != 2) 936 if (real_data[0] == PACKET_ID_REQUEST) {
437 return 0; 937 if (handle_request_packet(&conn->send_array, real_data, real_length) != 0) {
938 printf("fail %u %u\n", real_data[0], real_length);
939 return -1;
940 }
941
942 //TODO: use num.
943 } else {
944 Packet_Data dt;
945 dt.time = current_time_monotonic();
946 dt.length = real_length;
947 memcpy(dt.data, real_data, real_length);
438 948
439 uint8_t temp[crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES]; 949 if (add_data_to_buffer(&conn->recv_array, num, &dt) != 0)
950 return -1;
440 951
441 memcpy(public_key, data + 1, crypto_box_PUBLICKEYBYTES); 952 while (read_data_beg_buffer(&conn->recv_array, &dt) != -1) {
953 if (conn->connection_data_callback)
954 conn->connection_data_callback(conn->connection_data_callback_object, conn->connection_data_callback_id, dt.data,
955 dt.length);
956 }
442 957
443 int len = decrypt_data(public_key, c->self_secret_key, data + 1 + crypto_box_PUBLICKEYBYTES, 958 //send a data request packet for every x number of data packets recieved.
444 data + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, 959 ++conn->packet_counter;
445 crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + pad, temp);
446 960
447 if (len != crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES) 961 if (conn->packet_counter > (CRYPTO_PACKET_BUFFER_SIZE / 4)) {
448 return 0; 962 if (send_request_packet(c, crypt_connection_id) != 0)
963 return -1;
449 964
450 memcpy(secret_nonce, temp, crypto_box_NONCEBYTES); 965 conn->packet_counter = 0;
451 memcpy(session_key, temp + crypto_box_NONCEBYTES, crypto_box_PUBLICKEYBYTES); 966 }
452 return 1; 967 }
968
969 if (conn->status == CRYPTO_CONN_NOT_CONFIRMED) {
970 if (conn->connection_status_callback)
971 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 1);
972
973 clear_temp_packet(c, crypt_connection_id);
974 conn->status = CRYPTO_CONN_ESTABLISHED;
975 }
976
977 return 0;
453} 978}
454 979
455/* Get crypto connection id from public key of peer. 980/* Handle a packet that was recieved for the connection.
456 * 981 *
457 * return -1 if there are no connections like we are looking for. 982 * return -1 on failure.
458 * return id if it found it. 983 * return 0 on success.
459 */ 984 */
460static int getcryptconnection_id(Net_Crypto *c, uint8_t *public_key) 985static int handle_packet_connection(Net_Crypto *c, int crypt_connection_id, uint8_t *packet, uint16_t length)
461{ 986{
462 uint32_t i; 987 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE)
988 return -1;
463 989
464 for (i = 0; i < c->crypto_connections_length; ++i) { 990 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
465 if (c->crypto_connections[i].status != CRYPTO_CONN_NO_CONNECTION) 991
466 if (memcmp(public_key, c->crypto_connections[i].public_key, crypto_box_PUBLICKEYBYTES) == 0) 992 if (conn == 0)
467 return i; 993 return -1;
994
995 switch (packet[0]) {
996 case NET_PACKET_COOKIE_RESPONSE: {
997 if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING)
998 return -1;
999
1000 uint8_t cookie[COOKIE_LENGTH];
1001 uint64_t number;
1002
1003 if (handle_cookie_response(cookie, &number, packet, length, conn->shared_key) != sizeof(cookie))
1004 return -1;
1005
1006 if (number != conn->cookie_request_number)
1007 return -1;
1008
1009 if (create_send_handshake(c, crypt_connection_id, cookie) != 0)
1010 return -1;
1011
1012 conn->status = CRYPTO_CONN_HANDSHAKE_SENT;
1013 return 0;
1014 }
1015
1016 case NET_PACKET_CRYPTO_HS: {
1017 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT) {
1018 uint8_t peer_real_pk[crypto_box_PUBLICKEYBYTES];
1019 uint8_t cookie[COOKIE_LENGTH];
1020
1021 if (handle_crypto_handshake(c, conn->recv_nonce, conn->peersessionpublic_key, peer_real_pk, cookie, packet, length,
1022 conn->public_key) != 0)
1023 return -1;
1024
1025 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1026
1027 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING) {
1028 if (create_send_handshake(c, crypt_connection_id, cookie) != 0)
1029 return -1;
1030 }
1031
1032 conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1033 } else {
1034 return -1;
1035 }
1036
1037 return 0;
1038 }
1039
1040 case NET_PACKET_CRYPTO_DATA: {
1041 if (conn->status == CRYPTO_CONN_NOT_CONFIRMED || conn->status == CRYPTO_CONN_ESTABLISHED) {
1042 return handle_data_packet_helper(c, crypt_connection_id, packet, length);
1043 } else {
1044 return -1;
1045 }
1046
1047 return 0;
1048 }
1049
1050 default: {
1051 return -1;
1052 }
468 } 1053 }
469 1054
470 return -1; 1055 return 0;
471} 1056}
472 1057
473/* Set the size of the friend list to numfriends. 1058/* Set the size of the friend list to numfriends.
@@ -492,196 +1077,463 @@ static int realloc_cryptoconnection(Net_Crypto *c, uint32_t num)
492 return 0; 1077 return 0;
493} 1078}
494 1079
495/* Start a secure connection with other peer who has public_key and ip_port. 1080
1081/* Create a new empty crypto connection.
496 * 1082 *
497 * return -1 if failure. 1083 * return -1 on failure.
498 * return crypt_connection_id of the initialized connection if everything went well. 1084 * return connection id on success.
499 */ 1085 */
500int crypto_connect(Net_Crypto *c, uint8_t *public_key, IP_Port ip_port) 1086static int create_crypto_connection(Net_Crypto *c)
501{ 1087{
502 uint32_t i; 1088 uint32_t i;
503 int id_existing = getcryptconnection_id(c, public_key);
504 1089
505 if (id_existing != -1) { 1090 for (i = 0; i < c->crypto_connections_length; ++i) {
506 IP_Port c_ip = connection_ip(c->lossless_udp, c->crypto_connections[id_existing].number); 1091 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION)
507 1092 return i;
508 if (ipport_equal(&c_ip, &ip_port))
509 return -1;
510 } 1093 }
511 1094
512 if (realloc_cryptoconnection(c, c->crypto_connections_length + 1) == -1 1095 if (realloc_cryptoconnection(c, c->crypto_connections_length + 1) == -1)
513 || c->crypto_connections == NULL)
514 return -1; 1096 return -1;
515 1097
516 memset(&(c->crypto_connections[c->crypto_connections_length]), 0, sizeof(Crypto_Connection)); 1098 memset(&(c->crypto_connections[c->crypto_connections_length]), 0, sizeof(Crypto_Connection));
517 c->crypto_connections[c->crypto_connections_length].number = ~0; 1099 int id = c->crypto_connections_length;
1100 ++c->crypto_connections_length;
1101 return id;
1102}
518 1103
519 for (i = 0; i <= c->crypto_connections_length; ++i) { 1104/* Wipe a crypto connection.
520 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION) { 1105 *
521 int id_new = new_connection(c->lossless_udp, ip_port); 1106 * return -1 on failure.
1107 * return 0 on success.
1108 */
1109static int wipe_crypto_connection(Net_Crypto *c, int crypt_connection_id)
1110{
1111 if (crypt_connection_id_not_valid(c, crypt_connection_id))
1112 return -1;
522 1113
523 if (id_new == -1) 1114 uint32_t i;
524 return -1; 1115 memset(&(c->crypto_connections[crypt_connection_id]), 0 , sizeof(Crypto_Connection));
1116
1117 for (i = c->crypto_connections_length; i != 0; --i) {
1118 if (c->crypto_connections[i - 1].status != CRYPTO_CONN_NO_CONNECTION)
1119 break;
1120 }
1121
1122 if (c->crypto_connections_length != i) {
1123 c->crypto_connections_length = i;
1124 realloc_cryptoconnection(c, c->crypto_connections_length);
1125 }
525 1126
526 c->crypto_connections[i].number = id_new; 1127 return 0;
527 c->crypto_connections[i].status = CRYPTO_CONN_HANDSHAKE_SENT; 1128}
528 random_nonce(c->crypto_connections[i].recv_nonce);
529 memcpy(c->crypto_connections[i].public_key, public_key, crypto_box_PUBLICKEYBYTES);
530 crypto_box_keypair(c->crypto_connections[i].sessionpublic_key, c->crypto_connections[i].sessionsecret_key);
531 c->crypto_connections[i].timeout = unix_time() + CRYPTO_HANDSHAKE_TIMEOUT;
532 1129
533 if (c->crypto_connections_length == i) 1130/* Get crypto connection id from public key of peer.
534 ++c->crypto_connections_length; 1131 *
1132 * return -1 if there are no connections like we are looking for.
1133 * return id if it found it.
1134 */
1135static int getcryptconnection_id(Net_Crypto *c, uint8_t *public_key)
1136{
1137 uint32_t i;
535 1138
536 if (send_cryptohandshake(c, id_new, public_key, c->crypto_connections[i].recv_nonce, 1139 for (i = 0; i < c->crypto_connections_length; ++i) {
537 c->crypto_connections[i].sessionpublic_key) == 1) { 1140 if (c->crypto_connections[i].status != CRYPTO_CONN_NO_CONNECTION)
538 increment_nonce(c->crypto_connections[i].recv_nonce); 1141 if (memcmp(public_key, c->crypto_connections[i].public_key, crypto_box_PUBLICKEYBYTES) == 0)
539 return i; 1142 return i;
540 } 1143 }
541 1144
542 return -1; /* This should never happen. */ 1145 return -1;
543 } 1146}
1147
1148/* Add a source to the crypto connection.
1149 * This is to be used only when we have recieved a packet from that source.
1150 *
1151 * return -1 on failure.
1152 * return positive number on success.
1153 * 0 if source was a direct UDP connection.
1154 * TODO
1155 */
1156static int crypto_connection_add_source(Net_Crypto *c, int crypt_connection_id, IP_Port source)
1157{
1158 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1159
1160 if (conn == 0)
1161 return -1;
1162
1163 if (source.ip.family == AF_INET || source.ip.family == AF_INET6) {
1164 conn->ip_port = source;
1165 conn->direct_lastrecv_time = current_time_monotonic();
1166 return 0;
544 } 1167 }
545 1168
546 return -1; 1169 return -1;
547} 1170}
548 1171
549/* Handle an incoming connection. 1172
1173/* Set function to be called when someone requests a new connection to us.
1174 *
1175 * The set function should return -1 on failure and 0 on success.
550 * 1176 *
551 * return -1 if no crypto inbound connection. 1177 * n_c is only valid for the duration of the function call.
552 * return incoming connection id (Lossless_UDP one) if there is an incoming crypto connection. 1178 */
1179void new_connection_handler(Net_Crypto *c, int (*new_connection_callback)(void *object, New_Connection *n_c),
1180 void *object)
1181{
1182 c->new_connection_callback = new_connection_callback;
1183 c->new_connection_callback_object = object;
1184}
1185
1186/* Handle a handshake packet by someone who wants to initiate a new connection with us.
1187 * This calls the callback set by new_connection_handler() if the handshake is ok.
553 * 1188 *
554 * Put the public key of the peer in public_key, the secret_nonce from the handshake into secret_nonce 1189 * return -1 on failure.
555 * and the session public key for the connection in session_key. 1190 * return 0 on success.
556 * to accept it see: accept_crypto_inbound(...).
557 * to refuse it just call kill_connection(...) on the connection id.
558 */ 1191 */
559int crypto_inbound(Net_Crypto *c, uint8_t *public_key, uint8_t *secret_nonce, uint8_t *session_key) 1192static int handle_new_connection_handshake(Net_Crypto *c, IP_Port source, uint8_t *data, uint16_t length)
560{ 1193{
561 while (1) { 1194 New_Connection n_c;
562 int incoming_con = incoming_connection(c->lossless_udp, 1); 1195 n_c.cookie = malloc(COOKIE_LENGTH);
563 1196
564 if (incoming_con != -1) { 1197 if (n_c.cookie == NULL)
565 if (is_connected(c->lossless_udp, incoming_con) == LUDP_TIMED_OUT) { 1198 return -1;
566 kill_connection(c->lossless_udp, incoming_con);
567 continue;
568 }
569 1199
570 if (id_packet(c->lossless_udp, incoming_con) == 2) { 1200 n_c.source = source;
571 uint8_t temp_data[MAX_DATA_SIZE]; 1201 n_c.cookie_length = COOKIE_LENGTH;
572 uint16_t len = read_packet_silent(c->lossless_udp, incoming_con, temp_data);
573 1202
574 if (handle_cryptohandshake(c, public_key, secret_nonce, session_key, temp_data, len)) { 1203 if (handle_crypto_handshake(c, n_c.recv_nonce, n_c.peersessionpublic_key, n_c.public_key, n_c.cookie, data, length,
575 return incoming_con; 1204 0) != 0) {
576 } else { 1205 free(n_c.cookie);
577 kill_connection(c->lossless_udp, incoming_con); 1206 return -1;
578 } 1207 }
579 } else { 1208
580 kill_connection(c->lossless_udp, incoming_con); 1209 int crypt_connection_id = getcryptconnection_id(c, n_c.public_key);
1210
1211 if (crypt_connection_id != -1) {
1212 int ret = -1;
1213 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1214
1215 if (conn != 0 && (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT)) {
1216 memcpy(conn->recv_nonce, n_c.recv_nonce, crypto_box_NONCEBYTES);
1217 memcpy(conn->peersessionpublic_key, n_c.peersessionpublic_key, crypto_box_PUBLICKEYBYTES);
1218 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1219
1220 crypto_connection_add_source(c, crypt_connection_id, source);
1221
1222 if (create_send_handshake(c, crypt_connection_id, n_c.cookie) == 0) {
1223 conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1224 ret = 0;
581 } 1225 }
582 } else {
583 break;
584 } 1226 }
1227
1228 free(n_c.cookie);
1229 return ret;
585 } 1230 }
586 1231
587 return -1; 1232 int ret = c->new_connection_callback(c->new_connection_callback_object, &n_c);
1233 free(n_c.cookie);
1234 return ret;
588} 1235}
589 1236
590/* Kill a crypto connection. 1237/* Accept a crypto connection.
591 * 1238 *
592 * return 0 if killed successfully. 1239 * return -1 on failure.
593 * return 1 if there was a problem. 1240 * return connection id on success.
594 */ 1241 */
595int crypto_kill(Net_Crypto *c, int crypt_connection_id) 1242int accept_crypto_connection(Net_Crypto *c, New_Connection *n_c)
596{ 1243{
597 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 1244 if (getcryptconnection_id(c, n_c->public_key) != -1)
598 return 1; 1245 return -1;
599 1246
600 if (c->crypto_connections[crypt_connection_id].status != CRYPTO_CONN_NO_CONNECTION) { 1247 int crypt_connection_id = create_crypto_connection(c);
601 c->crypto_connections[crypt_connection_id].status = CRYPTO_CONN_NO_CONNECTION;
602 kill_connection(c->lossless_udp, c->crypto_connections[crypt_connection_id].number);
603 memset(&(c->crypto_connections[crypt_connection_id]), 0 , sizeof(Crypto_Connection));
604 c->crypto_connections[crypt_connection_id].number = ~0;
605 uint32_t i;
606 1248
607 for (i = c->crypto_connections_length; i != 0; --i) { 1249 if (crypt_connection_id == -1)
608 if (c->crypto_connections[i - 1].status != CRYPTO_CONN_NO_CONNECTION) 1250 return -1;
609 break;
610 }
611 1251
612 if (c->crypto_connections_length != i) { 1252 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
613 c->crypto_connections_length = i;
614 realloc_cryptoconnection(c, c->crypto_connections_length);
615 }
616 1253
617 return 0; 1254 if (conn == 0)
1255 return -1;
1256
1257 memcpy(conn->public_key, n_c->public_key, crypto_box_PUBLICKEYBYTES);
1258 memcpy(conn->recv_nonce, n_c->recv_nonce, crypto_box_NONCEBYTES);
1259 memcpy(conn->peersessionpublic_key, n_c->peersessionpublic_key, crypto_box_PUBLICKEYBYTES);
1260 random_nonce(conn->sent_nonce);
1261 crypto_box_keypair(conn->sessionpublic_key, conn->sessionsecret_key);
1262 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1263
1264 if (n_c->cookie_length != COOKIE_LENGTH)
1265 return -1;
1266
1267 if (create_send_handshake(c, crypt_connection_id, n_c->cookie) != 0)
1268 return -1;
1269
1270 send_temp_packet(c, crypt_connection_id);
1271 conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1272 crypto_connection_add_source(c, crypt_connection_id, n_c->source);
1273 return crypt_connection_id;
1274}
1275
1276/* Create a crypto connection.
1277 * If one to that real public key already exists, return it.
1278 *
1279 * return -1 on failure.
1280 * return connection id on success.
1281 */
1282int new_crypto_connection(Net_Crypto *c, uint8_t *real_public_key)
1283{
1284 int crypt_connection_id = getcryptconnection_id(c, real_public_key);
1285
1286 if (crypt_connection_id != -1)
1287 return crypt_connection_id;
1288
1289 crypt_connection_id = create_crypto_connection(c);
1290
1291 if (crypt_connection_id == -1)
1292 return -1;
1293
1294 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1295
1296 if (conn == 0)
1297 return -1;
1298
1299 memcpy(conn->public_key, real_public_key, crypto_box_PUBLICKEYBYTES);
1300 random_nonce(conn->sent_nonce);
1301 crypto_box_keypair(conn->sessionpublic_key, conn->sessionsecret_key);
1302 conn->status = CRYPTO_CONN_COOKIE_REQUESTING;
1303 return crypt_connection_id;
1304}
1305
1306/* Set the DHT public key of the crypto connection.
1307 *
1308 * return -1 on failure.
1309 * return 0 on success.
1310 */
1311int set_conection_dht_public_key(Net_Crypto *c, int crypt_connection_id, uint8_t *dht_public_key)
1312{
1313 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1314
1315 if (conn == 0)
1316 return -1;
1317
1318 if (conn->dht_public_key_set == 1 && memcmp(conn->dht_public_key, dht_public_key, crypto_box_PUBLICKEYBYTES) == 0)
1319 return -1;
1320
1321 memcpy(conn->dht_public_key, dht_public_key, crypto_box_PUBLICKEYBYTES);
1322 conn->dht_public_key_set = 1;
1323
1324 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING) {
1325 conn->cookie_request_number = random_64b();
1326 uint8_t cookie_request[COOKIE_REQUEST_LENGTH];
1327
1328 if (create_cookie_request(c, cookie_request, conn->dht_public_key, conn->public_key,
1329 conn->cookie_request_number, conn->shared_key) != sizeof(cookie_request))
1330 return -1;
1331
1332 if (new_temp_packet(c, crypt_connection_id, cookie_request, sizeof(cookie_request)) != 0)
1333 return -1;
1334 }//TODO
1335
1336 return 0;
1337}
1338
1339/* Set the direct ip of the crypto connection.
1340 *
1341 * return -1 on failure.
1342 * return 0 on success.
1343 */
1344int set_direct_ip_port(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port)
1345{
1346 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1347
1348 if (conn == 0)
1349 return -1;
1350
1351 if (!ipport_equal(&ip_port, &conn->ip_port)) {
1352 conn->ip_port = ip_port;
1353 conn->direct_lastrecv_time = 0;
618 } 1354 }
619 1355
620 return 1; 1356 return 0;
621} 1357}
622 1358
623/* Accept an incoming connection using the parameters provided by crypto_inbound. 1359/* Set function to be called when connection with crypt_connection_id goes connects/disconnects.
1360 *
1361 * The set function should return -1 on failure and 0 on success.
1362 * Note that if this function is set, the connection will clear itself on disconnect.
1363 * Object and id will be passed to this function untouched.
1364 * status is 1 if the connection is going online, 0 if it is going offline.
624 * 1365 *
625 * return -1 if not successful. 1366 * return -1 on failure.
626 * return the crypt_connection_id if successful. 1367 * return 0 on success.
627 */ 1368 */
628int accept_crypto_inbound(Net_Crypto *c, int connection_id, uint8_t *public_key, uint8_t *secret_nonce, 1369int connection_status_handler(Net_Crypto *c, int crypt_connection_id, int (*connection_status_callback)(void *object,
629 uint8_t *session_key) 1370 int id, uint8_t status), void *object, int id)
630{ 1371{
631 uint32_t i; 1372 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
632 1373
633 if (discard_packet(c->lossless_udp, connection_id) == -1) 1374 if (conn == 0)
634 return -1; 1375 return -1;
635 1376
636 /* 1377 conn->connection_status_callback = connection_status_callback;
637 * if(getcryptconnection_id(public_key) != -1) 1378 conn->connection_status_callback_object = object;
638 * { 1379 conn->connection_status_callback_id = id;
639 * return -1; 1380 return 0;
640 * } 1381}
641 */ 1382
1383/* Set function to be called when connection with crypt_connection_id receives a data packet of length.
1384 *
1385 * The set function should return -1 on failure and 0 on success.
1386 * Object and id will be passed to this function untouched.
1387 *
1388 * return -1 on failure.
1389 * return 0 on success.
1390 */
1391int connection_data_handler(Net_Crypto *c, int crypt_connection_id, int (*connection_data_callback)(void *object,
1392 int id, uint8_t *data, uint16_t length), void *object, int id)
1393{
1394 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
642 1395
643 if (realloc_cryptoconnection(c, c->crypto_connections_length + 1) == -1 1396 if (conn == 0)
644 || c->crypto_connections == NULL)
645 return -1; 1397 return -1;
646 1398
647 memset(&(c->crypto_connections[c->crypto_connections_length]), 0, sizeof(Crypto_Connection)); 1399 conn->connection_data_callback = connection_data_callback;
648 c->crypto_connections[c->crypto_connections_length].number = ~0; 1400 conn->connection_data_callback_object = object;
649 1401 conn->connection_data_callback_id = id;
650 for (i = 0; i <= c->crypto_connections_length; ++i) { 1402 return 0;
651 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION) { 1403}
652 c->crypto_connections[i].number = connection_id; 1404
653 c->crypto_connections[i].status = CRYPTO_CONN_NOT_CONFIRMED; 1405/* Get the crypto connection id from the ip_port.
654 c->crypto_connections[i].timeout = unix_time() + CRYPTO_HANDSHAKE_TIMEOUT; 1406 *
655 random_nonce(c->crypto_connections[i].recv_nonce); 1407 * return -1 on failure.
656 memcpy(c->crypto_connections[i].sent_nonce, secret_nonce, crypto_box_NONCEBYTES); 1408 * return connection id on success.
657 memcpy(c->crypto_connections[i].peersessionpublic_key, session_key, crypto_box_PUBLICKEYBYTES); 1409 */
658 increment_nonce(c->crypto_connections[i].sent_nonce); 1410static int crypto_id_ip_port(Net_Crypto *c, IP_Port ip_port)
659 memcpy(c->crypto_connections[i].public_key, public_key, crypto_box_PUBLICKEYBYTES); 1411{
660 1412 uint32_t i;
661 crypto_box_keypair(c->crypto_connections[i].sessionpublic_key, c->crypto_connections[i].sessionsecret_key); 1413
662 1414 for (i = 0; i < c->crypto_connections_length; ++i) {
663 if (c->crypto_connections_length == i) 1415 if (is_alive(c->crypto_connections[i].status))
664 ++c->crypto_connections_length; 1416 if (ipport_equal(&ip_port, &c->crypto_connections[i].ip_port))
665
666 if (send_cryptohandshake(c, connection_id, public_key, c->crypto_connections[i].recv_nonce,
667 c->crypto_connections[i].sessionpublic_key) == 1) {
668 increment_nonce(c->crypto_connections[i].recv_nonce);
669 uint32_t zero = 0;
670 encrypt_precompute(c->crypto_connections[i].peersessionpublic_key,
671 c->crypto_connections[i].sessionsecret_key,
672 c->crypto_connections[i].shared_key);
673 c->crypto_connections[i].status =
674 CRYPTO_CONN_ESTABLISHED; /* Connection status needs to be 3 for write_cryptpacket() to work. */
675 write_cryptpacket(c, i, ((uint8_t *)&zero), sizeof(zero));
676 c->crypto_connections[i].status = CRYPTO_CONN_NOT_CONFIRMED; /* Set it to its proper value right after. */
677 return i; 1417 return i;
678 } 1418 }
1419
1420 return -1;
1421}
1422
1423#define CRYPTO_MIN_PACKET_SIZE (1 + sizeof(uint16_t) + crypto_box_MACBYTES)
1424
1425/* Handle raw UDP packets coming directly from the socket.
1426 *
1427 * Handles:
1428 * Cookie response packets.
1429 * Crypto handshake packets.
1430 * Crypto data packets.
1431 *
1432 */
1433static int udp_handle_packet(void *object, IP_Port source, uint8_t *packet, uint32_t length)
1434{
1435 if (length <= CRYPTO_MIN_PACKET_SIZE || length > MAX_CRYPTO_PACKET_SIZE)
1436 return 1;
1437
1438 Net_Crypto *c = object;
1439 int crypt_connection_id = crypto_id_ip_port(c, source);
1440
1441 if (crypt_connection_id == -1) {
1442 if (packet[0] != NET_PACKET_CRYPTO_HS)
1443 return 1;
1444
1445 if (handle_new_connection_handshake(c, source, packet, length) != 0)
1446 return 1;
1447
1448 return 0;
1449 }
1450
1451 if (handle_packet_connection(c, crypt_connection_id, packet, length) != 0)
1452 return 1;
1453
1454 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1455
1456 if (conn == 0)
1457 return -1;
1458
1459 conn->direct_lastrecv_time = current_time_monotonic();
1460 return 0;
1461}
1462
1463static void send_crypto_packets(Net_Crypto *c)
1464{
1465 uint32_t i;
1466 uint64_t temp_time = current_time_monotonic();
1467
1468 for (i = 0; i < c->crypto_connections_length; ++i) {
1469 Crypto_Connection *conn = get_crypto_connection(c, i);
679 1470
680 return -1; /* This should never happen. */ 1471 if (conn == 0)
1472 return;
1473
1474 if (CRYPTO_SEND_PACKET_INTERVAL + conn->temp_packet_sent_time < temp_time) {
1475 send_temp_packet(c, i);
1476 }
1477
1478 if (conn->status >= CRYPTO_CONN_NOT_CONFIRMED
1479 && (CRYPTO_SEND_PACKET_INTERVAL + conn->last_data_packet_sent) < temp_time) {
1480 send_request_packet(c, i);
681 } 1481 }
1482
1483 //TODO
1484 send_requested_packets(c, i, ~0);
682 } 1485 }
1486}
683 1487
684 return -1; 1488
1489/* returns the number of packet slots left in the sendbuffer.
1490 * return 0 if failure.
1491 */
1492uint32_t crypto_num_free_sendqueue_slots(Net_Crypto *c, int crypt_connection_id)
1493{
1494 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1495
1496 if (conn == 0)
1497 return 0;
1498
1499 //TODO
1500 return CRYPTO_PACKET_BUFFER_SIZE - num_packets_array(&conn->send_array);
1501}
1502
1503
1504
1505
1506/* return -1 if data could not be put in packet queue.
1507 * return positive packet number if data was put into the queue.
1508 */
1509int64_t write_cryptpacket(Net_Crypto *c, int crypt_connection_id, uint8_t *data, uint32_t length)
1510{
1511 if (length == 0)
1512 return -1;
1513
1514 if (data[0] < CRYPTO_RESERVED_PACKETS)
1515 return -1;
1516
1517 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1518
1519 if (conn == 0)
1520 return -1;
1521
1522 if (conn->status != CRYPTO_CONN_ESTABLISHED)
1523 return -1;
1524
1525 return send_lossless_packet(c, crypt_connection_id, data, length);
1526}
1527
1528/* Kill a crypto connection.
1529 *
1530 * return -1 on failure.
1531 * return 0 on success.
1532 */
1533int crypto_kill(Net_Crypto *c, int crypt_connection_id)
1534{
1535 //TODO
1536 return wipe_crypto_connection(c, crypt_connection_id);
685} 1537}
686 1538
687/* return 0 if no connection. 1539/* return 0 if no connection.
@@ -721,97 +1573,14 @@ void load_keys(Net_Crypto *c, uint8_t *keys)
721 memcpy(c->self_secret_key, keys + crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES); 1573 memcpy(c->self_secret_key, keys + crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES);
722} 1574}
723 1575
724/* Handle received packets for not yet established crypto connections. */
725static void receive_crypto(Net_Crypto *c)
726{
727 uint32_t i;
728 uint64_t temp_time = unix_time();
729
730 for (i = 0; i < c->crypto_connections_length; ++i) {
731 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION)
732 continue;
733
734 if (c->crypto_connections[i].status == CRYPTO_CONN_HANDSHAKE_SENT) {
735 uint8_t temp_data[MAX_DATA_SIZE];
736 uint8_t secret_nonce[crypto_box_NONCEBYTES];
737 uint8_t public_key[crypto_box_PUBLICKEYBYTES];
738 uint8_t session_key[crypto_box_PUBLICKEYBYTES];
739 uint16_t len;
740
741 if (id_packet(c->lossless_udp, c->crypto_connections[i].number) == 2) { /* Handle handshake packet. */
742 len = read_packet(c->lossless_udp, c->crypto_connections[i].number, temp_data);
743
744 if (handle_cryptohandshake(c, public_key, secret_nonce, session_key, temp_data, len)) {
745 if (memcmp(public_key, c->crypto_connections[i].public_key, crypto_box_PUBLICKEYBYTES) == 0) {
746 memcpy(c->crypto_connections[i].sent_nonce, secret_nonce, crypto_box_NONCEBYTES);
747 memcpy(c->crypto_connections[i].peersessionpublic_key, session_key, crypto_box_PUBLICKEYBYTES);
748 increment_nonce(c->crypto_connections[i].sent_nonce);
749 uint32_t zero = 0;
750 encrypt_precompute(c->crypto_connections[i].peersessionpublic_key,
751 c->crypto_connections[i].sessionsecret_key,
752 c->crypto_connections[i].shared_key);
753 c->crypto_connections[i].status =
754 CRYPTO_CONN_ESTABLISHED; /* Connection status needs to be 3 for write_cryptpacket() to work. */
755 write_cryptpacket(c, i, ((uint8_t *)&zero), sizeof(zero));
756 c->crypto_connections[i].status = CRYPTO_CONN_NOT_CONFIRMED; /* Set it to its proper value right after. */
757 } else {
758 /* This should not happen, timeout the connection if it does. */
759 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
760 }
761 } else {
762 /* This should not happen, timeout the connection if it does. */
763 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
764 }
765 } else if (id_packet(c->lossless_udp,
766 c->crypto_connections[i].number) != (uint8_t)~0) {
767 /* This should not happen, timeout the connection if it does. */
768 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
769 }
770 }
771
772 if (c->crypto_connections[i].status == CRYPTO_CONN_NOT_CONFIRMED) {
773 if (id_packet(c->lossless_udp, c->crypto_connections[i].number) == 3) {
774 uint8_t temp_data[MAX_DATA_SIZE];
775 uint8_t data[MAX_DATA_SIZE];
776 int length = read_packet(c->lossless_udp, c->crypto_connections[i].number, temp_data);
777 int len = decrypt_data(c->crypto_connections[i].peersessionpublic_key,
778 c->crypto_connections[i].sessionsecret_key,
779 c->crypto_connections[i].recv_nonce, temp_data + 1, length - 1, data);
780 uint32_t zero = 0;
781
782 if (len == sizeof(uint32_t) && memcmp(((uint8_t *)&zero), data, sizeof(uint32_t)) == 0) {
783 increment_nonce(c->crypto_connections[i].recv_nonce);
784 encrypt_precompute(c->crypto_connections[i].peersessionpublic_key,
785 c->crypto_connections[i].sessionsecret_key,
786 c->crypto_connections[i].shared_key);
787 c->crypto_connections[i].status = CRYPTO_CONN_ESTABLISHED;
788 c->crypto_connections[i].timeout = ~0;
789 /* Connection is accepted. */
790 confirm_connection(c->lossless_udp, c->crypto_connections[i].number);
791 } else {
792 /* This should not happen, timeout the connection if it does. */
793 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
794 }
795 } else if (id_packet(c->lossless_udp, c->crypto_connections[i].number) != (uint8_t)~0) {
796 /* This should not happen, timeout the connection if it does. */
797 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
798 }
799 }
800
801 if (temp_time > c->crypto_connections[i].timeout) {
802 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT;
803 }
804 }
805}
806
807/* Run this to (re)initialize net_crypto. 1576/* Run this to (re)initialize net_crypto.
808 * Sets all the global connection variables to their default values. 1577 * Sets all the global connection variables to their default values.
809 */ 1578 */
810Net_Crypto *new_net_crypto(Networking_Core *net) 1579Net_Crypto *new_net_crypto(DHT *dht)
811{ 1580{
812 unix_time_update(); 1581 unix_time_update();
813 1582
814 if (net == NULL) 1583 if (dht == NULL)
815 return NULL; 1584 return NULL;
816 1585
817 Net_Crypto *temp = calloc(1, sizeof(Net_Crypto)); 1586 Net_Crypto *temp = calloc(1, sizeof(Net_Crypto));
@@ -819,31 +1588,50 @@ Net_Crypto *new_net_crypto(Networking_Core *net)
819 if (temp == NULL) 1588 if (temp == NULL)
820 return NULL; 1589 return NULL;
821 1590
822 temp->lossless_udp = new_lossless_udp(net); 1591 temp->dht = dht;
823
824 if (temp->lossless_udp == NULL) {
825 free(temp);
826 return NULL;
827 }
828 1592
829 new_keys(temp); 1593 new_keys(temp);
830 return temp; 1594 new_symmetric_key(temp->secret_symmetric_key);
831}
832 1595
833void init_cryptopackets(void *dht) 1596 networking_registerhandler(dht->net, NET_PACKET_COOKIE_REQUEST, &udp_handle_cookie_request, temp);
834{ 1597 networking_registerhandler(dht->net, NET_PACKET_COOKIE_RESPONSE, &udp_handle_packet, temp);
835 DHT *s_dht = dht; 1598 networking_registerhandler(dht->net, NET_PACKET_CRYPTO_HS, &udp_handle_packet, temp);
836 networking_registerhandler(s_dht->c->lossless_udp->net, NET_PACKET_CRYPTO, &cryptopacket_handle, s_dht); 1599 networking_registerhandler(dht->net, NET_PACKET_CRYPTO_DATA, &udp_handle_packet, temp);
1600 return temp;
837} 1601}
838 1602
839static void kill_timedout(Net_Crypto *c) 1603static void kill_timedout(Net_Crypto *c)
840{ 1604{
841 uint32_t i; 1605 uint32_t i;
1606 //uint64_t temp_time = current_time_monotonic();
842 1607
843 for (i = 0; i < c->crypto_connections_length; ++i) { 1608 for (i = 0; i < c->crypto_connections_length; ++i) {
844 if (c->crypto_connections[i].status != CRYPTO_CONN_NO_CONNECTION 1609 Crypto_Connection *conn = get_crypto_connection(c, i);
845 && is_connected(c->lossless_udp, c->crypto_connections[i].number) == LUDP_TIMED_OUT) 1610
846 c->crypto_connections[i].status = CRYPTO_CONN_TIMED_OUT; 1611 if (conn == 0)
1612 return;
1613
1614 if (conn->status == CRYPTO_CONN_NO_CONNECTION || conn->status == CRYPTO_CONN_TIMED_OUT)
1615 continue;
1616
1617 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT
1618 || conn->status == CRYPTO_CONN_NOT_CONFIRMED) {
1619 if (conn->temp_packet_num_sent < MAX_NUM_SENDPACKET_TRIES)
1620 continue;
1621
1622 if (conn->connection_status_callback) {
1623 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 0);
1624 crypto_kill(c, i);
1625 continue;
1626 }
1627
1628 conn->status = CRYPTO_CONN_TIMED_OUT;
1629 continue;
1630 }
1631
1632 if (conn->status == CRYPTO_CONN_ESTABLISHED) {
1633 //TODO: add a timeout here?
1634 }
847 } 1635 }
848} 1636}
849 1637
@@ -851,9 +1639,8 @@ static void kill_timedout(Net_Crypto *c)
851void do_net_crypto(Net_Crypto *c) 1639void do_net_crypto(Net_Crypto *c)
852{ 1640{
853 unix_time_update(); 1641 unix_time_update();
854 do_lossless_udp(c->lossless_udp);
855 kill_timedout(c); 1642 kill_timedout(c);
856 receive_crypto(c); 1643 send_crypto_packets(c);
857} 1644}
858 1645
859void kill_net_crypto(Net_Crypto *c) 1646void kill_net_crypto(Net_Crypto *c)
@@ -864,7 +1651,10 @@ void kill_net_crypto(Net_Crypto *c)
864 crypto_kill(c, i); 1651 crypto_kill(c, i);
865 } 1652 }
866 1653
867 kill_lossless_udp(c->lossless_udp); 1654 networking_registerhandler(c->dht->net, NET_PACKET_COOKIE_REQUEST, NULL, NULL);
1655 networking_registerhandler(c->dht->net, NET_PACKET_COOKIE_RESPONSE, NULL, NULL);
1656 networking_registerhandler(c->dht->net, NET_PACKET_CRYPTO_HS, NULL, NULL);
1657 networking_registerhandler(c->dht->net, NET_PACKET_CRYPTO_DATA, NULL, NULL);
868 memset(c, 0, sizeof(Net_Crypto)); 1658 memset(c, 0, sizeof(Net_Crypto));
869 free(c); 1659 free(c);
870} 1660}