onion.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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(routerinfo_t **rarray, int rarray_len);
  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. unsigned char iv[16];
  102. cell_t cell;
  103. memset(iv, 0, 16);
  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. circ->n_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
  113. crypto_digest_add_bytes(circ->n_digest, keys, 20);
  114. circ->p_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
  115. crypto_digest_add_bytes(circ->p_digest, keys+20, 20);
  116. log_fn(LOG_DEBUG,"init cipher forward 0x%.8x, backward 0x%.8x.",
  117. (unsigned int)*(uint32_t*)(keys+40), (unsigned int)*(uint32_t*)(keys+40+16));
  118. if (!(circ->n_crypto =
  119. crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40,iv,0))) {
  120. log_fn(LOG_WARN,"Cipher initialization failed (n).");
  121. return -1;
  122. }
  123. if (!(circ->p_crypto =
  124. crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40+16,iv,1))) {
  125. log_fn(LOG_WARN,"Cipher initialization failed (p).");
  126. return -1;
  127. }
  128. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, CRYPTO_SHA1_DIGEST_LEN);
  129. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  130. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  131. return 0;
  132. }
  133. extern int has_fetched_directory;
  134. static int new_route_len(double cw, routerinfo_t **rarray, int rarray_len) {
  135. int num_acceptable_routers;
  136. int routelen;
  137. assert((cw >= 0) && (cw < 1) && rarray); /* valid parameters */
  138. #ifdef TOR_PERF
  139. routelen = 2;
  140. #else
  141. routelen = 3;
  142. #endif
  143. #if 0
  144. for(routelen = 3; ; routelen++) { /* 3, increment until coinflip says we're done */
  145. if (crypto_pseudo_rand_int(255) >= cw*255) /* don't extend */
  146. break;
  147. }
  148. #endif
  149. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen, rarray_len);
  150. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  151. if(num_acceptable_routers < 2) {
  152. log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
  153. num_acceptable_routers);
  154. return -1;
  155. }
  156. if(num_acceptable_routers < routelen) {
  157. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
  158. routelen, num_acceptable_routers);
  159. routelen = num_acceptable_routers;
  160. }
  161. return routelen;
  162. }
  163. static routerinfo_t *choose_good_exit_server_general(routerlist_t *dir)
  164. {
  165. int *n_supported;
  166. int i, j;
  167. int n_pending_connections = 0;
  168. connection_t **carray;
  169. int n_connections;
  170. int best_support = -1;
  171. int n_best_support=0;
  172. smartlist_t *sl, *preferredexits, *excludedexits;
  173. routerinfo_t *router;
  174. get_connection_array(&carray, &n_connections);
  175. /* Count how many connections are waiting for a circuit to be built.
  176. * We use this for log messages now, but in the future we may depend on it.
  177. */
  178. for (i = 0; i < n_connections; ++i) {
  179. if (carray[i]->type == CONN_TYPE_AP &&
  180. carray[i]->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  181. !carray[i]->marked_for_close &&
  182. !circuit_stream_is_being_handled(carray[i]))
  183. ++n_pending_connections;
  184. }
  185. log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  186. n_pending_connections);
  187. /* Now we count, for each of the routers in the directory, how many
  188. * of the pending connections could possibly exit from that
  189. * router (n_supported[i]). (We can't be sure about cases where we
  190. * don't know the IP address of the pending connection.)
  191. */
  192. n_supported = tor_malloc(sizeof(int)*dir->n_routers);
  193. for (i = 0; i < dir->n_routers; ++i) { /* iterate over routers */
  194. if(!dir->routers[i]->is_running) {
  195. n_supported[i] = -1;
  196. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  197. dir->routers[i]->nickname, i);
  198. continue; /* skip routers that are known to be down */
  199. }
  200. if(router_exit_policy_rejects_all(dir->routers[i])) {
  201. n_supported[i] = -1;
  202. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  203. dir->routers[i]->nickname, i);
  204. continue; /* skip routers that reject all */
  205. }
  206. n_supported[i] = 0;
  207. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  208. if (carray[j]->type != CONN_TYPE_AP ||
  209. carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
  210. carray[j]->marked_for_close ||
  211. circuit_stream_is_being_handled(carray[j]))
  212. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  213. switch (connection_ap_can_use_exit(carray[j], dir->routers[i]))
  214. {
  215. case ADDR_POLICY_REJECTED:
  216. log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  217. dir->routers[i]->nickname, i);
  218. break; /* would be rejected; try next connection */
  219. case ADDR_POLICY_ACCEPTED:
  220. case ADDR_POLICY_UNKNOWN:
  221. ++n_supported[i];
  222. log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  223. dir->routers[i]->nickname, i, n_supported[i]);
  224. }
  225. } /* End looping over connections. */
  226. if (n_supported[i] > best_support) {
  227. /* If this router is better than previous ones, remember its index
  228. * and goodness, and start counting how many routers are this good. */
  229. best_support = n_supported[i]; n_best_support=1;
  230. log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  231. dir->routers[i]->nickname);
  232. } else if (n_supported[i] == best_support) {
  233. /* If this router is _as good_ as the best one, just increment the
  234. * count of equally good routers.*/
  235. ++n_best_support;
  236. }
  237. }
  238. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  239. n_best_support, best_support, n_pending_connections);
  240. preferredexits = smartlist_create();
  241. add_nickname_list_to_smartlist(preferredexits,options.ExitNodes);
  242. excludedexits = smartlist_create();
  243. add_nickname_list_to_smartlist(excludedexits,options.ExcludeNodes);
  244. sl = smartlist_create();
  245. /* If any routers definitely support any pending connections, choose one
  246. * at random. */
  247. if (best_support > 0) {
  248. for (i = 0; i < dir->n_routers; i++)
  249. if (n_supported[i] == best_support)
  250. smartlist_add(sl, dir->routers[i]);
  251. smartlist_subtract(sl,excludedexits);
  252. if (smartlist_overlap(sl,preferredexits))
  253. smartlist_intersect(sl,preferredexits);
  254. router = smartlist_choose(sl);
  255. } else {
  256. /* Either there are no pending connections, or no routers even seem to
  257. * possibly support any of them. Choose a router at random. */
  258. if (best_support == -1) {
  259. log(LOG_WARN, "All routers are down or middleman -- choosing a doomed exit at random.");
  260. }
  261. for(i = 0; i < dir->n_routers; i++)
  262. if(n_supported[i] != -1)
  263. smartlist_add(sl, 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. }
  269. smartlist_free(preferredexits);
  270. smartlist_free(excludedexits);
  271. smartlist_free(sl);
  272. tor_free(n_supported);
  273. if(router) {
  274. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  275. return router;
  276. }
  277. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  278. return NULL;
  279. }
  280. static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
  281. {
  282. if(purpose == CIRCUIT_PURPOSE_C_GENERAL)
  283. return choose_good_exit_server_general(dir);
  284. else
  285. return router_choose_random_node(dir, options.RendNodes, options.RendExcludeNodes, NULL);
  286. }
  287. cpath_build_state_t *onion_new_cpath_build_state(uint8_t purpose,
  288. const char *exit_nickname) {
  289. routerlist_t *rl;
  290. int r;
  291. cpath_build_state_t *info;
  292. routerinfo_t *exit;
  293. router_get_routerlist(&rl);
  294. r = new_route_len(options.PathlenCoinWeight, rl->routers, rl->n_routers);
  295. if (r < 0)
  296. return NULL;
  297. info = tor_malloc_zero(sizeof(cpath_build_state_t));
  298. info->desired_path_len = r;
  299. if(exit_nickname) { /* the circuit-builder pre-requested one */
  300. log_fn(LOG_INFO,"Using requested exit node '%s'", exit_nickname);
  301. info->chosen_exit = tor_strdup(exit_nickname);
  302. } else { /* we have to decide one */
  303. exit = choose_good_exit_server(purpose, rl);
  304. if(!exit) {
  305. log_fn(LOG_WARN,"failed to choose an exit server");
  306. tor_free(info);
  307. return NULL;
  308. }
  309. info->chosen_exit = tor_strdup(exit->nickname);
  310. }
  311. return info;
  312. }
  313. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  314. int i, j;
  315. int num=0;
  316. connection_t *conn;
  317. for(i=0;i<rarray_len;i++) {
  318. log_fn(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  319. if(rarray[i]->is_running == 0) {
  320. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  321. goto next_i_loop;
  322. }
  323. if(options.ORPort) {
  324. conn = connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port);
  325. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  326. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  327. goto next_i_loop;
  328. }
  329. }
  330. for(j=0;j<i;j++) {
  331. if(!crypto_pk_cmp_keys(rarray[i]->onion_pkey, rarray[j]->onion_pkey)) {
  332. /* these guys are twins. so we've already counted him. */
  333. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  334. goto next_i_loop;
  335. }
  336. }
  337. num++;
  338. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  339. next_i_loop:
  340. ; /* our compiler may need an explicit statement after the label */
  341. }
  342. return num;
  343. }
  344. static void remove_twins_from_smartlist(smartlist_t *sl, routerinfo_t *twin) {
  345. int i;
  346. routerinfo_t *r;
  347. if(twin == NULL)
  348. return;
  349. for(i=0; i < smartlist_len(sl); i++) {
  350. r = smartlist_get(sl,i);
  351. if (!crypto_pk_cmp_keys(r->onion_pkey, twin->onion_pkey)) {
  352. smartlist_del(sl,i--);
  353. }
  354. }
  355. }
  356. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  357. {
  358. if (*head_ptr) {
  359. new_hop->next = (*head_ptr);
  360. new_hop->prev = (*head_ptr)->prev;
  361. (*head_ptr)->prev->next = new_hop;
  362. (*head_ptr)->prev = new_hop;
  363. } else {
  364. *head_ptr = new_hop;
  365. new_hop->prev = new_hop->next = new_hop;
  366. }
  367. }
  368. int onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t *state, routerinfo_t **router_out)
  369. {
  370. int cur_len;
  371. crypt_path_t *cpath, *hop;
  372. routerinfo_t *r;
  373. routerinfo_t *choice;
  374. int i;
  375. smartlist_t *sl, *excludednodes;
  376. assert(head_ptr);
  377. assert(router_out);
  378. if (!*head_ptr) {
  379. cur_len = 0;
  380. } else {
  381. cur_len = 1;
  382. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  383. ++cur_len;
  384. }
  385. }
  386. if (cur_len >= state->desired_path_len) {
  387. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  388. state->desired_path_len);
  389. return 1;
  390. }
  391. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  392. state->desired_path_len);
  393. excludednodes = smartlist_create();
  394. add_nickname_list_to_smartlist(excludednodes,options.ExcludeNodes);
  395. if(cur_len == state->desired_path_len - 1) { /* Picking last node */
  396. log_fn(LOG_DEBUG, "Contemplating last hop: choice already made: %s",
  397. state->chosen_exit);
  398. choice = router_get_by_nickname(state->chosen_exit);
  399. smartlist_free(excludednodes);
  400. if(!choice) {
  401. log_fn(LOG_WARN,"Our chosen exit %s is no longer in the directory? Discarding this circuit.",
  402. state->chosen_exit);
  403. return -1;
  404. }
  405. } else if(cur_len == 0) { /* picking first node */
  406. /* try the nodes in EntryNodes first */
  407. sl = smartlist_create();
  408. add_nickname_list_to_smartlist(sl,options.EntryNodes);
  409. /* XXX one day, consider picking chosen_exit knowing what's in EntryNodes */
  410. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  411. smartlist_subtract(sl,excludednodes);
  412. choice = smartlist_choose(sl);
  413. smartlist_free(sl);
  414. if(!choice) {
  415. sl = smartlist_create();
  416. router_add_running_routers_to_smartlist(sl);
  417. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  418. smartlist_subtract(sl,excludednodes);
  419. choice = smartlist_choose(sl);
  420. smartlist_free(sl);
  421. }
  422. smartlist_free(excludednodes);
  423. if(!choice) {
  424. log_fn(LOG_WARN,"No acceptable routers while picking entry node. Discarding this circuit.");
  425. return -1;
  426. }
  427. } else {
  428. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  429. sl = smartlist_create();
  430. router_add_running_routers_to_smartlist(sl);
  431. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  432. for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
  433. r = router_get_by_addr_port(cpath->addr, cpath->port);
  434. assert(r);
  435. remove_twins_from_smartlist(sl,r);
  436. }
  437. smartlist_subtract(sl,excludednodes);
  438. choice = smartlist_choose(sl);
  439. smartlist_free(sl);
  440. smartlist_free(excludednodes);
  441. if(!choice) {
  442. log_fn(LOG_WARN,"No acceptable routers while picking intermediate node. Discarding this circuit.");
  443. return -1;
  444. }
  445. }
  446. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  447. choice->nickname, cur_len, state->chosen_exit);
  448. hop = (crypt_path_t *)tor_malloc_zero(sizeof(crypt_path_t));
  449. /* link hop into the cpath, at the end. */
  450. onion_append_to_cpath(head_ptr, hop);
  451. hop->state = CPATH_STATE_CLOSED;
  452. hop->port = choice->or_port;
  453. hop->addr = choice->addr;
  454. hop->package_window = CIRCWINDOW_START;
  455. hop->deliver_window = CIRCWINDOW_START;
  456. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  457. choice->nickname, cur_len);
  458. *router_out = choice;
  459. return 0;
  460. }
  461. /*----------------------------------------------------------------------*/
  462. /* Given a router's 128 byte public key,
  463. stores the following in onion_skin_out:
  464. [16 bytes] Symmetric key for encrypting blob past RSA
  465. [112 bytes] g^x part 1 (inside the RSA)
  466. [16 bytes] g^x part 2 (symmetrically encrypted)
  467. [ 6 bytes] Meeting point (IP/port)
  468. [ 8 bytes] Meeting cookie
  469. [16 bytes] End-to-end authentication [optional]
  470. * Stores the DH private key into handshake_state_out for later completion
  471. * of the handshake.
  472. *
  473. * The meeting point/cookies and auth are zeroed out for now.
  474. */
  475. int
  476. onion_skin_create(crypto_pk_env_t *dest_router_key,
  477. crypto_dh_env_t **handshake_state_out,
  478. char *onion_skin_out) /* Must be ONIONSKIN_CHALLENGE_LEN bytes */
  479. {
  480. char iv[16];
  481. char *challenge = NULL;
  482. crypto_dh_env_t *dh = NULL;
  483. crypto_cipher_env_t *cipher = NULL;
  484. int dhbytes, pkbytes;
  485. *handshake_state_out = NULL;
  486. memset(onion_skin_out, 0, ONIONSKIN_CHALLENGE_LEN);
  487. memset(iv, 0, 16);
  488. if (!(dh = crypto_dh_new()))
  489. goto err;
  490. dhbytes = crypto_dh_get_bytes(dh);
  491. pkbytes = crypto_pk_keysize(dest_router_key);
  492. assert(dhbytes == 128);
  493. assert(pkbytes == 128);
  494. challenge = (char *)tor_malloc_zero(ONIONSKIN_CHALLENGE_LEN);
  495. if (crypto_rand(16, challenge))
  496. goto err;
  497. /* You can't just run around RSA-encrypting any bitstream: if it's
  498. * greater than the RSA key, then OpenSSL will happily encrypt,
  499. * and later decrypt to the wrong value. So we set the first bit
  500. * of 'challenge' to 0. This means that our symmetric key is really
  501. * only 127 bits.
  502. */
  503. challenge[0] &= 0x7f;
  504. if (crypto_dh_get_public(dh, challenge+16, dhbytes))
  505. goto err;
  506. #ifdef DEBUG_ONION_SKINS
  507. #define PA(a,n) \
  508. { int _i; for (_i = 0; _i<n; ++_i) printf("%02x ",((int)(a)[_i])&0xFF); }
  509. printf("Client: client g^x:");
  510. PA(challenge+16,3);
  511. printf("...");
  512. PA(challenge+141,3);
  513. puts("");
  514. printf("Client: client symkey:");
  515. PA(challenge+0,16);
  516. puts("");
  517. #endif
  518. /* set meeting point, meeting cookie, etc here. Leave zero for now. */
  519. cipher = crypto_create_init_cipher(ONION_CIPHER, challenge, iv, 1);
  520. if (!cipher)
  521. goto err;
  522. if (crypto_pk_public_encrypt(dest_router_key, challenge, pkbytes,
  523. onion_skin_out, RSA_NO_PADDING)==-1)
  524. goto err;
  525. if (crypto_cipher_encrypt(cipher, challenge+pkbytes, ONIONSKIN_CHALLENGE_LEN-pkbytes,
  526. onion_skin_out+pkbytes))
  527. goto err;
  528. tor_free(challenge);
  529. crypto_free_cipher_env(cipher);
  530. *handshake_state_out = dh;
  531. return 0;
  532. err:
  533. tor_free(challenge);
  534. if (dh) crypto_dh_free(dh);
  535. if (cipher) crypto_free_cipher_env(cipher);
  536. return -1;
  537. }
  538. /* Given an encrypted DH public key as generated by onion_skin_create,
  539. * and the private key for this onion router, generate the reply (128-byte
  540. * DH plus the first 20 bytes of shared key material), and store the
  541. * next key_out_len bytes of key material in key_out.
  542. */
  543. int
  544. onion_skin_server_handshake(char *onion_skin, /* ONIONSKIN_CHALLENGE_LEN bytes */
  545. crypto_pk_env_t *private_key,
  546. char *handshake_reply_out, /* ONIONSKIN_REPLY_LEN bytes */
  547. char *key_out,
  548. int key_out_len)
  549. {
  550. char challenge[ONIONSKIN_CHALLENGE_LEN];
  551. char iv[16];
  552. crypto_dh_env_t *dh = NULL;
  553. crypto_cipher_env_t *cipher = NULL;
  554. int pkbytes;
  555. int len;
  556. char *key_material=NULL;
  557. memset(iv, 0, 16);
  558. pkbytes = crypto_pk_keysize(private_key);
  559. if (crypto_pk_private_decrypt(private_key,
  560. onion_skin, pkbytes,
  561. challenge, RSA_NO_PADDING) == -1)
  562. goto err;
  563. #ifdef DEBUG_ONION_SKINS
  564. printf("Server: client symkey:");
  565. PA(buf+0,16);
  566. puts("");
  567. #endif
  568. cipher = crypto_create_init_cipher(ONION_CIPHER, challenge, iv, 0);
  569. if (crypto_cipher_decrypt(cipher, onion_skin+pkbytes, ONIONSKIN_CHALLENGE_LEN-pkbytes,
  570. challenge+pkbytes))
  571. goto err;
  572. #ifdef DEBUG_ONION_SKINS
  573. printf("Server: client g^x:");
  574. PA(buf+16,3);
  575. printf("...");
  576. PA(buf+141,3);
  577. puts("");
  578. #endif
  579. dh = crypto_dh_new();
  580. if (crypto_dh_get_public(dh, handshake_reply_out, DH_KEY_LEN))
  581. goto err;
  582. #ifdef DEBUG_ONION_SKINS
  583. printf("Server: server g^y:");
  584. PA(handshake_reply_out+0,3);
  585. printf("...");
  586. PA(handshake_reply_out+125,3);
  587. puts("");
  588. #endif
  589. key_material = tor_malloc(20+key_out_len);
  590. len = crypto_dh_compute_secret(dh, challenge+16, DH_KEY_LEN,
  591. key_material, 20+key_out_len);
  592. if (len < 0)
  593. goto err;
  594. /* send back H(K|0) as proof that we learned K. */
  595. memcpy(handshake_reply_out+DH_KEY_LEN, key_material, 20);
  596. /* use the rest of the key material for our shared keys, digests, etc */
  597. memcpy(key_out, key_material+20, key_out_len);
  598. #ifdef DEBUG_ONION_SKINS
  599. printf("Server: key material:");
  600. PA(buf, DH_KEY_LEN);
  601. puts("");
  602. printf("Server: keys out:");
  603. PA(key_out, key_out_len);
  604. puts("");
  605. #endif
  606. tor_free(key_material);
  607. crypto_free_cipher_env(cipher);
  608. crypto_dh_free(dh);
  609. return 0;
  610. err:
  611. tor_free(key_material);
  612. if (cipher) crypto_free_cipher_env(cipher);
  613. if (dh) crypto_dh_free(dh);
  614. return -1;
  615. }
  616. /* Finish the client side of the DH handshake.
  617. * Given the 128 byte DH reply + 20 byte hash as generated by
  618. * onion_skin_server_handshake and the handshake state generated by
  619. * onion_skin_create, verify H(K) with the first 20 bytes of shared
  620. * key material, then generate key_out_len more bytes of shared key
  621. * material and store them in key_out.
  622. *
  623. * After the invocation, call crypto_dh_free on handshake_state.
  624. */
  625. int
  626. onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
  627. char *handshake_reply, /* Must be ONIONSKIN_REPLY_LEN bytes */
  628. char *key_out,
  629. int key_out_len)
  630. {
  631. int len;
  632. char *key_material=NULL;
  633. assert(crypto_dh_get_bytes(handshake_state) == DH_KEY_LEN);
  634. #ifdef DEBUG_ONION_SKINS
  635. printf("Client: server g^y:");
  636. PA(handshake_reply+0,3);
  637. printf("...");
  638. PA(handshake_reply+125,3);
  639. puts("");
  640. #endif
  641. key_material = tor_malloc(20+key_out_len);
  642. len = crypto_dh_compute_secret(handshake_state, handshake_reply, DH_KEY_LEN,
  643. key_material, 20+key_out_len);
  644. if (len < 0)
  645. return -1;
  646. if(memcmp(key_material, handshake_reply+DH_KEY_LEN, 20)) {
  647. /* H(K) does *not* match. Something fishy. */
  648. tor_free(key_material);
  649. log_fn(LOG_WARN,"Digest DOES NOT MATCH on onion handshake. Bug or attack.");
  650. return -1;
  651. }
  652. /* use the rest of the key material for our shared keys, digests, etc */
  653. memcpy(key_out, key_material+20, key_out_len);
  654. #ifdef DEBUG_ONION_SKINS
  655. printf("Client: keys out:");
  656. PA(key_out, key_out_len);
  657. puts("");
  658. #endif
  659. tor_free(key_material);
  660. return 0;
  661. }
  662. /*
  663. Local Variables:
  664. mode:c
  665. indent-tabs-mode:nil
  666. c-basic-offset:2
  667. End:
  668. */