onion.c 16 KB

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