onion.c 22 KB

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