onion.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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_zero(sizeof(struct onion_queue_t));
  29. tmp->circ = circ;
  30. if(!ol_tail) {
  31. assert(!ol_list);
  32. assert(!ol_length);
  33. ol_list = tmp;
  34. ol_tail = tmp;
  35. ol_length++;
  36. return 0;
  37. }
  38. assert(ol_list);
  39. assert(!ol_tail->next);
  40. if(ol_length >= options.MaxOnionsPending) {
  41. log_fn(LOG_WARN,"Already have %d onions queued. Closing.", ol_length);
  42. free(tmp);
  43. return -1;
  44. }
  45. ol_length++;
  46. ol_tail->next = tmp;
  47. ol_tail = tmp;
  48. return 0;
  49. }
  50. circuit_t *onion_next_task(void) {
  51. circuit_t *circ;
  52. if(!ol_list)
  53. return NULL; /* no onions pending, we're done */
  54. assert(ol_list->circ);
  55. assert(ol_list->circ->p_conn); /* make sure it's still valid */
  56. #if 0
  57. if(!ol_list->circ->p_conn) {
  58. log_fn(LOG_INFO,"ol_list->circ->p_conn null, must have died?");
  59. onion_pending_remove(ol_list->circ);
  60. return onion_next_task(); /* recurse: how about the next one? */
  61. }
  62. #endif
  63. assert(ol_length > 0);
  64. circ = ol_list->circ;
  65. onion_pending_remove(ol_list->circ);
  66. return circ;
  67. }
  68. /* go through ol_list, find the onion_queue_t element which points to
  69. * circ, remove and free that element. leave circ itself alone.
  70. */
  71. void onion_pending_remove(circuit_t *circ) {
  72. struct onion_queue_t *tmpo, *victim;
  73. if(!ol_list)
  74. return; /* nothing here. */
  75. /* first check to see if it's the first entry */
  76. tmpo = ol_list;
  77. if(tmpo->circ == circ) {
  78. /* it's the first one. remove it from the list. */
  79. ol_list = tmpo->next;
  80. if(!ol_list)
  81. ol_tail = NULL;
  82. ol_length--;
  83. victim = tmpo;
  84. } else { /* we need to hunt through the rest of the list */
  85. for( ;tmpo->next && tmpo->next->circ != circ; tmpo=tmpo->next) ;
  86. if(!tmpo->next) {
  87. log_fn(LOG_DEBUG,"circ (p_circ_id %d) not in list, probably at cpuworker.",circ->p_circ_id);
  88. return;
  89. }
  90. /* now we know tmpo->next->circ == circ */
  91. victim = tmpo->next;
  92. tmpo->next = victim->next;
  93. if(ol_tail == victim)
  94. ol_tail = tmpo;
  95. ol_length--;
  96. }
  97. /* now victim points to the element that needs to be removed */
  98. free(victim);
  99. }
  100. /* given a response payload and keys, initialize, then send a created cell back */
  101. int onionskin_answer(circuit_t *circ, unsigned char *payload, unsigned char *keys) {
  102. unsigned char iv[16];
  103. cell_t cell;
  104. memset(iv, 0, 16);
  105. memset(&cell, 0, sizeof(cell_t));
  106. cell.command = CELL_CREATED;
  107. cell.circ_id = circ->p_circ_id;
  108. cell.length = DH_KEY_LEN;
  109. circ->state = CIRCUIT_STATE_OPEN;
  110. log_fn(LOG_DEBUG,"Entering.");
  111. memcpy(cell.payload, payload, DH_KEY_LEN);
  112. log_fn(LOG_DEBUG,"init cipher forward %d, backward %d.", *(int*)keys, *(int*)(keys+16));
  113. if (!(circ->n_crypto =
  114. crypto_create_init_cipher(CIRCUIT_CIPHER,keys,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+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. char **parse_nickname_list(char *list, int *num) {
  128. char **out;
  129. char *start,*end;
  130. int i;
  131. while(isspace(*list)) list++;
  132. i=0, start = list;
  133. while(*start) {
  134. while(*start && !isspace(*start)) start++;
  135. i++;
  136. while(isspace(*start)) start++;
  137. }
  138. out = tor_malloc(i * sizeof(char *));
  139. i=0, start=list;
  140. while(*start) {
  141. end=start; while(*end && !isspace(*end)) end++;
  142. out[i] = tor_malloc(MAX_NICKNAME_LEN);
  143. strncpy(out[i],start,end-start);
  144. out[i][end-start] = 0; /* null terminate it */
  145. i++;
  146. while(isspace(*end)) end++;
  147. start = end;
  148. }
  149. *num = i;
  150. return out;
  151. }
  152. static int new_route_len(double cw, routerinfo_t **rarray, int rarray_len) {
  153. int num_acceptable_routers;
  154. int routelen;
  155. assert((cw >= 0) && (cw < 1) && rarray); /* valid parameters */
  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. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen, rarray_len);
  161. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  162. if(num_acceptable_routers < 2) {
  163. log_fn(LOG_INFO,"Not enough acceptable routers. Failing.");
  164. return -1;
  165. }
  166. if(num_acceptable_routers < routelen) {
  167. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",routelen, num_acceptable_routers);
  168. routelen = num_acceptable_routers;
  169. }
  170. if (routelen < 1) {
  171. log_fn(LOG_WARN,"Didn't find any acceptable routers. Failing.");
  172. return -1;
  173. }
  174. return routelen;
  175. }
  176. static routerinfo_t *choose_good_exit_server(directory_t *dir)
  177. {
  178. int *n_supported;
  179. int *n_maybe_supported;
  180. int i, j;
  181. int n_pending_connections = 0;
  182. connection_t **carray;
  183. int n_connections;
  184. int best_support = -1;
  185. int best_maybe_support = -1;
  186. int best_support_idx = -1;
  187. int best_maybe_support_idx = -1;
  188. int n_best_support=0, n_best_maybe_support=0;
  189. int n_running_routers=0;
  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. ++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. ++n_running_routers;
  226. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  227. if (carray[j]->type != CONN_TYPE_AP ||
  228. carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
  229. carray[j]->marked_for_close)
  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 pending connections, and %d that might support %d/%d.",
  270. n_best_support, best_support, n_pending_connections,
  271. n_best_maybe_support, best_maybe_support, n_pending_connections);
  272. /* If any routers definitely support any pending connections, choose one
  273. * at random. */
  274. if (best_support > 0) {
  275. i = crypto_pseudo_rand_int(n_best_support);
  276. /* Iterate over the routers, until we find the i-th one such that
  277. * n_supported[j] == best_support
  278. */
  279. for (j = best_support_idx; j < dir->n_routers; ++j) {
  280. if (n_supported[j] == best_support) {
  281. if (i)
  282. --i;
  283. else {
  284. tor_free(n_supported); tor_free(n_maybe_supported);
  285. log_fn(LOG_DEBUG, "Chose exit server '%s'", dir->routers[j]->nickname);
  286. return dir->routers[j];
  287. }
  288. }
  289. }
  290. /* This point should never be reached. */
  291. assert(0);
  292. }
  293. /* If any routers _maybe_ support pending connections, choose one at
  294. * random, as above. */
  295. if (best_maybe_support > 0) {
  296. i = crypto_pseudo_rand_int(n_best_maybe_support);
  297. for (j = best_maybe_support_idx; j < dir->n_routers; ++j) {
  298. if (n_maybe_supported[j] == best_maybe_support) {
  299. if (i)
  300. --i;
  301. else {
  302. tor_free(n_supported); tor_free(n_maybe_supported);
  303. log_fn(LOG_DEBUG, "Chose exit server '%s'", dir->routers[j]->nickname);
  304. return dir->routers[j];
  305. }
  306. }
  307. }
  308. /* This point should never be reached. */
  309. assert(0);
  310. }
  311. /* Either there are no pending connections, or no routers even seem to
  312. * possibly support any of them. Choose a router at random. */
  313. if (!n_running_routers) {
  314. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  315. return NULL;
  316. }
  317. /* Iterate over the routers, till we find the i'th one that has ->is_running
  318. * and allows exits. */
  319. i = crypto_pseudo_rand_int(n_running_routers);
  320. for (j = 0; j < dir->n_routers; ++j) {
  321. if (n_supported[j] != -1) {
  322. if (i)
  323. --i;
  324. else {
  325. tor_free(n_supported); tor_free(n_maybe_supported);
  326. log_fn(LOG_DEBUG, "Chose exit server '%s'", dir->routers[j]->nickname);
  327. return dir->routers[j];
  328. }
  329. }
  330. }
  331. assert(0);
  332. return NULL;
  333. }
  334. cpath_build_state_t *onion_new_cpath_build_state(void) {
  335. directory_t *dir;
  336. int r;
  337. cpath_build_state_t *info;
  338. router_get_directory(&dir);
  339. r = new_route_len(options.PathlenCoinWeight, dir->routers, dir->n_routers);
  340. if (r < 0)
  341. return NULL;
  342. info = tor_malloc(sizeof(cpath_build_state_t));
  343. info->desired_path_len = r;
  344. info->chosen_exit = tor_strdup(choose_good_exit_server(dir)->nickname);
  345. return info;
  346. }
  347. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  348. int i, j;
  349. int num=0;
  350. connection_t *conn;
  351. for(i=0;i<rarray_len;i++) {
  352. log_fn(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  353. if(rarray[i]->is_running == 0) {
  354. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  355. goto next_i_loop;
  356. }
  357. if(options.ORPort) {
  358. conn = connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port);
  359. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  360. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  361. goto next_i_loop;
  362. }
  363. }
  364. for(j=0;j<i;j++) {
  365. if(!crypto_pk_cmp_keys(rarray[i]->onion_pkey, rarray[j]->onion_pkey)) {
  366. /* these guys are twins. so we've already counted him. */
  367. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  368. goto next_i_loop;
  369. }
  370. }
  371. num++;
  372. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  373. next_i_loop:
  374. ; /* our compiler may need an explicit statement after the label */
  375. }
  376. return num;
  377. }
  378. int onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t *state, routerinfo_t **router_out)
  379. {
  380. int cur_len;
  381. crypt_path_t *cpath, *hop;
  382. routerinfo_t **rarray, *r;
  383. routerinfo_t *choice;
  384. int rarray_len;
  385. int i;
  386. directory_t *dir;
  387. int n_failures;
  388. assert(head_ptr);
  389. assert(router_out);
  390. router_get_directory(&dir);
  391. rarray = dir->routers;
  392. rarray_len = dir->n_routers;
  393. if (!*head_ptr) {
  394. cur_len = 0;
  395. } else {
  396. cur_len = 1;
  397. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  398. ++cur_len;
  399. }
  400. }
  401. if (cur_len >= state->desired_path_len) {
  402. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  403. state->desired_path_len);
  404. return 1;
  405. }
  406. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  407. state->desired_path_len);
  408. n_failures = 0;
  409. goto start;
  410. again:
  411. log_fn(LOG_DEBUG, "Picked an already-selected router for hop %d; retrying.",
  412. cur_len);
  413. ++n_failures;
  414. if (n_failures == 25) {
  415. /* This actually happens with P=1/30,000,000 when we _could_ build a
  416. * circuit. For now, let's leave it in.
  417. */
  418. log_fn(LOG_INFO, "Unable to continue generating circuit path");
  419. return -1;
  420. }
  421. start:
  422. /* XXX through each of these, don't pick nodes that are down */
  423. if(cur_len == 0) { /* picking entry node */
  424. log_fn(LOG_DEBUG, "Contemplating first hop: random choice.");
  425. choice = rarray[crypto_pseudo_rand_int(rarray_len)];
  426. } else if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  427. log_fn(LOG_DEBUG, "Contemplating last hop: choice already made.");
  428. choice = router_get_by_nickname(state->chosen_exit);
  429. /* XXX check if null */
  430. } else {
  431. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  432. choice = rarray[crypto_pseudo_rand_int(rarray_len)];
  433. }
  434. log_fn(LOG_DEBUG,"Contemplating router %s for hop %d (exit is %s)",
  435. choice->nickname, cur_len, state->chosen_exit);
  436. if (cur_len != state->desired_path_len-1 &&
  437. !strcasecmp(choice->nickname, state->chosen_exit)) {
  438. goto again;
  439. }
  440. for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
  441. r = router_get_by_addr_port(cpath->addr, cpath->port);
  442. if ((r && !crypto_pk_cmp_keys(r->onion_pkey, choice->onion_pkey))
  443. || (cur_len != state->desired_path_len-1 &&
  444. !strcasecmp(choice->nickname, state->chosen_exit))
  445. || (cpath->addr == choice->addr &&
  446. cpath->port == choice->or_port)
  447. || (options.ORPort &&
  448. !(connection_twin_get_by_addr_port(choice->addr,
  449. choice->or_port)))) {
  450. goto again;
  451. }
  452. }
  453. /* Okay, so we haven't used 'choice' before. */
  454. hop = (crypt_path_t *)tor_malloc_zero(sizeof(crypt_path_t));
  455. /* link hop into the cpath, at the end. */
  456. if (*head_ptr) {
  457. hop->next = (*head_ptr);
  458. hop->prev = (*head_ptr)->prev;
  459. (*head_ptr)->prev->next = hop;
  460. (*head_ptr)->prev = hop;
  461. } else {
  462. *head_ptr = hop;
  463. hop->prev = hop->next = hop;
  464. }
  465. hop->state = CPATH_STATE_CLOSED;
  466. hop->port = choice->or_port;
  467. hop->addr = choice->addr;
  468. hop->package_window = CIRCWINDOW_START;
  469. hop->deliver_window = CIRCWINDOW_START;
  470. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  471. choice->nickname, cur_len);
  472. *router_out = choice;
  473. return 0;
  474. }
  475. /*----------------------------------------------------------------------*/
  476. /* Given a router's public key, generates a 144-byte encrypted DH pubkey,
  477. * and stores it into onion_skin out. Stores the DH private key into
  478. * handshake_state_out for later completion of the handshake.
  479. *
  480. * The encrypted pubkey is formed as follows:
  481. * 16 bytes of symmetric key
  482. * 128 bytes of g^x for DH.
  483. * The first 128 bytes are RSA-encrypted with the server's public key,
  484. * and the last 16 are encrypted with the symmetric key.
  485. */
  486. int
  487. onion_skin_create(crypto_pk_env_t *dest_router_key,
  488. crypto_dh_env_t **handshake_state_out,
  489. char *onion_skin_out) /* Must be DH_ONIONSKIN_LEN bytes long */
  490. {
  491. char iv[16];
  492. char *pubkey = NULL;
  493. crypto_dh_env_t *dh = NULL;
  494. crypto_cipher_env_t *cipher = NULL;
  495. int dhbytes, pkbytes;
  496. *handshake_state_out = NULL;
  497. memset(onion_skin_out, 0, DH_ONIONSKIN_LEN);
  498. memset(iv, 0, 16);
  499. if (!(dh = crypto_dh_new()))
  500. goto err;
  501. dhbytes = crypto_dh_get_bytes(dh);
  502. pkbytes = crypto_pk_keysize(dest_router_key);
  503. assert(dhbytes+16 == DH_ONIONSKIN_LEN);
  504. pubkey = (char *)tor_malloc(dhbytes+16);
  505. if (crypto_rand(16, pubkey))
  506. goto err;
  507. /* XXXX You can't just run around RSA-encrypting any bitstream: if it's
  508. * greater than the RSA key, then OpenSSL will happily encrypt,
  509. * and later decrypt to the wrong value. So we set the first bit
  510. * of 'pubkey' to 0. This means that our symmetric key is really only
  511. * 127 bits long, but since it shouldn't be necessary to encrypt
  512. * DH public keys values in the first place, we should be fine.
  513. */
  514. pubkey[0] &= 0x7f;
  515. if (crypto_dh_get_public(dh, pubkey+16, dhbytes))
  516. goto err;
  517. #ifdef DEBUG_ONION_SKINS
  518. #define PA(a,n) \
  519. { int _i; for (_i = 0; _i<n; ++_i) printf("%02x ",((int)(a)[_i])&0xFF); }
  520. printf("Client: client g^x:");
  521. PA(pubkey+16,3);
  522. printf("...");
  523. PA(pubkey+141,3);
  524. puts("");
  525. printf("Client: client symkey:");
  526. PA(pubkey+0,16);
  527. puts("");
  528. #endif
  529. cipher = crypto_create_init_cipher(ONION_CIPHER, pubkey, iv, 1);
  530. if (!cipher)
  531. goto err;
  532. if (crypto_pk_public_encrypt(dest_router_key, pubkey, pkbytes,
  533. onion_skin_out, RSA_NO_PADDING)==-1)
  534. goto err;
  535. if (crypto_cipher_encrypt(cipher, pubkey+pkbytes, dhbytes+16-pkbytes,
  536. onion_skin_out+pkbytes))
  537. goto err;
  538. free(pubkey);
  539. crypto_free_cipher_env(cipher);
  540. *handshake_state_out = dh;
  541. return 0;
  542. err:
  543. tor_free(pubkey);
  544. if (dh) crypto_dh_free(dh);
  545. if (cipher) crypto_free_cipher_env(cipher);
  546. return -1;
  547. }
  548. /* Given an encrypted DH public key as generated by onion_skin_create,
  549. * and the private key for this onion router, generate the 128-byte DH
  550. * reply, and key_out_len bytes of key material, stored in key_out.
  551. */
  552. int
  553. onion_skin_server_handshake(char *onion_skin, /* DH_ONIONSKIN_LEN bytes long */
  554. crypto_pk_env_t *private_key,
  555. char *handshake_reply_out, /* DH_KEY_LEN bytes long */
  556. char *key_out,
  557. int key_out_len)
  558. {
  559. char buf[DH_ONIONSKIN_LEN];
  560. char iv[16];
  561. crypto_dh_env_t *dh = NULL;
  562. crypto_cipher_env_t *cipher = NULL;
  563. int pkbytes;
  564. int len;
  565. memset(iv, 0, 16);
  566. pkbytes = crypto_pk_keysize(private_key);
  567. if (crypto_pk_private_decrypt(private_key,
  568. onion_skin, pkbytes,
  569. buf, RSA_NO_PADDING) == -1)
  570. goto err;
  571. #ifdef DEBUG_ONION_SKINS
  572. printf("Server: client symkey:");
  573. PA(buf+0,16);
  574. puts("");
  575. #endif
  576. cipher = crypto_create_init_cipher(ONION_CIPHER, buf, iv, 0);
  577. if (crypto_cipher_decrypt(cipher, onion_skin+pkbytes, DH_ONIONSKIN_LEN-pkbytes,
  578. buf+pkbytes))
  579. goto err;
  580. #ifdef DEBUG_ONION_SKINS
  581. printf("Server: client g^x:");
  582. PA(buf+16,3);
  583. printf("...");
  584. PA(buf+141,3);
  585. puts("");
  586. #endif
  587. dh = crypto_dh_new();
  588. if (crypto_dh_get_public(dh, handshake_reply_out, DH_KEY_LEN))
  589. goto err;
  590. #ifdef DEBUG_ONION_SKINS
  591. printf("Server: server g^y:");
  592. PA(handshake_reply_out+0,3);
  593. printf("...");
  594. PA(handshake_reply_out+125,3);
  595. puts("");
  596. #endif
  597. len = crypto_dh_compute_secret(dh, buf+16, DH_KEY_LEN, key_out, key_out_len);
  598. if (len < 0)
  599. goto err;
  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. crypto_free_cipher_env(cipher);
  609. crypto_dh_free(dh);
  610. return 0;
  611. err:
  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 as generated by onion_skin_server_handshake
  618. * and the handshake state generated by onion_skin_create, generate
  619. * key_out_len bytes of shared key material and store them in key_out.
  620. *
  621. * After the invocation, call crypto_dh_free on handshake_state.
  622. */
  623. int
  624. onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
  625. char *handshake_reply,/* Must be DH_KEY_LEN bytes long*/
  626. char *key_out,
  627. int key_out_len)
  628. {
  629. int len;
  630. assert(crypto_dh_get_bytes(handshake_state) == DH_KEY_LEN);
  631. #ifdef DEBUG_ONION_SKINS
  632. printf("Client: server g^y:");
  633. PA(handshake_reply+0,3);
  634. printf("...");
  635. PA(handshake_reply+125,3);
  636. puts("");
  637. #endif
  638. len = crypto_dh_compute_secret(handshake_state, handshake_reply, DH_KEY_LEN,
  639. key_out, key_out_len);
  640. if (len < 0)
  641. return -1;
  642. #ifdef DEBUG_ONION_SKINS
  643. printf("Client: keys out:");
  644. PA(key_out, key_out_len);
  645. puts("");
  646. #endif
  647. return 0;
  648. }
  649. /*
  650. Local Variables:
  651. mode:c
  652. indent-tabs-mode:nil
  653. c-basic-offset:2
  654. End:
  655. */