onion.c 15 KB

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