onion.c 23 KB

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