onion.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /* Copyright 2001,2002 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. static int onionskin_process(circuit_t *circ);
  8. int decide_aci_type(uint32_t local_addr, uint16_t local_port,
  9. uint32_t remote_addr, uint16_t remote_port) {
  10. if(local_addr > remote_addr)
  11. return ACI_TYPE_HIGHER;
  12. if(local_addr < remote_addr)
  13. return ACI_TYPE_LOWER;
  14. if(local_port > remote_port)
  15. return ACI_TYPE_HIGHER;
  16. /* else */
  17. return ACI_TYPE_LOWER;
  18. }
  19. /* global (within this file) variables used by the next few functions */
  20. static struct onion_queue_t *ol_list=NULL;
  21. static struct onion_queue_t *ol_tail=NULL;
  22. static int ol_length=0;
  23. int onion_pending_add(circuit_t *circ) {
  24. struct onion_queue_t *tmp;
  25. tmp = tor_malloc(sizeof(struct onion_queue_t));
  26. memset(tmp, 0, sizeof(struct onion_queue_t));
  27. tmp->circ = circ;
  28. if(!ol_tail) {
  29. assert(!ol_list);
  30. assert(!ol_length);
  31. ol_list = tmp;
  32. ol_tail = tmp;
  33. ol_length++;
  34. return 0;
  35. }
  36. assert(ol_list);
  37. assert(!ol_tail->next);
  38. if(ol_length >= options.MaxOnionsPending) {
  39. log(LOG_INFO,"onion_pending_add(): Already have %d onions queued. Closing.", ol_length);
  40. free(tmp);
  41. return -1;
  42. }
  43. ol_length++;
  44. ol_tail->next = tmp;
  45. ol_tail = tmp;
  46. return 0;
  47. }
  48. int onion_pending_check(void) {
  49. if(ol_list)
  50. return 1;
  51. else
  52. return 0;
  53. }
  54. void onion_pending_process_one(void) {
  55. struct relay_queue_t *tmpd;
  56. circuit_t *circ;
  57. if(!ol_list)
  58. return; /* no onions pending, we're done */
  59. assert(ol_list->circ);
  60. if(!ol_list->circ->p_conn) {
  61. log(LOG_INFO,"onion_pending_process_one(): ol_list->circ->p_conn null, must have died?");
  62. onion_pending_remove(ol_list->circ);
  63. return; /* it died on us */
  64. }
  65. assert(ol_length > 0);
  66. circ = ol_list->circ;
  67. if(onionskin_process(circ) < 0) {
  68. log(LOG_DEBUG,"onion_pending_process_one(): Failed. Closing.");
  69. onion_pending_remove(circ);
  70. circuit_close(circ);
  71. } else {
  72. log(LOG_DEBUG,"onion_pending_process_one(): Succeeded. Delivering queued relay cells.");
  73. for(tmpd = ol_list->relay_cells; tmpd; tmpd=tmpd->next) {
  74. log(LOG_DEBUG,"onion_pending_process_one(): Delivering relay cell...");
  75. command_process_relay_cell(tmpd->cell, circ->p_conn);
  76. }
  77. onion_pending_remove(circ);
  78. }
  79. return;
  80. }
  81. /* go through ol_list, find the onion_queue_t element which points to
  82. * circ, remove and free that element. leave circ itself alone.
  83. */
  84. void onion_pending_remove(circuit_t *circ) {
  85. struct onion_queue_t *tmpo, *victim;
  86. struct relay_queue_t *tmpd;
  87. if(!ol_list)
  88. return; /* nothing here. */
  89. /* first check to see if it's the first entry */
  90. tmpo = ol_list;
  91. if(tmpo->circ == circ) {
  92. /* it's the first one. remove it from the list. */
  93. ol_list = tmpo->next;
  94. if(!ol_list)
  95. ol_tail = NULL;
  96. ol_length--;
  97. victim = tmpo;
  98. } else { /* we need to hunt through the rest of the list */
  99. for( ;tmpo->next && tmpo->next->circ != circ; tmpo=tmpo->next) ;
  100. if(!tmpo->next) {
  101. log(LOG_WARNING,"onion_pending_remove(): circ (p_aci %d), not in list!",circ->p_aci);
  102. return;
  103. }
  104. /* now we know tmpo->next->circ == circ */
  105. victim = tmpo->next;
  106. tmpo->next = victim->next;
  107. if(ol_tail == victim)
  108. ol_tail = tmpo;
  109. ol_length--;
  110. }
  111. /* now victim points to the element that needs to be removed */
  112. /* first dump the attached relay cells too, if any */
  113. while(victim->relay_cells) {
  114. tmpd = victim->relay_cells;
  115. victim->relay_cells = tmpd->next;
  116. free(tmpd->cell);
  117. free(tmpd);
  118. }
  119. free(victim);
  120. }
  121. struct relay_queue_t *relay_queue_add(struct relay_queue_t *list, cell_t *cell, crypt_path_t *layer_hint) {
  122. struct relay_queue_t *tmpd, *newd;
  123. newd = tor_malloc(sizeof(struct relay_queue_t));
  124. memset(newd, 0, sizeof(struct relay_queue_t));
  125. newd->cell = tor_malloc(sizeof(cell_t));
  126. memcpy(newd->cell, cell, sizeof(cell_t));
  127. newd->layer_hint = layer_hint;
  128. if(!list) {
  129. return newd;
  130. }
  131. for(tmpd = list; tmpd->next; tmpd=tmpd->next) ;
  132. /* now tmpd->next is null */
  133. tmpd->next = newd;
  134. return list;
  135. }
  136. /* a relay cell has arrived for a circuit which is still pending. Find
  137. * the right entry in ol_list, and add it to the end of the 'relay_cells'
  138. * list.
  139. */
  140. void onion_pending_relay_add(circuit_t *circ, cell_t *cell) {
  141. struct onion_queue_t *tmpo;
  142. for(tmpo=ol_list; tmpo; tmpo=tmpo->next) {
  143. if(tmpo->circ == circ) {
  144. tmpo->relay_cells = relay_queue_add(tmpo->relay_cells, cell, NULL);
  145. return;
  146. }
  147. }
  148. }
  149. /* learn keys, initialize, then send a created cell back */
  150. static int onionskin_process(circuit_t *circ) {
  151. unsigned char iv[16];
  152. unsigned char keys[32];
  153. cell_t cell;
  154. memset(iv, 0, 16);
  155. memset(&cell, 0, sizeof(cell_t));
  156. cell.command = CELL_CREATED;
  157. cell.aci = circ->p_aci;
  158. cell.length = DH_KEY_LEN;
  159. circ->state = CIRCUIT_STATE_OPEN;
  160. log(LOG_DEBUG,"onionskin_process(): Entering.");
  161. if(onion_skin_server_handshake(circ->onionskin, get_privatekey(),
  162. cell.payload, keys, 32) < 0) {
  163. log(LOG_ERR,"onionskin_process(): onion_skin_server_handshake failed.");
  164. return -1;
  165. }
  166. log(LOG_DEBUG,"onionskin_process: init cipher forward %d, backward %d.", *(int*)keys, *(int*)(keys+16));
  167. if (!(circ->n_crypto =
  168. crypto_create_init_cipher(DEFAULT_CIPHER,keys,iv,0))) {
  169. log(LOG_ERR,"Cipher initialization failed.");
  170. return -1;
  171. }
  172. if (!(circ->p_crypto =
  173. crypto_create_init_cipher(DEFAULT_CIPHER,keys+16,iv,1))) {
  174. log(LOG_ERR,"Cipher initialization failed.");
  175. return -1;
  176. }
  177. if(connection_write_cell_to_buf(&cell, circ->p_conn) < 0) {
  178. return -1;
  179. }
  180. log(LOG_DEBUG,"onionskin_process(): Finished sending 'created' cell.");
  181. return 0;
  182. }
  183. /* uses a weighted coin with weight cw to choose a route length */
  184. int chooselen(double cw)
  185. {
  186. int len = 2;
  187. uint8_t coin;
  188. if ((cw < 0) || (cw >= 1)) /* invalid parameter */
  189. return -1;
  190. while(1)
  191. {
  192. if (CRYPTO_PSEUDO_RAND_INT(coin))
  193. return -1;
  194. if (coin > cw*255) /* don't extend */
  195. break;
  196. else
  197. len++;
  198. }
  199. return len;
  200. }
  201. /* returns an array of pointers to routent that define a new route through the OR network
  202. * int cw is the coin weight to use when choosing the route
  203. * order of routers is from last to first
  204. */
  205. unsigned int *new_route(double cw, routerinfo_t **rarray, int rarray_len, int *routelen)
  206. {
  207. int i;
  208. int num_acceptable_routers;
  209. unsigned int *route;
  210. unsigned int oldchoice, choice;
  211. assert((cw >= 0) && (cw < 1) && (rarray) && (routelen) ); /* valid parameters */
  212. *routelen = chooselen(cw);
  213. if (*routelen == -1) {
  214. log(LOG_ERR,"Choosing route length failed.");
  215. return NULL;
  216. }
  217. log(LOG_DEBUG,"new_route(): Chosen route length %d.",*routelen);
  218. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  219. if(num_acceptable_routers < 2) {
  220. log(LOG_INFO,"new_route(): Not enough acceptable routers. Failing.");
  221. return NULL;
  222. }
  223. if(num_acceptable_routers < *routelen) {
  224. log(LOG_DEBUG,"new_route(): Cutting routelen from %d to %d.",*routelen, num_acceptable_routers);
  225. *routelen = num_acceptable_routers;
  226. }
  227. if(*routelen < 1) {
  228. log(LOG_ERR,"new_route(): Didn't find any acceptable routers. Failing.");
  229. return NULL;
  230. }
  231. /* allocate memory for the new route */
  232. route = (unsigned int *)tor_malloc(*routelen * sizeof(unsigned int));
  233. oldchoice = rarray_len;
  234. for(i=0;i<*routelen;i++) {
  235. log(LOG_DEBUG,"new_route(): Choosing hop %u.",i);
  236. if (CRYPTO_PSEUDO_RAND_INT(choice)) {
  237. free((void *)route);
  238. return NULL;
  239. }
  240. choice = choice % (rarray_len);
  241. log(LOG_DEBUG,"new_route(): Contemplating router %u.",choice);
  242. if(choice == oldchoice ||
  243. (oldchoice < rarray_len && !crypto_pk_cmp_keys(rarray[choice]->pkey, rarray[oldchoice]->pkey)) ||
  244. (options.ORPort && !connection_twin_get_by_addr_port(rarray[choice]->addr, rarray[choice]->or_port))) {
  245. /* Same router as last choice, or router twin,
  246. * or no routers with that key are connected to us.
  247. * Try again. */
  248. log(LOG_DEBUG,"new_route(): Picked a router %d that won't work as next hop.",choice);
  249. i--;
  250. continue;
  251. }
  252. log(LOG_DEBUG,"new_route(): Chosen router %u for hop %u.",choice,i);
  253. oldchoice = choice;
  254. route[i] = choice;
  255. }
  256. return route;
  257. }
  258. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  259. int i, j;
  260. int num=0;
  261. connection_t *conn;
  262. for(i=0;i<rarray_len;i++) {
  263. log(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  264. if(options.ORPort) {
  265. conn = connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port);
  266. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  267. log(LOG_DEBUG,"Nope, %d is not connected.",i);
  268. goto next_i_loop;
  269. }
  270. }
  271. for(j=0;j<i;j++) {
  272. if(!crypto_pk_cmp_keys(rarray[i]->pkey, rarray[j]->pkey)) {
  273. /* these guys are twins. so we've already counted him. */
  274. log(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  275. goto next_i_loop;
  276. }
  277. }
  278. num++;
  279. log(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  280. next_i_loop:
  281. ; /* our compiler may need an explicit statement after the label */
  282. }
  283. return num;
  284. }
  285. crypt_path_t *onion_generate_cpath(routerinfo_t **firsthop) {
  286. int routelen; /* length of the route */
  287. unsigned int *route; /* hops in the route as an array of indexes into rarray */
  288. crypt_path_t *cpath=NULL;
  289. directory_t *dir;
  290. routerinfo_t **rarray;
  291. int rarray_len;
  292. int i;
  293. crypt_path_t *hop;
  294. routerinfo_t *router;
  295. struct in_addr netaddr;
  296. router_get_directory(&dir);
  297. rarray = dir->routers;
  298. rarray_len = dir->n_routers;
  299. /* choose a route */
  300. route = new_route(options.CoinWeight, rarray, rarray_len, &routelen);
  301. if (!route) {
  302. log(LOG_ERR,"onion_generate_cpath(): Error choosing a route through the OR network.");
  303. return NULL;
  304. }
  305. log(LOG_DEBUG,"onion_generate_cpath(): Chosen a route of length %u: ",routelen);
  306. *firsthop = rarray[route[routelen-1]];
  307. assert(*firsthop); /* should always be defined */
  308. for(i=0; i<routelen; i++) {
  309. netaddr.s_addr = htonl((rarray[route[i]])->addr);
  310. log(LOG_DEBUG,"onion_generate_cpath(): %u : %s:%u, %u/%u",routelen-i,
  311. inet_ntoa(netaddr),
  312. (rarray[route[i]])->or_port,
  313. (rarray[route[i]])->pkey,
  314. crypto_pk_keysize((rarray[route[i]])->pkey));
  315. }
  316. /* create the cpath layer by layer, starting at the last hop */
  317. for (i=0;i<routelen;i++) {
  318. router = rarray[route[i]];
  319. /* build up the crypt_path */
  320. hop = (crypt_path_t *)tor_malloc(sizeof(crypt_path_t));
  321. memset(hop, 0, sizeof(crypt_path_t));
  322. /* link hop into the cpath, at the front */
  323. hop->next = cpath;
  324. hop->prev = NULL;
  325. hop->state = CPATH_STATE_CLOSED;
  326. if(cpath) {
  327. cpath->prev = hop;
  328. }
  329. cpath = hop;
  330. hop->port = rarray[route[i]]->or_port;
  331. hop->addr = rarray[route[i]]->addr;
  332. hop->package_window = CIRCWINDOW_START;
  333. hop->deliver_window = CIRCWINDOW_START;
  334. log(LOG_DEBUG,"onion_generate_cpath() : Building hop %u of crypt path.",i+1);
  335. }
  336. /* now link cpath->prev to the end of cpath */
  337. for(hop=cpath; hop->next; hop=hop->next) ;
  338. hop->next = cpath;
  339. cpath->prev = hop;
  340. free(route);
  341. return cpath;
  342. }
  343. /*----------------------------------------------------------------------*/
  344. /* Given a router's public key, generates a 144-byte encrypted DH pubkey,
  345. * and stores it into onion_skin out. Stores the DH private key into
  346. * handshake_state_out for later completion of the handshake.
  347. *
  348. * The encrypted pubkey is formed as follows:
  349. * 16 bytes of symmetric key
  350. * 128 bytes of g^x for DH.
  351. * The first 128 bytes are RSA-encrypted with the server's public key,
  352. * and the last 16 are encrypted with the symmetric key.
  353. */
  354. /* FIXME: Nick: looks like we could simplify this by just using 128 bytes for g^x. */
  355. int
  356. onion_skin_create(crypto_pk_env_t *dest_router_key,
  357. crypto_dh_env_t **handshake_state_out,
  358. char *onion_skin_out) /* Must be DH_ONIONSKIN_LEN bytes long */
  359. {
  360. char iv[16];
  361. char *pubkey = NULL;
  362. crypto_dh_env_t *dh = NULL;
  363. crypto_cipher_env_t *cipher = NULL;
  364. int dhbytes, pkbytes;
  365. *handshake_state_out = NULL;
  366. memset(onion_skin_out, 0, DH_ONIONSKIN_LEN);
  367. memset(iv, 0, 16);
  368. if (!(dh = crypto_dh_new()))
  369. goto err;
  370. dhbytes = crypto_dh_get_bytes(dh);
  371. pkbytes = crypto_pk_keysize(dest_router_key);
  372. assert(dhbytes+16 == DH_ONIONSKIN_LEN);
  373. pubkey = (char *)tor_malloc(dhbytes+16);
  374. if (crypto_rand(16, pubkey))
  375. goto err;
  376. /* XXXX You can't just run around RSA-encrypting any bitstream: if it's
  377. * greater than the RSA key, then OpenSSL will happily encrypt,
  378. * and later decrypt to the wrong value. So we set the first bit
  379. * of 'pubkey' to 0. This means that our symmetric key is really only
  380. * 127 bits long, but since it shouldn't be necessary to encrypt
  381. * DH public keys values in the first place, we should be fine.
  382. */
  383. pubkey[0] &= 0x7f;
  384. if (crypto_dh_get_public(dh, pubkey+16, dhbytes))
  385. goto err;
  386. #if 0
  387. printf("Client DH sent: %x %x %x ... %x %x %x\n",
  388. (int) pubkey[16], (int) pubkey[17], (int) pubkey[18],
  389. (int) pubkey[205], (int) pubkey[206], (int) pubkey[207]);
  390. printf("Client key sent: %x %x %x ... %x %x %x\n",
  391. pubkey[0],pubkey[1],pubkey[2],
  392. pubkey[13],pubkey[14],pubkey[15]);
  393. #endif
  394. cipher = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, pubkey, iv, 1);
  395. if (!cipher)
  396. goto err;
  397. if (crypto_pk_public_encrypt(dest_router_key, pubkey, pkbytes,
  398. onion_skin_out, RSA_NO_PADDING)==-1)
  399. goto err;
  400. if (crypto_cipher_encrypt(cipher, pubkey+pkbytes, dhbytes+16-pkbytes,
  401. onion_skin_out+pkbytes))
  402. goto err;
  403. free(pubkey);
  404. crypto_free_cipher_env(cipher);
  405. *handshake_state_out = dh;
  406. return 0;
  407. err:
  408. if (pubkey) free(pubkey);
  409. if (dh) crypto_dh_free(dh);
  410. if (cipher) crypto_free_cipher_env(cipher);
  411. return -1;
  412. }
  413. /* Given an encrypted DH public key as generated by onion_skin_create,
  414. * and the private key for this onion router, generate the 128-byte DH
  415. * reply, and key_out_len bytes of key material, stored in key_out.
  416. */
  417. int
  418. onion_skin_server_handshake(char *onion_skin, /* DH_ONIONSKIN_LEN bytes long */
  419. crypto_pk_env_t *private_key,
  420. char *handshake_reply_out, /* DH_KEY_LEN bytes long */
  421. char *key_out,
  422. int key_out_len)
  423. {
  424. char buf[DH_ONIONSKIN_LEN];
  425. char iv[16];
  426. crypto_dh_env_t *dh = NULL;
  427. crypto_cipher_env_t *cipher = NULL;
  428. int pkbytes;
  429. memset(iv, 0, 16);
  430. pkbytes = crypto_pk_keysize(private_key);
  431. if (crypto_pk_private_decrypt(private_key,
  432. onion_skin, pkbytes,
  433. buf, RSA_NO_PADDING) == -1)
  434. goto err;
  435. #if 0
  436. printf("Client key got: %x %x %x ... %x %x %x\n",
  437. buf[0],buf[1],buf[2], buf[13],buf[14],buf[15]);
  438. #endif
  439. cipher = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, buf, iv, 0);
  440. if (crypto_cipher_decrypt(cipher, onion_skin+pkbytes, DH_ONIONSKIN_LEN-pkbytes,
  441. buf+pkbytes))
  442. goto err;
  443. #if 0
  444. printf("Client DH got: %x %x %x ... %x %x %x\n",
  445. (int) buf[16], (int) buf[17], (int) buf[18],
  446. (int) buf[205], (int) buf[206], (int) buf[207]);
  447. #endif
  448. dh = crypto_dh_new();
  449. if (crypto_dh_get_public(dh, handshake_reply_out, DH_KEY_LEN))
  450. goto err;
  451. if (crypto_dh_compute_secret(dh, buf+16, DH_KEY_LEN, buf))
  452. goto err;
  453. memcpy(key_out, buf+DH_KEY_LEN-key_out_len, key_out_len);
  454. crypto_free_cipher_env(cipher);
  455. crypto_dh_free(dh);
  456. return 0;
  457. err:
  458. if (cipher) crypto_free_cipher_env(cipher);
  459. if (dh) crypto_dh_free(dh);
  460. return -1;
  461. }
  462. /* Finish the client side of the DH handshake.
  463. * Given the 128 byte DH reply as generated by onion_skin_server_handshake
  464. * and the handshake state generated by onion_skin_create, generate
  465. * key_out_len bytes of shared key material and store them in key_out.
  466. *
  467. * After the invocation, call crypto_dh_free on handshake_state.
  468. */
  469. int
  470. onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
  471. char *handshake_reply,/* Must be DH_KEY_LEN bytes long*/
  472. char *key_out,
  473. int key_out_len)
  474. {
  475. char key_material[DH_KEY_LEN];
  476. assert(crypto_dh_get_bytes(handshake_state) == DH_KEY_LEN);
  477. memset(key_material, 0, DH_KEY_LEN);
  478. if (crypto_dh_compute_secret(handshake_state, handshake_reply, DH_KEY_LEN,
  479. key_material))
  480. return -1;
  481. memcpy(key_out, key_material+DH_KEY_LEN-key_out_len, key_out_len);
  482. return 0;
  483. }
  484. /*
  485. Local Variables:
  486. mode:c
  487. indent-tabs-mode:nil
  488. c-basic-offset:2
  489. End:
  490. */