onion.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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(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_WARN,"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_circ_id %d) not in list, probably at cpuworker.",circ->p_circ_id);
  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.circ_id = circ->p_circ_id;
  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_WARN,"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_WARN,"Cipher initialization failed (p).");
  119. return -1;
  120. }
  121. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  122. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  123. return 0;
  124. }
  125. /* uses a weighted coin with weight cw to choose a route length */
  126. static int chooselen(double cw) {
  127. int len = 2;
  128. uint8_t coin;
  129. if ((cw < 0) || (cw >= 1)) /* invalid parameter */
  130. return -1;
  131. while(1)
  132. {
  133. if (CRYPTO_PSEUDO_RAND_INT(coin))
  134. return -1;
  135. if (coin > cw*255) /* don't extend */
  136. break;
  137. else
  138. len++;
  139. }
  140. return len;
  141. }
  142. static int new_route_len(double cw, routerinfo_t **rarray, int rarray_len) {
  143. int num_acceptable_routers;
  144. int routelen;
  145. assert((cw >= 0) && (cw < 1) && (rarray) ); /* valid parameters */
  146. routelen = chooselen(cw);
  147. if (routelen == -1) {
  148. log_fn(LOG_WARN,"Choosing route length failed.");
  149. return -1;
  150. }
  151. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen, rarray_len);
  152. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  153. if(num_acceptable_routers < 2) {
  154. log_fn(LOG_INFO,"Not enough acceptable routers. Failing.");
  155. return -1;
  156. }
  157. if(num_acceptable_routers < routelen) {
  158. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",routelen, num_acceptable_routers);
  159. routelen = num_acceptable_routers;
  160. }
  161. if (routelen < 1) {
  162. log_fn(LOG_WARN,"Didn't find any acceptable routers. Failing.");
  163. return -1;
  164. }
  165. return routelen;
  166. }
  167. int onion_new_route_len(void) {
  168. directory_t *dir;
  169. router_get_directory(&dir);
  170. return new_route_len(options.CoinWeight, dir->routers, dir->n_routers);
  171. }
  172. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  173. int i, j;
  174. int num=0;
  175. connection_t *conn;
  176. for(i=0;i<rarray_len;i++) {
  177. log_fn(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  178. if(options.OnionRouter) {
  179. conn = connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port);
  180. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  181. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  182. goto next_i_loop;
  183. }
  184. }
  185. for(j=0;j<i;j++) {
  186. if(!crypto_pk_cmp_keys(rarray[i]->onion_pkey, rarray[j]->onion_pkey)) {
  187. /* these guys are twins. so we've already counted him. */
  188. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  189. goto next_i_loop;
  190. }
  191. }
  192. num++;
  193. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  194. next_i_loop:
  195. ; /* our compiler may need an explicit statement after the label */
  196. }
  197. return num;
  198. }
  199. /* XXX This function should be replaced by calls to onion_extend_cpath */
  200. crypt_path_t *onion_generate_cpath(routerinfo_t **firsthop) {
  201. int routelen;
  202. crypt_path_t *cpath=NULL;
  203. int r;
  204. directory_t *dir;
  205. routerinfo_t **rarray;
  206. int rarray_len;
  207. assert(firsthop);
  208. *firsthop = NULL;
  209. router_get_directory(&dir);
  210. rarray = dir->routers;
  211. rarray_len = dir->n_routers;
  212. routelen = new_route_len(options.CoinWeight, rarray, rarray_len);
  213. if (routelen < 0) return NULL;
  214. while (1) {
  215. r = onion_extend_cpath(&cpath, routelen, cpath ? NULL : firsthop);
  216. if (r < 0) {
  217. if (cpath) circuit_free_cpath(cpath);
  218. return NULL;
  219. } else if (r == 1) {
  220. break;
  221. }
  222. /* r == 0; keep on chugging. */
  223. }
  224. return cpath;
  225. }
  226. int onion_extend_cpath(crypt_path_t **head_ptr, int path_len, routerinfo_t **router_out)
  227. {
  228. int cur_len;
  229. crypt_path_t *cpath, *hop;
  230. routerinfo_t **rarray, *r;
  231. unsigned int choice;
  232. int rarray_len;
  233. int i;
  234. directory_t *dir;
  235. assert(head_ptr);
  236. if (router_out)
  237. *router_out = NULL;
  238. router_get_directory(&dir);
  239. rarray = dir->routers;
  240. rarray_len = dir->n_routers;
  241. if (!*head_ptr) {
  242. cur_len = 0;
  243. } else {
  244. cur_len = 1;
  245. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  246. ++cur_len;
  247. }
  248. }
  249. if (cur_len >= path_len) { return 1; }
  250. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len, path_len);
  251. again:
  252. if (CRYPTO_PSEUDO_RAND_INT(choice)) {
  253. return -1;
  254. }
  255. choice %= rarray_len;
  256. log_fn(LOG_DEBUG,"Contemplating router %s for hop %d",
  257. rarray[choice]->nickname, cur_len);
  258. for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
  259. r = router_get_by_addr_port(cpath->addr, cpath->port);
  260. if ((r && !crypto_pk_cmp_keys(r->onion_pkey, rarray[choice]->onion_pkey))
  261. || (cpath->addr == rarray[choice]->addr &&
  262. cpath->port == rarray[choice]->or_port)
  263. || (options.OnionRouter &&
  264. !(connection_twin_get_by_addr_port(rarray[choice]->addr,
  265. rarray[choice]->or_port)))) {
  266. log_fn(LOG_DEBUG, "Picked an already-selected router for hop %d; retrying.",
  267. cur_len);
  268. goto again;
  269. }
  270. }
  271. /* Okay, so we haven't used 'choice' before. */
  272. hop = (crypt_path_t *)tor_malloc(sizeof(crypt_path_t));
  273. memset(hop, 0, sizeof(crypt_path_t));
  274. /* link hop into the cpath, at the end. */
  275. if (*head_ptr) {
  276. hop->next = (*head_ptr);
  277. hop->prev = (*head_ptr)->prev;
  278. (*head_ptr)->prev->next = hop;
  279. (*head_ptr)->prev = hop;
  280. } else {
  281. *head_ptr = hop;
  282. hop->prev = hop->next = hop;
  283. }
  284. hop->state = CPATH_STATE_CLOSED;
  285. hop->port = rarray[choice]->or_port;
  286. hop->addr = rarray[choice]->addr;
  287. hop->package_window = CIRCWINDOW_START;
  288. hop->deliver_window = CIRCWINDOW_START;
  289. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  290. rarray[choice]->nickname, cur_len);
  291. if (router_out)
  292. *router_out = rarray[choice];
  293. return 0;
  294. }
  295. /*----------------------------------------------------------------------*/
  296. /* Given a router's public key, generates a 144-byte encrypted DH pubkey,
  297. * and stores it into onion_skin out. Stores the DH private key into
  298. * handshake_state_out for later completion of the handshake.
  299. *
  300. * The encrypted pubkey is formed as follows:
  301. * 16 bytes of symmetric key
  302. * 128 bytes of g^x for DH.
  303. * The first 128 bytes are RSA-encrypted with the server's public key,
  304. * and the last 16 are encrypted with the symmetric key.
  305. */
  306. int
  307. onion_skin_create(crypto_pk_env_t *dest_router_key,
  308. crypto_dh_env_t **handshake_state_out,
  309. char *onion_skin_out) /* Must be DH_ONIONSKIN_LEN bytes long */
  310. {
  311. char iv[16];
  312. char *pubkey = NULL;
  313. crypto_dh_env_t *dh = NULL;
  314. crypto_cipher_env_t *cipher = NULL;
  315. int dhbytes, pkbytes;
  316. *handshake_state_out = NULL;
  317. memset(onion_skin_out, 0, DH_ONIONSKIN_LEN);
  318. memset(iv, 0, 16);
  319. if (!(dh = crypto_dh_new()))
  320. goto err;
  321. dhbytes = crypto_dh_get_bytes(dh);
  322. pkbytes = crypto_pk_keysize(dest_router_key);
  323. assert(dhbytes+16 == DH_ONIONSKIN_LEN);
  324. pubkey = (char *)tor_malloc(dhbytes+16);
  325. if (crypto_rand(16, pubkey))
  326. goto err;
  327. /* XXXX You can't just run around RSA-encrypting any bitstream: if it's
  328. * greater than the RSA key, then OpenSSL will happily encrypt,
  329. * and later decrypt to the wrong value. So we set the first bit
  330. * of 'pubkey' to 0. This means that our symmetric key is really only
  331. * 127 bits long, but since it shouldn't be necessary to encrypt
  332. * DH public keys values in the first place, we should be fine.
  333. */
  334. pubkey[0] &= 0x7f;
  335. if (crypto_dh_get_public(dh, pubkey+16, dhbytes))
  336. goto err;
  337. #ifdef DEBUG_ONION_SKINS
  338. #define PA(a,n) \
  339. { int _i; for (_i = 0; _i<n; ++_i) printf("%02x ",((int)(a)[_i])&0xFF); }
  340. printf("Client: client g^x:");
  341. PA(pubkey+16,3);
  342. printf("...");
  343. PA(pubkey+141,3);
  344. puts("");
  345. printf("Client: client symkey:");
  346. PA(pubkey+0,16);
  347. puts("");
  348. #endif
  349. cipher = crypto_create_init_cipher(ONION_CIPHER, pubkey, iv, 1);
  350. if (!cipher)
  351. goto err;
  352. if (crypto_pk_public_encrypt(dest_router_key, pubkey, pkbytes,
  353. onion_skin_out, RSA_NO_PADDING)==-1)
  354. goto err;
  355. if (crypto_cipher_encrypt(cipher, pubkey+pkbytes, dhbytes+16-pkbytes,
  356. onion_skin_out+pkbytes))
  357. goto err;
  358. free(pubkey);
  359. crypto_free_cipher_env(cipher);
  360. *handshake_state_out = dh;
  361. return 0;
  362. err:
  363. tor_free(pubkey);
  364. if (dh) crypto_dh_free(dh);
  365. if (cipher) crypto_free_cipher_env(cipher);
  366. return -1;
  367. }
  368. /* Given an encrypted DH public key as generated by onion_skin_create,
  369. * and the private key for this onion router, generate the 128-byte DH
  370. * reply, and key_out_len bytes of key material, stored in key_out.
  371. */
  372. int
  373. onion_skin_server_handshake(char *onion_skin, /* DH_ONIONSKIN_LEN bytes long */
  374. crypto_pk_env_t *private_key,
  375. char *handshake_reply_out, /* DH_KEY_LEN bytes long */
  376. char *key_out,
  377. int key_out_len)
  378. {
  379. char buf[DH_ONIONSKIN_LEN];
  380. char iv[16];
  381. crypto_dh_env_t *dh = NULL;
  382. crypto_cipher_env_t *cipher = NULL;
  383. int pkbytes;
  384. int len;
  385. memset(iv, 0, 16);
  386. pkbytes = crypto_pk_keysize(private_key);
  387. if (crypto_pk_private_decrypt(private_key,
  388. onion_skin, pkbytes,
  389. buf, RSA_NO_PADDING) == -1)
  390. goto err;
  391. #ifdef DEBUG_ONION_SKINS
  392. printf("Server: client symkey:");
  393. PA(buf+0,16);
  394. puts("");
  395. #endif
  396. cipher = crypto_create_init_cipher(ONION_CIPHER, buf, iv, 0);
  397. if (crypto_cipher_decrypt(cipher, onion_skin+pkbytes, DH_ONIONSKIN_LEN-pkbytes,
  398. buf+pkbytes))
  399. goto err;
  400. #ifdef DEBUG_ONION_SKINS
  401. printf("Server: client g^x:");
  402. PA(buf+16,3);
  403. printf("...");
  404. PA(buf+141,3);
  405. puts("");
  406. #endif
  407. dh = crypto_dh_new();
  408. if (crypto_dh_get_public(dh, handshake_reply_out, DH_KEY_LEN))
  409. goto err;
  410. #ifdef DEBUG_ONION_SKINS
  411. printf("Server: server g^y:");
  412. PA(handshake_reply_out+0,3);
  413. printf("...");
  414. PA(handshake_reply_out+125,3);
  415. puts("");
  416. #endif
  417. len = crypto_dh_compute_secret(dh, buf+16, DH_KEY_LEN, key_out, key_out_len);
  418. if (len < 0)
  419. goto err;
  420. #ifdef DEBUG_ONION_SKINS
  421. printf("Server: key material:");
  422. PA(buf, DH_KEY_LEN);
  423. puts("");
  424. printf("Server: keys out:");
  425. PA(key_out, key_out_len);
  426. puts("");
  427. #endif
  428. crypto_free_cipher_env(cipher);
  429. crypto_dh_free(dh);
  430. return 0;
  431. err:
  432. if (cipher) crypto_free_cipher_env(cipher);
  433. if (dh) crypto_dh_free(dh);
  434. return -1;
  435. }
  436. /* Finish the client side of the DH handshake.
  437. * Given the 128 byte DH reply as generated by onion_skin_server_handshake
  438. * and the handshake state generated by onion_skin_create, generate
  439. * key_out_len bytes of shared key material and store them in key_out.
  440. *
  441. * After the invocation, call crypto_dh_free on handshake_state.
  442. */
  443. int
  444. onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
  445. char *handshake_reply,/* Must be DH_KEY_LEN bytes long*/
  446. char *key_out,
  447. int key_out_len)
  448. {
  449. int len;
  450. assert(crypto_dh_get_bytes(handshake_state) == DH_KEY_LEN);
  451. #ifdef DEBUG_ONION_SKINS
  452. printf("Client: server g^y:");
  453. PA(handshake_reply+0,3);
  454. printf("...");
  455. PA(handshake_reply+125,3);
  456. puts("");
  457. #endif
  458. len = crypto_dh_compute_secret(handshake_state, handshake_reply, DH_KEY_LEN,
  459. key_out, key_out_len);
  460. if (len < 0)
  461. return -1;
  462. #ifdef DEBUG_ONION_SKINS
  463. printf("Client: keys out:");
  464. PA(key_out, key_out_len);
  465. puts("");
  466. #endif
  467. return 0;
  468. }
  469. /*
  470. Local Variables:
  471. mode:c
  472. indent-tabs-mode:nil
  473. c-basic-offset:2
  474. End:
  475. */