In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / onion.c
blobae39f451f41a0465c3b9236b4eaca7621bb2f323
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file onion.c
9 * \brief Functions to queue create cells, wrap the various onionskin types,
10 * and parse and create the CREATE cell and its allies.
11 **/
13 #include "or.h"
14 #include "circuitlist.h"
15 #include "config.h"
16 #include "cpuworker.h"
17 #include "networkstatus.h"
18 #include "onion.h"
19 #include "onion_fast.h"
20 #include "onion_ntor.h"
21 #include "onion_tap.h"
22 #include "relay.h"
23 #include "rephist.h"
24 #include "router.h"
26 /** Type for a linked list of circuits that are waiting for a free CPU worker
27 * to process a waiting onion handshake. */
28 typedef struct onion_queue_t {
29 TOR_TAILQ_ENTRY(onion_queue_t) next;
30 or_circuit_t *circ;
31 uint16_t handshake_type;
32 create_cell_t *onionskin;
33 time_t when_added;
34 } onion_queue_t;
36 /** 5 seconds on the onion queue til we just send back a destroy */
37 #define ONIONQUEUE_WAIT_CUTOFF 5
39 /** Array of queues of circuits waiting for CPU workers. An element is NULL
40 * if that queue is empty.*/
41 TOR_TAILQ_HEAD(onion_queue_head_t, onion_queue_t)
42 ol_list[MAX_ONION_HANDSHAKE_TYPE+1] = {
43 TOR_TAILQ_HEAD_INITIALIZER(ol_list[0]), /* tap */
44 TOR_TAILQ_HEAD_INITIALIZER(ol_list[1]), /* fast */
45 TOR_TAILQ_HEAD_INITIALIZER(ol_list[2]), /* ntor */
48 /** Number of entries of each type currently in each element of ol_list[]. */
49 static int ol_entries[MAX_ONION_HANDSHAKE_TYPE+1];
51 static int num_ntors_per_tap(void);
52 static void onion_queue_entry_remove(onion_queue_t *victim);
54 /* XXXX024 Check lengths vs MAX_ONIONSKIN_{CHALLENGE,REPLY}_LEN.
56 * (By which I think I meant, "make sure that no
57 * X_ONIONSKIN_CHALLENGE/REPLY_LEN is greater than
58 * MAX_ONIONSKIN_CHALLENGE/REPLY_LEN." Also, make sure that we can pass
59 * over-large values via EXTEND2/EXTENDED2, for future-compatibility.*/
61 /** Return true iff we have room to queue another onionskin of type
62 * <b>type</b>. */
63 static int
64 have_room_for_onionskin(uint16_t type)
66 const or_options_t *options = get_options();
67 int num_cpus;
68 uint64_t tap_usec, ntor_usec;
69 uint64_t ntor_during_tap_usec, tap_during_ntor_usec;
71 /* If we've got fewer than 50 entries, we always have room for one more. */
72 if (ol_entries[type] < 50)
73 return 1;
74 num_cpus = get_num_cpus(options);
75 /* Compute how many microseconds we'd expect to need to clear all
76 * onionskins in various combinations of the queues. */
78 /* How long would it take to process all the TAP cells in the queue? */
79 tap_usec = estimated_usec_for_onionskins(
80 ol_entries[ONION_HANDSHAKE_TYPE_TAP],
81 ONION_HANDSHAKE_TYPE_TAP) / num_cpus;
83 /* How long would it take to process all the NTor cells in the queue? */
84 ntor_usec = estimated_usec_for_onionskins(
85 ol_entries[ONION_HANDSHAKE_TYPE_NTOR],
86 ONION_HANDSHAKE_TYPE_NTOR) / num_cpus;
88 /* How long would it take to process the tap cells that we expect to
89 * process while draining the ntor queue? */
90 tap_during_ntor_usec = estimated_usec_for_onionskins(
91 MIN(ol_entries[ONION_HANDSHAKE_TYPE_TAP],
92 ol_entries[ONION_HANDSHAKE_TYPE_NTOR] / num_ntors_per_tap()),
93 ONION_HANDSHAKE_TYPE_TAP) / num_cpus;
95 /* How long would it take to process the ntor cells that we expect to
96 * process while draining the tap queue? */
97 ntor_during_tap_usec = estimated_usec_for_onionskins(
98 MIN(ol_entries[ONION_HANDSHAKE_TYPE_NTOR],
99 ol_entries[ONION_HANDSHAKE_TYPE_TAP] * num_ntors_per_tap()),
100 ONION_HANDSHAKE_TYPE_NTOR) / num_cpus;
102 /* See whether that exceeds MaxOnionQueueDelay. If so, we can't queue
103 * this. */
104 if (type == ONION_HANDSHAKE_TYPE_NTOR &&
105 (ntor_usec + tap_during_ntor_usec) / 1000 >
106 (uint64_t)options->MaxOnionQueueDelay)
107 return 0;
109 if (type == ONION_HANDSHAKE_TYPE_TAP &&
110 (tap_usec + ntor_during_tap_usec) / 1000 >
111 (uint64_t)options->MaxOnionQueueDelay)
112 return 0;
114 #ifdef CURVE25519_ENABLED
115 /* If we support the ntor handshake, then don't let TAP handshakes use
116 * more than 2/3 of the space on the queue. */
117 if (type == ONION_HANDSHAKE_TYPE_TAP &&
118 tap_usec / 1000 > (uint64_t)options->MaxOnionQueueDelay * 2 / 3)
119 return 0;
120 #else
121 (void) type;
122 #endif
124 return 1;
127 /** Add <b>circ</b> to the end of ol_list and return 0, except
128 * if ol_list is too long, in which case do nothing and return -1.
131 onion_pending_add(or_circuit_t *circ, create_cell_t *onionskin)
133 onion_queue_t *tmp;
134 time_t now = time(NULL);
136 if (onionskin->handshake_type > MAX_ONION_HANDSHAKE_TYPE) {
137 log_warn(LD_BUG, "Handshake %d out of range! Dropping.",
138 onionskin->handshake_type);
139 return -1;
142 tmp = tor_malloc_zero(sizeof(onion_queue_t));
143 tmp->circ = circ;
144 tmp->handshake_type = onionskin->handshake_type;
145 tmp->onionskin = onionskin;
146 tmp->when_added = now;
148 if (!have_room_for_onionskin(onionskin->handshake_type)) {
149 #define WARN_TOO_MANY_CIRC_CREATIONS_INTERVAL (60)
150 static ratelim_t last_warned =
151 RATELIM_INIT(WARN_TOO_MANY_CIRC_CREATIONS_INTERVAL);
152 char *m;
153 if (onionskin->handshake_type == ONION_HANDSHAKE_TYPE_NTOR &&
154 (m = rate_limit_log(&last_warned, approx_time()))) {
155 log_warn(LD_GENERAL,
156 "Your computer is too slow to handle this many circuit "
157 "creation requests! Please consider using the "
158 "MaxAdvertisedBandwidth config option or choosing a more "
159 "restricted exit policy.%s",m);
160 tor_free(m);
162 tor_free(tmp);
163 return -1;
166 ++ol_entries[onionskin->handshake_type];
167 log_info(LD_OR, "New create (%s). Queues now ntor=%d and tap=%d.",
168 onionskin->handshake_type == ONION_HANDSHAKE_TYPE_NTOR ? "ntor" : "tap",
169 ol_entries[ONION_HANDSHAKE_TYPE_NTOR],
170 ol_entries[ONION_HANDSHAKE_TYPE_TAP]);
172 circ->onionqueue_entry = tmp;
173 TOR_TAILQ_INSERT_TAIL(&ol_list[onionskin->handshake_type], tmp, next);
175 /* cull elderly requests. */
176 while (1) {
177 onion_queue_t *head = TOR_TAILQ_FIRST(&ol_list[onionskin->handshake_type]);
178 if (now - head->when_added < (time_t)ONIONQUEUE_WAIT_CUTOFF)
179 break;
181 circ = head->circ;
182 circ->onionqueue_entry = NULL;
183 onion_queue_entry_remove(head);
184 log_info(LD_CIRC,
185 "Circuit create request is too old; canceling due to overload.");
186 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
188 return 0;
191 /** Return a fairness parameter, to prefer processing NTOR style
192 * handshakes but still slowly drain the TAP queue so we don't starve
193 * it entirely. */
194 static int
195 num_ntors_per_tap(void)
197 #define DEFAULT_NUM_NTORS_PER_TAP 10
198 #define MIN_NUM_NTORS_PER_TAP 1
199 #define MAX_NUM_NTORS_PER_TAP 100000
201 return networkstatus_get_param(NULL, "NumNTorsPerTAP",
202 DEFAULT_NUM_NTORS_PER_TAP,
203 MIN_NUM_NTORS_PER_TAP,
204 MAX_NUM_NTORS_PER_TAP);
207 /** Choose which onion queue we'll pull from next. If one is empty choose
208 * the other; if they both have elements, load balance across them but
209 * favoring NTOR. */
210 static uint16_t
211 decide_next_handshake_type(void)
213 /* The number of times we've chosen ntor lately when both were available. */
214 static int recently_chosen_ntors = 0;
216 if (!ol_entries[ONION_HANDSHAKE_TYPE_NTOR])
217 return ONION_HANDSHAKE_TYPE_TAP; /* no ntors? try tap */
219 if (!ol_entries[ONION_HANDSHAKE_TYPE_TAP]) {
221 /* Nick wants us to prioritize new tap requests when there aren't
222 * any in the queue and we've processed k ntor cells since the last
223 * tap cell. This strategy is maybe a good idea, since it starves tap
224 * less in the case where tap is rare, or maybe a poor idea, since it
225 * makes the new tap cell unfairly jump in front of ntor cells that
226 * got here first. In any case this edge case will only become relevant
227 * once tap is rare. We should reevaluate whether we like this decision
228 * once tap gets more rare. */
229 if (ol_entries[ONION_HANDSHAKE_TYPE_NTOR] &&
230 recently_chosen_ntors <= num_ntors_per_tap())
231 ++recently_chosen_ntors;
233 return ONION_HANDSHAKE_TYPE_NTOR; /* no taps? try ntor */
236 /* They both have something queued. Pick ntor if we haven't done that
237 * too much lately. */
238 if (++recently_chosen_ntors <= num_ntors_per_tap()) {
239 return ONION_HANDSHAKE_TYPE_NTOR;
242 /* Else, it's time to let tap have its turn. */
243 recently_chosen_ntors = 0;
244 return ONION_HANDSHAKE_TYPE_TAP;
247 /** Remove the highest priority item from ol_list[] and return it, or
248 * return NULL if the lists are empty.
250 or_circuit_t *
251 onion_next_task(create_cell_t **onionskin_out)
253 or_circuit_t *circ;
254 uint16_t handshake_to_choose = decide_next_handshake_type();
255 onion_queue_t *head = TOR_TAILQ_FIRST(&ol_list[handshake_to_choose]);
257 if (!head)
258 return NULL; /* no onions pending, we're done */
260 tor_assert(head->circ);
261 tor_assert(head->handshake_type <= MAX_ONION_HANDSHAKE_TYPE);
262 // tor_assert(head->circ->p_chan); /* make sure it's still valid */
263 /* XXX I only commented out the above line to make the unit tests
264 * more manageable. That's probably not good long-term. -RD */
265 circ = head->circ;
266 if (head->onionskin)
267 --ol_entries[head->handshake_type];
268 log_info(LD_OR, "Processing create (%s). Queues now ntor=%d and tap=%d.",
269 head->handshake_type == ONION_HANDSHAKE_TYPE_NTOR ? "ntor" : "tap",
270 ol_entries[ONION_HANDSHAKE_TYPE_NTOR],
271 ol_entries[ONION_HANDSHAKE_TYPE_TAP]);
273 *onionskin_out = head->onionskin;
274 head->onionskin = NULL; /* prevent free. */
275 circ->onionqueue_entry = NULL;
276 onion_queue_entry_remove(head);
277 return circ;
280 /** Return the number of <b>handshake_type</b>-style create requests pending.
283 onion_num_pending(uint16_t handshake_type)
285 return ol_entries[handshake_type];
288 /** Go through ol_list, find the onion_queue_t element which points to
289 * circ, remove and free that element. Leave circ itself alone.
291 void
292 onion_pending_remove(or_circuit_t *circ)
294 onion_queue_t *victim;
296 if (!circ)
297 return;
299 victim = circ->onionqueue_entry;
300 if (victim)
301 onion_queue_entry_remove(victim);
304 /** Remove a queue entry <b>victim</b> from the queue, unlinking it from
305 * its circuit and freeing it and any structures it owns.*/
306 static void
307 onion_queue_entry_remove(onion_queue_t *victim)
309 if (victim->handshake_type > MAX_ONION_HANDSHAKE_TYPE) {
310 log_warn(LD_BUG, "Handshake %d out of range! Dropping.",
311 victim->handshake_type);
312 /* XXX leaks */
313 return;
316 TOR_TAILQ_REMOVE(&ol_list[victim->handshake_type], victim, next);
318 if (victim->circ)
319 victim->circ->onionqueue_entry = NULL;
321 if (victim->onionskin)
322 --ol_entries[victim->handshake_type];
324 tor_free(victim->onionskin);
325 tor_free(victim);
328 /** Remove all circuits from the pending list. Called from tor_free_all. */
329 void
330 clear_pending_onions(void)
332 onion_queue_t *victim, *next;
333 int i;
334 for (i=0; i<=MAX_ONION_HANDSHAKE_TYPE; i++) {
335 for (victim = TOR_TAILQ_FIRST(&ol_list[i]); victim; victim = next) {
336 next = TOR_TAILQ_NEXT(victim,next);
337 onion_queue_entry_remove(victim);
339 tor_assert(TOR_TAILQ_EMPTY(&ol_list[i]));
341 memset(ol_entries, 0, sizeof(ol_entries));
344 /* ============================================================ */
346 /** Fill in a server_onion_keys_t object at <b>keys</b> with all of the keys
347 * and other info we might need to do onion handshakes. (We make a copy of
348 * our keys for each cpuworker to avoid race conditions with the main thread,
349 * and to avoid locking) */
350 void
351 setup_server_onion_keys(server_onion_keys_t *keys)
353 memset(keys, 0, sizeof(server_onion_keys_t));
354 memcpy(keys->my_identity, router_get_my_id_digest(), DIGEST_LEN);
355 dup_onion_keys(&keys->onion_key, &keys->last_onion_key);
356 #ifdef CURVE25519_ENABLED
357 keys->curve25519_key_map = construct_ntor_key_map();
358 keys->junk_keypair = tor_malloc_zero(sizeof(curve25519_keypair_t));
359 curve25519_keypair_generate(keys->junk_keypair, 0);
360 #endif
363 /** Release all storage held in <b>keys</b>, but do not free <b>keys</b>
364 * itself (as it's likely to be stack-allocated.) */
365 void
366 release_server_onion_keys(server_onion_keys_t *keys)
368 if (! keys)
369 return;
371 crypto_pk_free(keys->onion_key);
372 crypto_pk_free(keys->last_onion_key);
373 #ifdef CURVE25519_ENABLED
374 ntor_key_map_free(keys->curve25519_key_map);
375 tor_free(keys->junk_keypair);
376 #endif
377 memset(keys, 0, sizeof(server_onion_keys_t));
380 /** Release whatever storage is held in <b>state</b>, depending on its
381 * type, and clear its pointer. */
382 void
383 onion_handshake_state_release(onion_handshake_state_t *state)
385 switch (state->tag) {
386 case ONION_HANDSHAKE_TYPE_TAP:
387 crypto_dh_free(state->u.tap);
388 state->u.tap = NULL;
389 break;
390 case ONION_HANDSHAKE_TYPE_FAST:
391 fast_handshake_state_free(state->u.fast);
392 state->u.fast = NULL;
393 break;
394 #ifdef CURVE25519_ENABLED
395 case ONION_HANDSHAKE_TYPE_NTOR:
396 ntor_handshake_state_free(state->u.ntor);
397 state->u.ntor = NULL;
398 break;
399 #endif
400 default:
401 log_warn(LD_BUG, "called with unknown handshake state type %d",
402 (int)state->tag);
403 tor_fragile_assert();
407 /** Perform the first step of a circuit-creation handshake of type <b>type</b>
408 * (one of ONION_HANDSHAKE_TYPE_*): generate the initial "onion skin" in
409 * <b>onion_skin_out</b>, and store any state information in <b>state_out</b>.
410 * Return -1 on failure, and the length of the onionskin on acceptance.
413 onion_skin_create(int type,
414 const extend_info_t *node,
415 onion_handshake_state_t *state_out,
416 uint8_t *onion_skin_out)
418 int r = -1;
420 switch (type) {
421 case ONION_HANDSHAKE_TYPE_TAP:
422 if (!node->onion_key)
423 return -1;
425 if (onion_skin_TAP_create(node->onion_key,
426 &state_out->u.tap,
427 (char*)onion_skin_out) < 0)
428 return -1;
430 r = TAP_ONIONSKIN_CHALLENGE_LEN;
431 break;
432 case ONION_HANDSHAKE_TYPE_FAST:
433 if (fast_onionskin_create(&state_out->u.fast, onion_skin_out) < 0)
434 return -1;
436 r = CREATE_FAST_LEN;
437 break;
438 case ONION_HANDSHAKE_TYPE_NTOR:
439 #ifdef CURVE25519_ENABLED
440 if (tor_mem_is_zero((const char*)node->curve25519_onion_key.public_key,
441 CURVE25519_PUBKEY_LEN))
442 return -1;
443 if (onion_skin_ntor_create((const uint8_t*)node->identity_digest,
444 &node->curve25519_onion_key,
445 &state_out->u.ntor,
446 onion_skin_out) < 0)
447 return -1;
449 r = NTOR_ONIONSKIN_LEN;
450 #else
451 return -1;
452 #endif
453 break;
454 default:
455 log_warn(LD_BUG, "called with unknown handshake state type %d", type);
456 tor_fragile_assert();
457 r = -1;
460 if (r > 0)
461 state_out->tag = (uint16_t) type;
463 return r;
466 /** Perform the second (server-side) step of a circuit-creation handshake of
467 * type <b>type</b>, responding to the client request in <b>onion_skin</b>
468 * using the keys in <b>keys</b>. On success, write our response into
469 * <b>reply_out</b>, generate <b>keys_out_len</b> bytes worth of key material
470 * in <b>keys_out_len</b>, a hidden service nonce to <b>rend_nonce_out</b>,
471 * and return the length of the reply. On failure, return -1.
474 onion_skin_server_handshake(int type,
475 const uint8_t *onion_skin, size_t onionskin_len,
476 const server_onion_keys_t *keys,
477 uint8_t *reply_out,
478 uint8_t *keys_out, size_t keys_out_len,
479 uint8_t *rend_nonce_out)
481 int r = -1;
483 switch (type) {
484 case ONION_HANDSHAKE_TYPE_TAP:
485 if (onionskin_len != TAP_ONIONSKIN_CHALLENGE_LEN)
486 return -1;
487 if (onion_skin_TAP_server_handshake((const char*)onion_skin,
488 keys->onion_key, keys->last_onion_key,
489 (char*)reply_out,
490 (char*)keys_out, keys_out_len)<0)
491 return -1;
492 r = TAP_ONIONSKIN_REPLY_LEN;
493 memcpy(rend_nonce_out, reply_out+DH_KEY_LEN, DIGEST_LEN);
494 break;
495 case ONION_HANDSHAKE_TYPE_FAST:
496 if (onionskin_len != CREATE_FAST_LEN)
497 return -1;
498 if (fast_server_handshake(onion_skin, reply_out, keys_out, keys_out_len)<0)
499 return -1;
500 r = CREATED_FAST_LEN;
501 memcpy(rend_nonce_out, reply_out+DIGEST_LEN, DIGEST_LEN);
502 break;
503 case ONION_HANDSHAKE_TYPE_NTOR:
504 #ifdef CURVE25519_ENABLED
505 if (onionskin_len < NTOR_ONIONSKIN_LEN)
506 return -1;
508 size_t keys_tmp_len = keys_out_len + DIGEST_LEN;
509 uint8_t *keys_tmp = tor_malloc(keys_out_len + DIGEST_LEN);
511 if (onion_skin_ntor_server_handshake(
512 onion_skin, keys->curve25519_key_map,
513 keys->junk_keypair,
514 keys->my_identity,
515 reply_out, keys_tmp, keys_tmp_len)<0) {
516 tor_free(keys_tmp);
517 return -1;
519 memcpy(keys_out, keys_tmp, keys_out_len);
520 memcpy(rend_nonce_out, keys_tmp+keys_out_len, DIGEST_LEN);
521 memwipe(keys_tmp, 0, keys_tmp_len);
522 tor_free(keys_tmp);
523 r = NTOR_REPLY_LEN;
525 #else
526 return -1;
527 #endif
528 break;
529 default:
530 log_warn(LD_BUG, "called with unknown handshake state type %d", type);
531 tor_fragile_assert();
532 return -1;
535 return r;
538 /** Perform the final (client-side) step of a circuit-creation handshake of
539 * type <b>type</b>, using our state in <b>handshake_state</b> and the
540 * server's response in <b>reply</b>. On success, generate <b>keys_out_len</b>
541 * bytes worth of key material in <b>keys_out_len</b>, set
542 * <b>rend_authenticator_out</b> to the "KH" field that can be used to
543 * establish introduction points at this hop, and return 0. On failure,
544 * return -1. */
546 onion_skin_client_handshake(int type,
547 const onion_handshake_state_t *handshake_state,
548 const uint8_t *reply, size_t reply_len,
549 uint8_t *keys_out, size_t keys_out_len,
550 uint8_t *rend_authenticator_out)
552 if (handshake_state->tag != type)
553 return -1;
555 switch (type) {
556 case ONION_HANDSHAKE_TYPE_TAP:
557 if (reply_len != TAP_ONIONSKIN_REPLY_LEN) {
558 log_warn(LD_CIRC, "TAP reply was not of the correct length.");
559 return -1;
561 if (onion_skin_TAP_client_handshake(handshake_state->u.tap,
562 (const char*)reply,
563 (char *)keys_out, keys_out_len) < 0)
564 return -1;
566 memcpy(rend_authenticator_out, reply+DH_KEY_LEN, DIGEST_LEN);
568 return 0;
569 case ONION_HANDSHAKE_TYPE_FAST:
570 if (reply_len != CREATED_FAST_LEN) {
571 log_warn(LD_CIRC, "CREATED_FAST reply was not of the correct length.");
572 return -1;
574 if (fast_client_handshake(handshake_state->u.fast, reply,
575 keys_out, keys_out_len) < 0)
576 return -1;
578 memcpy(rend_authenticator_out, reply+DIGEST_LEN, DIGEST_LEN);
579 return 0;
580 #ifdef CURVE25519_ENABLED
581 case ONION_HANDSHAKE_TYPE_NTOR:
582 if (reply_len < NTOR_REPLY_LEN) {
583 log_warn(LD_CIRC, "ntor reply was not of the correct length.");
584 return -1;
587 size_t keys_tmp_len = keys_out_len + DIGEST_LEN;
588 uint8_t *keys_tmp = tor_malloc(keys_tmp_len);
589 if (onion_skin_ntor_client_handshake(handshake_state->u.ntor,
590 reply,
591 keys_tmp, keys_tmp_len) < 0) {
592 tor_free(keys_tmp);
593 return -1;
595 memcpy(keys_out, keys_tmp, keys_out_len);
596 memcpy(rend_authenticator_out, keys_tmp + keys_out_len, DIGEST_LEN);
597 memwipe(keys_tmp, 0, keys_tmp_len);
598 tor_free(keys_tmp);
600 return 0;
601 #endif
602 default:
603 log_warn(LD_BUG, "called with unknown handshake state type %d", type);
604 tor_fragile_assert();
605 return -1;
609 /** Helper: return 0 if <b>cell</b> appears valid, -1 otherwise. If
610 * <b>unknown_ok</b> is true, allow cells with handshake types we don't
611 * recognize. */
612 static int
613 check_create_cell(const create_cell_t *cell, int unknown_ok)
615 switch (cell->cell_type) {
616 case CELL_CREATE:
617 if (cell->handshake_type != ONION_HANDSHAKE_TYPE_TAP &&
618 cell->handshake_type != ONION_HANDSHAKE_TYPE_NTOR)
619 return -1;
620 break;
621 case CELL_CREATE_FAST:
622 if (cell->handshake_type != ONION_HANDSHAKE_TYPE_FAST)
623 return -1;
624 break;
625 case CELL_CREATE2:
626 break;
627 default:
628 return -1;
631 switch (cell->handshake_type) {
632 case ONION_HANDSHAKE_TYPE_TAP:
633 if (cell->handshake_len != TAP_ONIONSKIN_CHALLENGE_LEN)
634 return -1;
635 break;
636 case ONION_HANDSHAKE_TYPE_FAST:
637 if (cell->handshake_len != CREATE_FAST_LEN)
638 return -1;
639 break;
640 #ifdef CURVE25519_ENABLED
641 case ONION_HANDSHAKE_TYPE_NTOR:
642 if (cell->handshake_len != NTOR_ONIONSKIN_LEN)
643 return -1;
644 break;
645 #endif
646 default:
647 if (! unknown_ok)
648 return -1;
651 return 0;
654 /** Write the various parameters into the create cell. Separate from
655 * create_cell_parse() to make unit testing easier.
657 void
658 create_cell_init(create_cell_t *cell_out, uint8_t cell_type,
659 uint16_t handshake_type, uint16_t handshake_len,
660 const uint8_t *onionskin)
662 memset(cell_out, 0, sizeof(*cell_out));
664 cell_out->cell_type = cell_type;
665 cell_out->handshake_type = handshake_type;
666 cell_out->handshake_len = handshake_len;
667 memcpy(cell_out->onionskin, onionskin, handshake_len);
670 /** Helper: parse the CREATE2 payload at <b>p</b>, which could be up to
671 * <b>p_len</b> bytes long, and use it to fill the fields of
672 * <b>cell_out</b>. Return 0 on success and -1 on failure.
674 * Note that part of the body of an EXTEND2 cell is a CREATE2 payload, so
675 * this function is also used for parsing those.
677 static int
678 parse_create2_payload(create_cell_t *cell_out, const uint8_t *p, size_t p_len)
680 uint16_t handshake_type, handshake_len;
682 if (p_len < 4)
683 return -1;
685 handshake_type = ntohs(get_uint16(p));
686 handshake_len = ntohs(get_uint16(p+2));
688 if (handshake_len > CELL_PAYLOAD_SIZE - 4 || handshake_len > p_len - 4)
689 return -1;
690 if (handshake_type == ONION_HANDSHAKE_TYPE_FAST)
691 return -1;
693 create_cell_init(cell_out, CELL_CREATE2, handshake_type, handshake_len,
694 p+4);
695 return 0;
698 /** Magic string which, in a CREATE or EXTEND cell, indicates that a seeming
699 * TAP payload is really an ntor payload. We'd do away with this if every
700 * relay supported EXTEND2, but we want to be able to extend from A to B with
701 * ntor even when A doesn't understand EXTEND2 and so can't generate a
702 * CREATE2 cell.
704 #define NTOR_CREATE_MAGIC "ntorNTORntorNTOR"
706 /** Parse a CREATE, CREATE_FAST, or CREATE2 cell from <b>cell_in</b> into
707 * <b>cell_out</b>. Return 0 on success, -1 on failure. (We reject some
708 * syntactically valid CREATE2 cells that we can't generate or react to.) */
710 create_cell_parse(create_cell_t *cell_out, const cell_t *cell_in)
712 switch (cell_in->command) {
713 case CELL_CREATE:
714 if (tor_memeq(cell_in->payload, NTOR_CREATE_MAGIC, 16)) {
715 create_cell_init(cell_out, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
716 NTOR_ONIONSKIN_LEN, cell_in->payload+16);
717 } else {
718 create_cell_init(cell_out, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
719 TAP_ONIONSKIN_CHALLENGE_LEN, cell_in->payload);
721 break;
722 case CELL_CREATE_FAST:
723 create_cell_init(cell_out, CELL_CREATE_FAST, ONION_HANDSHAKE_TYPE_FAST,
724 CREATE_FAST_LEN, cell_in->payload);
725 break;
726 case CELL_CREATE2:
727 if (parse_create2_payload(cell_out, cell_in->payload,
728 CELL_PAYLOAD_SIZE) < 0)
729 return -1;
730 break;
731 default:
732 return -1;
735 return check_create_cell(cell_out, 0);
738 /** Helper: return 0 if <b>cell</b> appears valid, -1 otherwise. */
739 static int
740 check_created_cell(const created_cell_t *cell)
742 switch (cell->cell_type) {
743 case CELL_CREATED:
744 if (cell->handshake_len != TAP_ONIONSKIN_REPLY_LEN &&
745 cell->handshake_len != NTOR_REPLY_LEN)
746 return -1;
747 break;
748 case CELL_CREATED_FAST:
749 if (cell->handshake_len != CREATED_FAST_LEN)
750 return -1;
751 break;
752 case CELL_CREATED2:
753 if (cell->handshake_len > RELAY_PAYLOAD_SIZE-2)
754 return -1;
755 break;
758 return 0;
761 /** Parse a CREATED, CREATED_FAST, or CREATED2 cell from <b>cell_in</b> into
762 * <b>cell_out</b>. Return 0 on success, -1 on failure. */
764 created_cell_parse(created_cell_t *cell_out, const cell_t *cell_in)
766 memset(cell_out, 0, sizeof(*cell_out));
768 switch (cell_in->command) {
769 case CELL_CREATED:
770 cell_out->cell_type = CELL_CREATED;
771 cell_out->handshake_len = TAP_ONIONSKIN_REPLY_LEN;
772 memcpy(cell_out->reply, cell_in->payload, TAP_ONIONSKIN_REPLY_LEN);
773 break;
774 case CELL_CREATED_FAST:
775 cell_out->cell_type = CELL_CREATED_FAST;
776 cell_out->handshake_len = CREATED_FAST_LEN;
777 memcpy(cell_out->reply, cell_in->payload, CREATED_FAST_LEN);
778 break;
779 case CELL_CREATED2:
781 const uint8_t *p = cell_in->payload;
782 cell_out->cell_type = CELL_CREATED2;
783 cell_out->handshake_len = ntohs(get_uint16(p));
784 if (cell_out->handshake_len > CELL_PAYLOAD_SIZE - 2)
785 return -1;
786 memcpy(cell_out->reply, p+2, cell_out->handshake_len);
787 break;
791 return check_created_cell(cell_out);
794 /** Helper: return 0 if <b>cell</b> appears valid, -1 otherwise. */
795 static int
796 check_extend_cell(const extend_cell_t *cell)
798 if (tor_digest_is_zero((const char*)cell->node_id))
799 return -1;
800 /* We don't currently allow EXTEND2 cells without an IPv4 address */
801 if (tor_addr_family(&cell->orport_ipv4.addr) == AF_UNSPEC)
802 return -1;
803 if (cell->create_cell.cell_type == CELL_CREATE) {
804 if (cell->cell_type != RELAY_COMMAND_EXTEND)
805 return -1;
806 } else if (cell->create_cell.cell_type == CELL_CREATE2) {
807 if (cell->cell_type != RELAY_COMMAND_EXTEND2 &&
808 cell->cell_type != RELAY_COMMAND_EXTEND)
809 return -1;
810 } else {
811 /* In particular, no CREATE_FAST cells are allowed */
812 return -1;
814 if (cell->create_cell.handshake_type == ONION_HANDSHAKE_TYPE_FAST)
815 return -1;
817 return check_create_cell(&cell->create_cell, 1);
820 /** Protocol constants for specifier types in EXTEND2
821 * @{
823 #define SPECTYPE_IPV4 0
824 #define SPECTYPE_IPV6 1
825 #define SPECTYPE_LEGACY_ID 2
826 /** @} */
828 /** Parse an EXTEND or EXTEND2 cell (according to <b>command</b>) from the
829 * <b>payload_length</b> bytes of <b>payload</b> into <b>cell_out</b>. Return
830 * 0 on success, -1 on failure. */
832 extend_cell_parse(extend_cell_t *cell_out, const uint8_t command,
833 const uint8_t *payload, size_t payload_length)
835 const uint8_t *eop;
837 memset(cell_out, 0, sizeof(*cell_out));
838 if (payload_length > RELAY_PAYLOAD_SIZE)
839 return -1;
840 eop = payload + payload_length;
842 switch (command) {
843 case RELAY_COMMAND_EXTEND:
845 if (payload_length != 6 + TAP_ONIONSKIN_CHALLENGE_LEN + DIGEST_LEN)
846 return -1;
848 cell_out->cell_type = RELAY_COMMAND_EXTEND;
849 tor_addr_from_ipv4n(&cell_out->orport_ipv4.addr, get_uint32(payload));
850 cell_out->orport_ipv4.port = ntohs(get_uint16(payload+4));
851 tor_addr_make_unspec(&cell_out->orport_ipv6.addr);
852 if (tor_memeq(payload + 6, NTOR_CREATE_MAGIC, 16)) {
853 cell_out->create_cell.cell_type = CELL_CREATE2;
854 cell_out->create_cell.handshake_type = ONION_HANDSHAKE_TYPE_NTOR;
855 cell_out->create_cell.handshake_len = NTOR_ONIONSKIN_LEN;
856 memcpy(cell_out->create_cell.onionskin, payload + 22,
857 NTOR_ONIONSKIN_LEN);
858 } else {
859 cell_out->create_cell.cell_type = CELL_CREATE;
860 cell_out->create_cell.handshake_type = ONION_HANDSHAKE_TYPE_TAP;
861 cell_out->create_cell.handshake_len = TAP_ONIONSKIN_CHALLENGE_LEN;
862 memcpy(cell_out->create_cell.onionskin, payload + 6,
863 TAP_ONIONSKIN_CHALLENGE_LEN);
865 memcpy(cell_out->node_id, payload + 6 + TAP_ONIONSKIN_CHALLENGE_LEN,
866 DIGEST_LEN);
867 break;
869 case RELAY_COMMAND_EXTEND2:
871 uint8_t n_specs, spectype, speclen;
872 int i;
873 int found_ipv4 = 0, found_ipv6 = 0, found_id = 0;
874 tor_addr_make_unspec(&cell_out->orport_ipv4.addr);
875 tor_addr_make_unspec(&cell_out->orport_ipv6.addr);
877 if (payload_length == 0)
878 return -1;
880 cell_out->cell_type = RELAY_COMMAND_EXTEND2;
881 n_specs = *payload++;
882 /* Parse the specifiers. We'll only take the first IPv4 and first IPv6
883 * address, and the node ID, and ignore everything else */
884 for (i = 0; i < n_specs; ++i) {
885 if (eop - payload < 2)
886 return -1;
887 spectype = payload[0];
888 speclen = payload[1];
889 payload += 2;
890 if (eop - payload < speclen)
891 return -1;
892 switch (spectype) {
893 case SPECTYPE_IPV4:
894 if (speclen != 6)
895 return -1;
896 if (!found_ipv4) {
897 tor_addr_from_ipv4n(&cell_out->orport_ipv4.addr,
898 get_uint32(payload));
899 cell_out->orport_ipv4.port = ntohs(get_uint16(payload+4));
900 found_ipv4 = 1;
902 break;
903 case SPECTYPE_IPV6:
904 if (speclen != 18)
905 return -1;
906 if (!found_ipv6) {
907 tor_addr_from_ipv6_bytes(&cell_out->orport_ipv6.addr,
908 (const char*)payload);
909 cell_out->orport_ipv6.port = ntohs(get_uint16(payload+16));
910 found_ipv6 = 1;
912 break;
913 case SPECTYPE_LEGACY_ID:
914 if (speclen != 20)
915 return -1;
916 if (found_id)
917 return -1;
918 memcpy(cell_out->node_id, payload, 20);
919 found_id = 1;
920 break;
922 payload += speclen;
924 if (!found_id || !found_ipv4)
925 return -1;
926 if (parse_create2_payload(&cell_out->create_cell,payload,eop-payload)<0)
927 return -1;
928 break;
930 default:
931 return -1;
934 return check_extend_cell(cell_out);
937 /** Helper: return 0 if <b>cell</b> appears valid, -1 otherwise. */
938 static int
939 check_extended_cell(const extended_cell_t *cell)
941 if (cell->created_cell.cell_type == CELL_CREATED) {
942 if (cell->cell_type != RELAY_COMMAND_EXTENDED)
943 return -1;
944 } else if (cell->created_cell.cell_type == CELL_CREATED2) {
945 if (cell->cell_type != RELAY_COMMAND_EXTENDED2)
946 return -1;
947 } else {
948 return -1;
951 return check_created_cell(&cell->created_cell);
954 /** Parse an EXTENDED or EXTENDED2 cell (according to <b>command</b>) from the
955 * <b>payload_length</b> bytes of <b>payload</b> into <b>cell_out</b>. Return
956 * 0 on success, -1 on failure. */
958 extended_cell_parse(extended_cell_t *cell_out,
959 const uint8_t command, const uint8_t *payload,
960 size_t payload_len)
962 memset(cell_out, 0, sizeof(*cell_out));
963 if (payload_len > RELAY_PAYLOAD_SIZE)
964 return -1;
966 switch (command) {
967 case RELAY_COMMAND_EXTENDED:
968 if (payload_len != TAP_ONIONSKIN_REPLY_LEN)
969 return -1;
970 cell_out->cell_type = RELAY_COMMAND_EXTENDED;
971 cell_out->created_cell.cell_type = CELL_CREATED;
972 cell_out->created_cell.handshake_len = TAP_ONIONSKIN_REPLY_LEN;
973 memcpy(cell_out->created_cell.reply, payload, TAP_ONIONSKIN_REPLY_LEN);
974 break;
975 case RELAY_COMMAND_EXTENDED2:
977 cell_out->cell_type = RELAY_COMMAND_EXTENDED2;
978 cell_out->created_cell.cell_type = CELL_CREATED2;
979 cell_out->created_cell.handshake_len = ntohs(get_uint16(payload));
980 if (cell_out->created_cell.handshake_len > RELAY_PAYLOAD_SIZE - 2 ||
981 cell_out->created_cell.handshake_len > payload_len - 2)
982 return -1;
983 memcpy(cell_out->created_cell.reply, payload+2,
984 cell_out->created_cell.handshake_len);
986 break;
987 default:
988 return -1;
991 return check_extended_cell(cell_out);
994 /** Fill <b>cell_out</b> with a correctly formatted version of the
995 * CREATE{,_FAST,2} cell in <b>cell_in</b>. Return 0 on success, -1 on
996 * failure. This is a cell we didn't originate if <b>relayed</b> is true. */
997 static int
998 create_cell_format_impl(cell_t *cell_out, const create_cell_t *cell_in,
999 int relayed)
1001 uint8_t *p;
1002 size_t space;
1003 if (check_create_cell(cell_in, relayed) < 0)
1004 return -1;
1006 memset(cell_out->payload, 0, sizeof(cell_out->payload));
1007 cell_out->command = cell_in->cell_type;
1009 p = cell_out->payload;
1010 space = sizeof(cell_out->payload);
1012 switch (cell_in->cell_type) {
1013 case CELL_CREATE:
1014 if (cell_in->handshake_type == ONION_HANDSHAKE_TYPE_NTOR) {
1015 memcpy(p, NTOR_CREATE_MAGIC, 16);
1016 p += 16;
1017 space -= 16;
1019 /* Fall through */
1020 case CELL_CREATE_FAST:
1021 tor_assert(cell_in->handshake_len <= space);
1022 memcpy(p, cell_in->onionskin, cell_in->handshake_len);
1023 break;
1024 case CELL_CREATE2:
1025 tor_assert(cell_in->handshake_len <= sizeof(cell_out->payload)-4);
1026 set_uint16(cell_out->payload, htons(cell_in->handshake_type));
1027 set_uint16(cell_out->payload+2, htons(cell_in->handshake_len));
1028 memcpy(cell_out->payload + 4, cell_in->onionskin, cell_in->handshake_len);
1029 break;
1030 default:
1031 return -1;
1034 return 0;
1038 create_cell_format(cell_t *cell_out, const create_cell_t *cell_in)
1040 return create_cell_format_impl(cell_out, cell_in, 0);
1044 create_cell_format_relayed(cell_t *cell_out, const create_cell_t *cell_in)
1046 return create_cell_format_impl(cell_out, cell_in, 1);
1049 /** Fill <b>cell_out</b> with a correctly formatted version of the
1050 * CREATED{,_FAST,2} cell in <b>cell_in</b>. Return 0 on success, -1 on
1051 * failure. */
1053 created_cell_format(cell_t *cell_out, const created_cell_t *cell_in)
1055 if (check_created_cell(cell_in) < 0)
1056 return -1;
1058 memset(cell_out->payload, 0, sizeof(cell_out->payload));
1059 cell_out->command = cell_in->cell_type;
1061 switch (cell_in->cell_type) {
1062 case CELL_CREATED:
1063 case CELL_CREATED_FAST:
1064 tor_assert(cell_in->handshake_len <= sizeof(cell_out->payload));
1065 memcpy(cell_out->payload, cell_in->reply, cell_in->handshake_len);
1066 break;
1067 case CELL_CREATED2:
1068 tor_assert(cell_in->handshake_len <= sizeof(cell_out->payload)-2);
1069 set_uint16(cell_out->payload, htons(cell_in->handshake_len));
1070 memcpy(cell_out->payload + 2, cell_in->reply, cell_in->handshake_len);
1071 break;
1072 default:
1073 return -1;
1075 return 0;
1078 /** Format the EXTEND{,2} cell in <b>cell_in</b>, storing its relay payload in
1079 * <b>payload_out</b>, the number of bytes used in *<b>len_out</b>, and the
1080 * relay command in *<b>command_out</b>. The <b>payload_out</b> must have
1081 * RELAY_PAYLOAD_SIZE bytes available. Return 0 on success, -1 on failure. */
1083 extend_cell_format(uint8_t *command_out, uint16_t *len_out,
1084 uint8_t *payload_out, const extend_cell_t *cell_in)
1086 uint8_t *p, *eop;
1087 if (check_extend_cell(cell_in) < 0)
1088 return -1;
1090 p = payload_out;
1091 eop = payload_out + RELAY_PAYLOAD_SIZE;
1093 memset(p, 0, RELAY_PAYLOAD_SIZE);
1095 switch (cell_in->cell_type) {
1096 case RELAY_COMMAND_EXTEND:
1098 *command_out = RELAY_COMMAND_EXTEND;
1099 *len_out = 6 + TAP_ONIONSKIN_CHALLENGE_LEN + DIGEST_LEN;
1100 set_uint32(p, tor_addr_to_ipv4n(&cell_in->orport_ipv4.addr));
1101 set_uint16(p+4, ntohs(cell_in->orport_ipv4.port));
1102 if (cell_in->create_cell.handshake_type == ONION_HANDSHAKE_TYPE_NTOR) {
1103 memcpy(p+6, NTOR_CREATE_MAGIC, 16);
1104 memcpy(p+22, cell_in->create_cell.onionskin, NTOR_ONIONSKIN_LEN);
1105 } else {
1106 memcpy(p+6, cell_in->create_cell.onionskin,
1107 TAP_ONIONSKIN_CHALLENGE_LEN);
1109 memcpy(p+6+TAP_ONIONSKIN_CHALLENGE_LEN, cell_in->node_id, DIGEST_LEN);
1111 break;
1112 case RELAY_COMMAND_EXTEND2:
1114 uint8_t n = 2;
1115 *command_out = RELAY_COMMAND_EXTEND2;
1117 *p++ = n; /* 2 identifiers */
1118 *p++ = SPECTYPE_IPV4; /* First is IPV4. */
1119 *p++ = 6; /* It's 6 bytes long. */
1120 set_uint32(p, tor_addr_to_ipv4n(&cell_in->orport_ipv4.addr));
1121 set_uint16(p+4, htons(cell_in->orport_ipv4.port));
1122 p += 6;
1123 *p++ = SPECTYPE_LEGACY_ID; /* Next is an identity digest. */
1124 *p++ = 20; /* It's 20 bytes long */
1125 memcpy(p, cell_in->node_id, DIGEST_LEN);
1126 p += 20;
1128 /* Now we can send the handshake */
1129 set_uint16(p, htons(cell_in->create_cell.handshake_type));
1130 set_uint16(p+2, htons(cell_in->create_cell.handshake_len));
1131 p += 4;
1133 if (cell_in->create_cell.handshake_len > eop - p)
1134 return -1;
1136 memcpy(p, cell_in->create_cell.onionskin,
1137 cell_in->create_cell.handshake_len);
1139 p += cell_in->create_cell.handshake_len;
1140 *len_out = p - payload_out;
1142 break;
1143 default:
1144 return -1;
1147 return 0;
1150 /** Format the EXTENDED{,2} cell in <b>cell_in</b>, storing its relay payload
1151 * in <b>payload_out</b>, the number of bytes used in *<b>len_out</b>, and the
1152 * relay command in *<b>command_out</b>. The <b>payload_out</b> must have
1153 * RELAY_PAYLOAD_SIZE bytes available. Return 0 on success, -1 on failure. */
1155 extended_cell_format(uint8_t *command_out, uint16_t *len_out,
1156 uint8_t *payload_out, const extended_cell_t *cell_in)
1158 uint8_t *p;
1159 if (check_extended_cell(cell_in) < 0)
1160 return -1;
1162 p = payload_out;
1163 memset(p, 0, RELAY_PAYLOAD_SIZE);
1165 switch (cell_in->cell_type) {
1166 case RELAY_COMMAND_EXTENDED:
1168 *command_out = RELAY_COMMAND_EXTENDED;
1169 *len_out = TAP_ONIONSKIN_REPLY_LEN;
1170 memcpy(payload_out, cell_in->created_cell.reply,
1171 TAP_ONIONSKIN_REPLY_LEN);
1173 break;
1174 case RELAY_COMMAND_EXTENDED2:
1176 *command_out = RELAY_COMMAND_EXTENDED2;
1177 *len_out = 2 + cell_in->created_cell.handshake_len;
1178 set_uint16(payload_out, htons(cell_in->created_cell.handshake_len));
1179 if (2+cell_in->created_cell.handshake_len > RELAY_PAYLOAD_SIZE)
1180 return -1;
1181 memcpy(payload_out+2, cell_in->created_cell.reply,
1182 cell_in->created_cell.handshake_len);
1184 break;
1185 default:
1186 return -1;
1189 return 0;