Merge flagday into main branch.
[tor.git] / src / or / onion.c
blob7ad736e9541a181f8b0d5722c2614caf485effe3
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "or.h"
7 /* prototypes for smartlist operations from routerlist.h
8 * they're here to prevent precedence issues with the .h files
9 */
10 void router_add_running_routers_to_smartlist(smartlist_t *sl);
11 void add_nickname_list_to_smartlist(smartlist_t *sl, char *list);
13 extern or_options_t options; /* command-line and config-file options */
15 static int count_acceptable_routers(smartlist_t *routers);
17 int decide_circ_id_type(char *local_nick, char *remote_nick) {
18 int result;
20 assert(remote_nick);
21 if(!local_nick)
22 return CIRC_ID_TYPE_LOWER;
23 result = strcmp(local_nick, remote_nick);
24 assert(result);
25 if(result < 0)
26 return CIRC_ID_TYPE_LOWER;
27 return CIRC_ID_TYPE_HIGHER;
30 struct onion_queue_t {
31 circuit_t *circ;
32 struct onion_queue_t *next;
35 /* global (within this file) variables used by the next few functions */
36 static struct onion_queue_t *ol_list=NULL;
37 static struct onion_queue_t *ol_tail=NULL;
38 static int ol_length=0;
40 int onion_pending_add(circuit_t *circ) {
41 struct onion_queue_t *tmp;
43 tmp = tor_malloc(sizeof(struct onion_queue_t));
44 tmp->circ = circ;
45 tmp->next = NULL;
47 if(!ol_tail) {
48 assert(!ol_list);
49 assert(!ol_length);
50 ol_list = tmp;
51 ol_tail = tmp;
52 ol_length++;
53 return 0;
56 assert(ol_list);
57 assert(!ol_tail->next);
59 if(ol_length >= options.MaxOnionsPending) {
60 log_fn(LOG_WARN,"Already have %d onions queued. Closing.", ol_length);
61 free(tmp);
62 return -1;
65 ol_length++;
66 ol_tail->next = tmp;
67 ol_tail = tmp;
68 return 0;
72 circuit_t *onion_next_task(void) {
73 circuit_t *circ;
75 if(!ol_list)
76 return NULL; /* no onions pending, we're done */
78 assert(ol_list->circ);
79 assert(ol_list->circ->p_conn); /* make sure it's still valid */
80 assert(ol_length > 0);
81 circ = ol_list->circ;
82 onion_pending_remove(ol_list->circ);
83 return circ;
86 /* go through ol_list, find the onion_queue_t element which points to
87 * circ, remove and free that element. leave circ itself alone.
89 void onion_pending_remove(circuit_t *circ) {
90 struct onion_queue_t *tmpo, *victim;
92 if(!ol_list)
93 return; /* nothing here. */
95 /* first check to see if it's the first entry */
96 tmpo = ol_list;
97 if(tmpo->circ == circ) {
98 /* it's the first one. remove it from the list. */
99 ol_list = tmpo->next;
100 if(!ol_list)
101 ol_tail = NULL;
102 ol_length--;
103 victim = tmpo;
104 } else { /* we need to hunt through the rest of the list */
105 for( ;tmpo->next && tmpo->next->circ != circ; tmpo=tmpo->next) ;
106 if(!tmpo->next) {
107 log_fn(LOG_DEBUG,"circ (p_circ_id %d) not in list, probably at cpuworker.",circ->p_circ_id);
108 return;
110 /* now we know tmpo->next->circ == circ */
111 victim = tmpo->next;
112 tmpo->next = victim->next;
113 if(ol_tail == victim)
114 ol_tail = tmpo;
115 ol_length--;
118 /* now victim points to the element that needs to be removed */
120 free(victim);
123 /* given a response payload and keys, initialize, then send a created cell back */
124 int onionskin_answer(circuit_t *circ, unsigned char *payload, unsigned char *keys) {
125 cell_t cell;
126 crypt_path_t *tmp_cpath;
128 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
130 memset(&cell, 0, sizeof(cell_t));
131 cell.command = CELL_CREATED;
132 cell.circ_id = circ->p_circ_id;
134 circ->state = CIRCUIT_STATE_OPEN;
136 log_fn(LOG_DEBUG,"Entering.");
138 memcpy(cell.payload, payload, ONIONSKIN_REPLY_LEN);
140 log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
141 (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
142 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
143 log_fn(LOG_WARN,"Circuit initialization failed");
144 tor_free(tmp_cpath);
145 return -1;
147 circ->n_digest = tmp_cpath->f_digest;
148 circ->n_crypto = tmp_cpath->f_crypto;
149 circ->p_digest = tmp_cpath->b_digest;
150 circ->p_crypto = tmp_cpath->b_crypto;
151 tor_free(tmp_cpath);
153 memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
155 connection_or_write_cell_to_buf(&cell, circ->p_conn);
156 log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
158 return 0;
161 extern int has_fetched_directory;
163 static int new_route_len(double cw, uint8_t purpose, smartlist_t *routers) {
164 int num_acceptable_routers;
165 int routelen;
167 assert((cw >= 0) && (cw < 1) && routers); /* valid parameters */
169 #ifdef TOR_PERF
170 routelen = 2;
171 #else
172 if(purpose == CIRCUIT_PURPOSE_C_GENERAL)
173 routelen = 3;
174 else if(purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
175 routelen = 4;
176 else if(purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
177 routelen = 3;
178 else if(purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
179 routelen = 3;
180 else if(purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
181 routelen = 4;
182 else {
183 log_fn(LOG_WARN,"Unhandled purpose %d", purpose);
184 return -1;
186 #endif
187 #if 0
188 for(routelen = 3; ; routelen++) { /* 3, increment until coinflip says we're done */
189 if (crypto_pseudo_rand_int(255) >= cw*255) /* don't extend */
190 break;
192 #endif
193 log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen,
194 smartlist_len(routers));
196 num_acceptable_routers = count_acceptable_routers(routers);
198 if(num_acceptable_routers < 2) {
199 log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
200 num_acceptable_routers);
201 return -1;
204 if(num_acceptable_routers < routelen) {
205 log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
206 routelen, num_acceptable_routers);
207 routelen = num_acceptable_routers;
210 return routelen;
213 static routerinfo_t *choose_good_exit_server_general(routerlist_t *dir)
215 int *n_supported;
216 int i, j;
217 int n_pending_connections = 0;
218 connection_t **carray;
219 int n_connections;
220 int best_support = -1;
221 int n_best_support=0;
222 smartlist_t *sl, *preferredexits, *excludedexits;
223 routerinfo_t *router;
225 get_connection_array(&carray, &n_connections);
227 /* Count how many connections are waiting for a circuit to be built.
228 * We use this for log messages now, but in the future we may depend on it.
230 for (i = 0; i < n_connections; ++i) {
231 if (carray[i]->type == CONN_TYPE_AP &&
232 carray[i]->state == AP_CONN_STATE_CIRCUIT_WAIT &&
233 !carray[i]->marked_for_close &&
234 !circuit_stream_is_being_handled(carray[i]))
235 ++n_pending_connections;
237 log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
238 n_pending_connections);
239 /* Now we count, for each of the routers in the directory, how many
240 * of the pending connections could possibly exit from that
241 * router (n_supported[i]). (We can't be sure about cases where we
242 * don't know the IP address of the pending connection.)
244 n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
245 for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
246 router = smartlist_get(dir->routers, i);
247 if(router_is_me(router)) {
248 n_supported[i] = -1;
249 log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
250 /* XXX there's probably a reverse predecessor attack here, but
251 * it's slow. should we take this out? -RD
253 continue;
255 if(!router->is_running) {
256 n_supported[i] = -1;
257 log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
258 router->nickname, i);
259 continue; /* skip routers that are known to be down */
261 if(router_exit_policy_rejects_all(router)) {
262 n_supported[i] = -1;
263 log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
264 router->nickname, i);
265 continue; /* skip routers that reject all */
267 n_supported[i] = 0;
268 for (j = 0; j < n_connections; ++j) { /* iterate over connections */
269 if (carray[j]->type != CONN_TYPE_AP ||
270 carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
271 carray[j]->marked_for_close ||
272 circuit_stream_is_being_handled(carray[j]))
273 continue; /* Skip everything but APs in CIRCUIT_WAIT */
274 switch (connection_ap_can_use_exit(carray[j], router))
276 case ADDR_POLICY_REJECTED:
277 log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
278 router->nickname, i);
279 break; /* would be rejected; try next connection */
280 case ADDR_POLICY_ACCEPTED:
281 case ADDR_POLICY_UNKNOWN:
282 ++n_supported[i];
283 log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
284 router->nickname, i, n_supported[i]);
286 } /* End looping over connections. */
287 if (n_supported[i] > best_support) {
288 /* If this router is better than previous ones, remember its index
289 * and goodness, and start counting how many routers are this good. */
290 best_support = n_supported[i]; n_best_support=1;
291 log_fn(LOG_DEBUG,"%s is new best supported option so far.",
292 router->nickname);
293 } else if (n_supported[i] == best_support) {
294 /* If this router is _as good_ as the best one, just increment the
295 * count of equally good routers.*/
296 ++n_best_support;
299 log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
300 n_best_support, best_support, n_pending_connections);
302 preferredexits = smartlist_create();
303 add_nickname_list_to_smartlist(preferredexits,options.ExitNodes);
305 excludedexits = smartlist_create();
306 add_nickname_list_to_smartlist(excludedexits,options.ExcludeNodes);
308 sl = smartlist_create();
310 /* If any routers definitely support any pending connections, choose one
311 * at random. */
312 if (best_support > 0) {
313 for (i = 0; i < smartlist_len(dir->routers); i++)
314 if (n_supported[i] == best_support)
315 smartlist_add(sl, smartlist_get(dir->routers, i));
317 smartlist_subtract(sl,excludedexits);
318 if (smartlist_overlap(sl,preferredexits))
319 smartlist_intersect(sl,preferredexits);
320 router = smartlist_choose(sl);
321 } else {
322 /* Either there are no pending connections, or no routers even seem to
323 * possibly support any of them. Choose a router at random. */
324 if (best_support == -1) {
325 log(LOG_WARN, "All routers are down or middleman -- choosing a doomed exit at random.");
327 for(i = 0; i < smartlist_len(dir->routers); i++)
328 if(n_supported[i] != -1)
329 smartlist_add(sl, smartlist_get(dir->routers, i));
331 smartlist_subtract(sl,excludedexits);
332 if (smartlist_overlap(sl,preferredexits))
333 smartlist_intersect(sl,preferredexits);
334 router = smartlist_choose(sl);
337 smartlist_free(preferredexits);
338 smartlist_free(excludedexits);
339 smartlist_free(sl);
340 tor_free(n_supported);
341 if(router) {
342 log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
343 return router;
345 log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
346 return NULL;
349 static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
351 smartlist_t *obsolete_routers;
352 routerinfo_t *r;
353 switch(purpose) {
354 case CIRCUIT_PURPOSE_C_GENERAL:
355 return choose_good_exit_server_general(dir);
356 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
357 obsolete_routers = smartlist_create();
358 router_add_nonrendezvous_to_list(obsolete_routers);
359 r = router_choose_random_node(dir, options.RendNodes, options.RendExcludeNodes, obsolete_routers);
360 smartlist_free(obsolete_routers);
361 return r;
362 default:
363 log_fn(LOG_WARN,"unhandled purpose %d", purpose);
364 assert(0);
366 return NULL; /* never reached */
369 cpath_build_state_t *onion_new_cpath_build_state(uint8_t purpose,
370 const char *exit_nickname) {
371 routerlist_t *rl;
372 int r;
373 cpath_build_state_t *info;
374 routerinfo_t *exit;
376 router_get_routerlist(&rl);
377 r = new_route_len(options.PathlenCoinWeight, purpose, rl->routers);
378 if (r < 0)
379 return NULL;
380 info = tor_malloc_zero(sizeof(cpath_build_state_t));
381 info->desired_path_len = r;
382 if(exit_nickname) { /* the circuit-builder pre-requested one */
383 log_fn(LOG_INFO,"Using requested exit node '%s'", exit_nickname);
384 info->chosen_exit = tor_strdup(exit_nickname);
385 } else { /* we have to decide one */
386 exit = choose_good_exit_server(purpose, rl);
387 if(!exit) {
388 log_fn(LOG_WARN,"failed to choose an exit server");
389 tor_free(info);
390 return NULL;
392 info->chosen_exit = tor_strdup(exit->nickname);
394 return info;
397 static int count_acceptable_routers(smartlist_t *routers) {
398 int i, j, n;
399 int num=0;
400 connection_t *conn;
401 routerinfo_t *r, *r2;
403 n = smartlist_len(routers);
404 for(i=0;i<n;i++) {
405 log_fn(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
406 r = smartlist_get(routers, i);
407 if(r->is_running == 0) {
408 log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
409 goto next_i_loop;
411 if(options.ORPort) {
412 conn = connection_exact_get_by_addr_port(r->addr, r->or_port);
413 if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
414 log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
415 goto next_i_loop;
418 for(j=0;j<i;j++) {
419 r2 = smartlist_get(routers, j);
420 if(!crypto_pk_cmp_keys(r->onion_pkey, r2->onion_pkey)) {
421 /* these guys are twins. so we've already counted him. */
422 log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
423 goto next_i_loop;
426 num++;
427 log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
428 next_i_loop:
429 ; /* our compiler may need an explicit statement after the label */
432 return num;
435 static void remove_twins_from_smartlist(smartlist_t *sl, routerinfo_t *twin) {
436 int i;
437 routerinfo_t *r;
439 if(twin == NULL)
440 return;
442 for(i=0; i < smartlist_len(sl); i++) {
443 r = smartlist_get(sl,i);
444 if (!crypto_pk_cmp_keys(r->onion_pkey, twin->onion_pkey)) {
445 smartlist_del(sl,i--);
450 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
452 if (*head_ptr) {
453 new_hop->next = (*head_ptr);
454 new_hop->prev = (*head_ptr)->prev;
455 (*head_ptr)->prev->next = new_hop;
456 (*head_ptr)->prev = new_hop;
457 } else {
458 *head_ptr = new_hop;
459 new_hop->prev = new_hop->next = new_hop;
463 int onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t *state, routerinfo_t **router_out)
465 int cur_len;
466 crypt_path_t *cpath, *hop;
467 routerinfo_t *r;
468 routerinfo_t *choice;
469 int i;
470 smartlist_t *sl, *excludednodes;
472 assert(head_ptr);
473 assert(router_out);
475 if (!*head_ptr) {
476 cur_len = 0;
477 } else {
478 cur_len = 1;
479 for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
480 ++cur_len;
483 if (cur_len >= state->desired_path_len) {
484 log_fn(LOG_DEBUG, "Path is complete: %d steps long",
485 state->desired_path_len);
486 return 1;
488 log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
489 state->desired_path_len);
491 excludednodes = smartlist_create();
492 add_nickname_list_to_smartlist(excludednodes,options.ExcludeNodes);
494 if(cur_len == state->desired_path_len - 1) { /* Picking last node */
495 log_fn(LOG_DEBUG, "Contemplating last hop: choice already made: %s",
496 state->chosen_exit);
497 choice = router_get_by_nickname(state->chosen_exit);
498 smartlist_free(excludednodes);
499 if(!choice) {
500 log_fn(LOG_WARN,"Our chosen exit %s is no longer in the directory? Discarding this circuit.",
501 state->chosen_exit);
502 return -1;
504 } else if(cur_len == 0) { /* picking first node */
505 /* try the nodes in EntryNodes first */
506 sl = smartlist_create();
507 add_nickname_list_to_smartlist(sl,options.EntryNodes);
508 /* XXX one day, consider picking chosen_exit knowing what's in EntryNodes */
509 remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
510 remove_twins_from_smartlist(sl,router_get_my_routerinfo());
511 smartlist_subtract(sl,excludednodes);
512 choice = smartlist_choose(sl);
513 smartlist_free(sl);
514 if(!choice) {
515 sl = smartlist_create();
516 router_add_running_routers_to_smartlist(sl);
517 remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
518 remove_twins_from_smartlist(sl,router_get_my_routerinfo());
519 smartlist_subtract(sl,excludednodes);
520 choice = smartlist_choose(sl);
521 smartlist_free(sl);
523 smartlist_free(excludednodes);
524 if(!choice) {
525 log_fn(LOG_WARN,"No acceptable routers while picking entry node. Discarding this circuit.");
526 return -1;
528 } else {
529 log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
530 sl = smartlist_create();
531 router_add_running_routers_to_smartlist(sl);
532 remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
533 remove_twins_from_smartlist(sl,router_get_my_routerinfo());
534 for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
535 r = router_get_by_addr_port(cpath->addr, cpath->port);
536 assert(r);
537 remove_twins_from_smartlist(sl,r);
539 smartlist_subtract(sl,excludednodes);
540 choice = smartlist_choose(sl);
541 smartlist_free(sl);
542 smartlist_free(excludednodes);
543 if(!choice) {
544 log_fn(LOG_WARN,"No acceptable routers while picking intermediate node. Discarding this circuit.");
545 return -1;
549 log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
550 choice->nickname, cur_len, state->chosen_exit);
552 hop = tor_malloc_zero(sizeof(crypt_path_t));
554 /* link hop into the cpath, at the end. */
555 onion_append_to_cpath(head_ptr, hop);
557 hop->state = CPATH_STATE_CLOSED;
559 hop->port = choice->or_port;
560 hop->addr = choice->addr;
562 hop->package_window = CIRCWINDOW_START;
563 hop->deliver_window = CIRCWINDOW_START;
565 log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
566 choice->nickname, cur_len);
568 *router_out = choice;
569 return 0;
572 /*----------------------------------------------------------------------*/
574 /* Given a router's 128 byte public key,
575 stores the following in onion_skin_out:
576 [16 bytes] Symmetric key for encrypting blob past RSA
577 [112 bytes] g^x part 1 (inside the RSA)
578 [16 bytes] g^x part 2 (symmetrically encrypted)
580 * Stores the DH private key into handshake_state_out for later completion
581 * of the handshake.
583 * The meeting point/cookies and auth are zeroed out for now.
586 onion_skin_create(crypto_pk_env_t *dest_router_key,
587 crypto_dh_env_t **handshake_state_out,
588 char *onion_skin_out) /* Must be ONIONSKIN_CHALLENGE_LEN bytes */
590 char *challenge = NULL;
591 crypto_dh_env_t *dh = NULL;
592 int dhbytes, pkbytes;
594 *handshake_state_out = NULL;
595 memset(onion_skin_out, 0, ONIONSKIN_CHALLENGE_LEN);
597 if (!(dh = crypto_dh_new()))
598 goto err;
600 dhbytes = crypto_dh_get_bytes(dh);
601 pkbytes = crypto_pk_keysize(dest_router_key);
602 assert(dhbytes == 128);
603 assert(pkbytes == 128);
604 challenge = tor_malloc_zero(DH_KEY_LEN);
606 if (crypto_dh_get_public(dh, challenge, dhbytes))
607 goto err;
609 #ifdef DEBUG_ONION_SKINS
610 #define PA(a,n) \
611 { int _i; for (_i = 0; _i<n; ++_i) printf("%02x ",((int)(a)[_i])&0xFF); }
613 printf("Client: client g^x:");
614 PA(challenge+16,3);
615 printf("...");
616 PA(challenge+141,3);
617 puts("");
619 printf("Client: client symkey:");
620 PA(challenge+0,16);
621 puts("");
622 #endif
624 /* set meeting point, meeting cookie, etc here. Leave zero for now. */
625 if (crypto_pk_public_hybrid_encrypt(dest_router_key, challenge,
626 DH_KEY_LEN,
627 onion_skin_out, PK_PKCS1_OAEP_PADDING, 1)<0)
628 goto err;
630 tor_free(challenge);
631 *handshake_state_out = dh;
633 return 0;
634 err:
635 tor_free(challenge);
636 if (dh) crypto_dh_free(dh);
637 return -1;
640 /* Given an encrypted DH public key as generated by onion_skin_create,
641 * and the private key for this onion router, generate the reply (128-byte
642 * DH plus the first 20 bytes of shared key material), and store the
643 * next key_out_len bytes of key material in key_out.
646 onion_skin_server_handshake(char *onion_skin, /* ONIONSKIN_CHALLENGE_LEN bytes */
647 crypto_pk_env_t *private_key,
648 crypto_pk_env_t *prev_private_key,
649 char *handshake_reply_out, /* ONIONSKIN_REPLY_LEN bytes */
650 char *key_out,
651 int key_out_len)
653 char challenge[ONIONSKIN_CHALLENGE_LEN];
654 crypto_dh_env_t *dh = NULL;
655 int len;
656 char *key_material=NULL;
657 int i;
658 crypto_pk_env_t *k;
660 len = -1;
661 for (i=0;i<2;++i) {
662 k = i==0?private_key:prev_private_key;
663 if (!k)
664 break;
665 len = crypto_pk_private_hybrid_decrypt(k,
666 onion_skin, ONIONSKIN_CHALLENGE_LEN,
667 challenge, PK_PKCS1_OAEP_PADDING);
668 if (len>0)
669 break;
671 if (len<0) {
672 log_fn(LOG_WARN, "Couldn't decrypt onionskin");
673 goto err;
674 } else if (len != DH_KEY_LEN) {
675 log_fn(LOG_WARN, "Unexpected onionskin length after decryption: %d",
676 len);
677 goto err;
680 dh = crypto_dh_new();
681 if (crypto_dh_get_public(dh, handshake_reply_out, DH_KEY_LEN))
682 goto err;
684 #ifdef DEBUG_ONION_SKINS
685 printf("Server: server g^y:");
686 PA(handshake_reply_out+0,3);
687 printf("...");
688 PA(handshake_reply_out+125,3);
689 puts("");
690 #endif
692 key_material = tor_malloc(DIGEST_LEN+key_out_len);
693 len = crypto_dh_compute_secret(dh, challenge, DH_KEY_LEN,
694 key_material, DIGEST_LEN+key_out_len);
695 if (len < 0)
696 goto err;
698 /* send back H(K|0) as proof that we learned K. */
699 memcpy(handshake_reply_out+DH_KEY_LEN, key_material, DIGEST_LEN);
701 /* use the rest of the key material for our shared keys, digests, etc */
702 memcpy(key_out, key_material+DIGEST_LEN, key_out_len);
704 #ifdef DEBUG_ONION_SKINS
705 printf("Server: key material:");
706 PA(buf, DH_KEY_LEN);
707 puts("");
708 printf("Server: keys out:");
709 PA(key_out, key_out_len);
710 puts("");
711 #endif
713 tor_free(key_material);
714 crypto_dh_free(dh);
715 return 0;
716 err:
717 tor_free(key_material);
718 if (dh) crypto_dh_free(dh);
720 return -1;
723 /* Finish the client side of the DH handshake.
724 * Given the 128 byte DH reply + 20 byte hash as generated by
725 * onion_skin_server_handshake and the handshake state generated by
726 * onion_skin_create, verify H(K) with the first 20 bytes of shared
727 * key material, then generate key_out_len more bytes of shared key
728 * material and store them in key_out.
730 * After the invocation, call crypto_dh_free on handshake_state.
733 onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
734 char *handshake_reply, /* Must be ONIONSKIN_REPLY_LEN bytes */
735 char *key_out,
736 int key_out_len)
738 int len;
739 char *key_material=NULL;
740 assert(crypto_dh_get_bytes(handshake_state) == DH_KEY_LEN);
742 #ifdef DEBUG_ONION_SKINS
743 printf("Client: server g^y:");
744 PA(handshake_reply+0,3);
745 printf("...");
746 PA(handshake_reply+125,3);
747 puts("");
748 #endif
750 key_material = tor_malloc(20+key_out_len);
751 len = crypto_dh_compute_secret(handshake_state, handshake_reply, DH_KEY_LEN,
752 key_material, 20+key_out_len);
753 if (len < 0)
754 return -1;
756 if(memcmp(key_material, handshake_reply+DH_KEY_LEN, 20)) {
757 /* H(K) does *not* match. Something fishy. */
758 tor_free(key_material);
759 log_fn(LOG_WARN,"Digest DOES NOT MATCH on onion handshake. Bug or attack.");
760 return -1;
763 /* use the rest of the key material for our shared keys, digests, etc */
764 memcpy(key_out, key_material+20, key_out_len);
766 #ifdef DEBUG_ONION_SKINS
767 printf("Client: keys out:");
768 PA(key_out, key_out_len);
769 puts("");
770 #endif
772 tor_free(key_material);
773 return 0;
777 Local Variables:
778 mode:c
779 indent-tabs-mode:nil
780 c-basic-offset:2
781 End: