onion.c 24 KB

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