onion.c 15 KB

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