onion.c 25 KB

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