onion.c 15 KB

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