circuitbuild.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. /* Copyright 2001 Matej Pfajfar, 2001-2004 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file circuitbuild.c
  6. * \brief The actual details of building circuits.
  7. **/
  8. #include "or.h"
  9. extern or_options_t options; /* command-line and config-file options */
  10. /********* START VARIABLES **********/
  11. /** A global list of all circuits at this hop. */
  12. extern circuit_t *global_circuitlist;
  13. /********* END VARIABLES ************/
  14. static cpath_build_state_t *
  15. onion_new_cpath_build_state(uint8_t purpose, const char *exit_nickname);
  16. static int
  17. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  18. *state, routerinfo_t **router_out);
  19. static int decide_circ_id_type(char *local_nick, char *remote_nick);
  20. static int count_acceptable_routers(smartlist_t *routers);
  21. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  22. * and with the high bit specified by circ_id_type (see
  23. * decide_circ_id_type()), until we get a circ_id that is not in use
  24. * by any other circuit on that conn.
  25. *
  26. * Return it, or 0 if can't get a unique circ_id.
  27. */
  28. static uint16_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
  29. uint16_t test_circ_id;
  30. int attempts=0;
  31. uint16_t high_bit;
  32. tor_assert(conn && conn->type == CONN_TYPE_OR);
  33. high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  34. do {
  35. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  36. * circID such that (high_bit|test_circ_id) is not already used. */
  37. test_circ_id = conn->next_circ_id++;
  38. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  39. test_circ_id = 1;
  40. conn->next_circ_id = 2;
  41. }
  42. if(++attempts > 1<<15) {
  43. /* Make sure we don't loop forever if all circ_id's are used. This
  44. * matters because it's an external DoS vulnerability.
  45. */
  46. log_fn(LOG_WARN,"No unused circ IDs. Failing.");
  47. return 0;
  48. }
  49. test_circ_id |= high_bit;
  50. } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
  51. return test_circ_id;
  52. }
  53. /** Log, at severity <b>severity</b>, the nicknames of each router in
  54. * circ's cpath. Also log the length of the cpath, and the intended
  55. * exit point.
  56. */
  57. void circuit_log_path(int severity, circuit_t *circ) {
  58. char buf[1024];
  59. char *s = buf;
  60. struct crypt_path_t *hop;
  61. char *states[] = {"closed", "waiting for keys", "open"};
  62. routerinfo_t *router;
  63. tor_assert(CIRCUIT_IS_ORIGIN(circ) && circ->cpath);
  64. snprintf(s, sizeof(buf)-1, "circ (length %d, exit %s): ",
  65. circ->build_state->desired_path_len, circ->build_state->chosen_exit);
  66. hop=circ->cpath;
  67. do {
  68. s = buf + strlen(buf);
  69. router = router_get_by_addr_port(hop->addr,hop->port);
  70. if(router) {
  71. snprintf(s, sizeof(buf) - (s - buf), "%s(%s) ",
  72. router->nickname, states[hop->state]);
  73. } else {
  74. if(circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  75. snprintf(s, sizeof(buf) - (s - buf), "(rendjoin hop)");
  76. } else {
  77. snprintf(s, sizeof(buf) - (s - buf), "UNKNOWN ");
  78. }
  79. }
  80. hop=hop->next;
  81. } while(hop!=circ->cpath);
  82. log_fn(severity,"%s",buf);
  83. }
  84. /** Tell the rep(utation)hist(ory) module about the status of the links
  85. * in circ. Hops that have become OPEN are marked as successfully
  86. * extended; the _first_ hop that isn't open (if any) is marked as
  87. * unable to extend.
  88. */
  89. void circuit_rep_hist_note_result(circuit_t *circ) {
  90. struct crypt_path_t *hop;
  91. char *prev_nickname = NULL;
  92. routerinfo_t *router;
  93. hop = circ->cpath;
  94. if(!hop) {
  95. /* XXX
  96. * if !hop, then we're not the beginning of this circuit.
  97. * for now, just forget about it. later, we should remember when
  98. * extends-through-us failed, too.
  99. */
  100. return;
  101. }
  102. if (options.ORPort) {
  103. prev_nickname = options.Nickname;
  104. }
  105. do {
  106. router = router_get_by_addr_port(hop->addr,hop->port);
  107. if (router) {
  108. if (prev_nickname) {
  109. if (hop->state == CPATH_STATE_OPEN)
  110. rep_hist_note_extend_succeeded(prev_nickname, router->nickname);
  111. else {
  112. rep_hist_note_extend_failed(prev_nickname, router->nickname);
  113. break;
  114. }
  115. }
  116. prev_nickname = router->nickname;
  117. } else {
  118. prev_nickname = NULL;
  119. }
  120. hop=hop->next;
  121. } while (hop!=circ->cpath);
  122. }
  123. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  124. * of information about circuit <b>circ</b>.
  125. */
  126. static void
  127. circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  128. char *type, int this_circid, int other_circid) {
  129. struct crypt_path_t *hop;
  130. log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
  131. poll_index, type, this_circid, other_circid, circ->state,
  132. circuit_state_to_string[circ->state], (int)circ->timestamp_created);
  133. if(CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  134. if(circ->state == CIRCUIT_STATE_BUILDING)
  135. log(severity,"Building: desired len %d, planned exit node %s.",
  136. circ->build_state->desired_path_len, circ->build_state->chosen_exit);
  137. for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
  138. log(severity,"hop: state %d, addr 0x%.8x, port %d", hop->state,
  139. (unsigned int)hop->addr,
  140. (int)hop->port);
  141. }
  142. }
  143. /** Log, at severity <b>severity</b>, information about each circuit
  144. * that is connected to <b>conn</b>.
  145. */
  146. void circuit_dump_by_conn(connection_t *conn, int severity) {
  147. circuit_t *circ;
  148. connection_t *tmpconn;
  149. for(circ=global_circuitlist;circ;circ = circ->next) {
  150. if(circ->p_conn == conn)
  151. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  152. circ->p_circ_id, circ->n_circ_id);
  153. for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  154. if(tmpconn == conn) {
  155. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  156. circ->p_circ_id, circ->n_circ_id);
  157. }
  158. }
  159. if(circ->n_conn == conn)
  160. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  161. circ->n_circ_id, circ->p_circ_id);
  162. for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  163. if(tmpconn == conn) {
  164. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  165. circ->n_circ_id, circ->p_circ_id);
  166. }
  167. }
  168. }
  169. }
  170. /** Build a new circuit for <b>purpose</b>. If <b>exit_nickname</b>
  171. * is defined, then use that as your exit router, else choose a suitable
  172. * exit node.
  173. *
  174. * Also launch a connection to the first OR in the chosen path, if
  175. * it's not open already.
  176. */
  177. circuit_t *circuit_establish_circuit(uint8_t purpose,
  178. const char *exit_nickname) {
  179. routerinfo_t *firsthop;
  180. connection_t *n_conn;
  181. circuit_t *circ;
  182. circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  183. circ->state = CIRCUIT_STATE_OR_WAIT;
  184. circ->build_state = onion_new_cpath_build_state(purpose, exit_nickname);
  185. circ->purpose = purpose;
  186. if (! circ->build_state) {
  187. log_fn(LOG_INFO,"Generating cpath failed.");
  188. circuit_mark_for_close(circ);
  189. return NULL;
  190. }
  191. onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
  192. if(!CIRCUIT_IS_ORIGIN(circ)) {
  193. log_fn(LOG_INFO,"Generating first cpath hop failed.");
  194. circuit_mark_for_close(circ);
  195. return NULL;
  196. }
  197. /* now see if we're already connected to the first OR in 'route' */
  198. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  199. firsthop->address,firsthop->or_port);
  200. n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
  201. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  202. circ->n_addr = firsthop->addr;
  203. circ->n_port = firsthop->or_port;
  204. if(!n_conn) { /* launch the connection */
  205. n_conn = connection_or_connect(firsthop);
  206. if(!n_conn) { /* connect failed, forget the whole thing */
  207. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  208. circuit_mark_for_close(circ);
  209. return NULL;
  210. }
  211. }
  212. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  213. /* return success. The onion/circuit/etc will be taken care of automatically
  214. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  215. */
  216. return circ;
  217. } else { /* it (or a twin) is already open. use it. */
  218. circ->n_addr = n_conn->addr;
  219. circ->n_port = n_conn->port;
  220. circ->n_conn = n_conn;
  221. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  222. if(circuit_send_next_onion_skin(circ) < 0) {
  223. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  224. circuit_mark_for_close(circ);
  225. return NULL;
  226. }
  227. }
  228. return circ;
  229. }
  230. /** Find circuits that are waiting on <b>or_conn</b> to become open,
  231. * if any, and get them to send their create cells forward.
  232. */
  233. void circuit_n_conn_open(connection_t *or_conn) {
  234. circuit_t *circ;
  235. for(circ=global_circuitlist;circ;circ = circ->next) {
  236. if (circ->marked_for_close)
  237. continue;
  238. if(CIRCUIT_IS_ORIGIN(circ) && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
  239. tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  240. log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
  241. circ->n_conn = or_conn;
  242. if(circuit_send_next_onion_skin(circ) < 0) {
  243. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  244. circuit_mark_for_close(circ);
  245. continue;
  246. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  247. }
  248. }
  249. }
  250. }
  251. extern int has_completed_circuit;
  252. /** This is the backbone function for building circuits.
  253. *
  254. * If circ's first hop is closed, then we need to build a create
  255. * cell and send it forward.
  256. *
  257. * Otherwise, we need to build a relay extend cell and send it
  258. * forward.
  259. *
  260. * Return -1 if we want to tear down circ, else return 0.
  261. */
  262. int circuit_send_next_onion_skin(circuit_t *circ) {
  263. cell_t cell;
  264. crypt_path_t *hop;
  265. routerinfo_t *router;
  266. int r;
  267. int circ_id_type;
  268. char payload[2+4+ONIONSKIN_CHALLENGE_LEN];
  269. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  270. if(circ->cpath->state == CPATH_STATE_CLOSED) {
  271. tor_assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
  272. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  273. circ_id_type = decide_circ_id_type(options.Nickname,
  274. circ->n_conn->nickname);
  275. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  276. memset(&cell, 0, sizeof(cell_t));
  277. cell.command = CELL_CREATE;
  278. cell.circ_id = circ->n_circ_id;
  279. router = router_get_by_nickname(circ->n_conn->nickname);
  280. if (!router) {
  281. log_fn(LOG_WARN,"Couldn't find routerinfo for %s",
  282. circ->n_conn->nickname);
  283. return -1;
  284. }
  285. if(onion_skin_create(router->onion_pkey,
  286. &(circ->cpath->handshake_state),
  287. cell.payload) < 0) {
  288. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  289. return -1;
  290. }
  291. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  292. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  293. circ->state = CIRCUIT_STATE_BUILDING;
  294. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  295. } else {
  296. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  297. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  298. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  299. r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
  300. if (r==1) {
  301. /* done building the circuit. whew. */
  302. circ->state = CIRCUIT_STATE_OPEN;
  303. log_fn(LOG_INFO,"circuit built!");
  304. circuit_reset_failure_count();
  305. if(!has_completed_circuit) {
  306. has_completed_circuit=1;
  307. log_fn(LOG_NOTICE,"Tor has successfully opened a circuit. Looks like it's working.");
  308. }
  309. circuit_rep_hist_note_result(circ);
  310. circuit_has_opened(circ); /* do other actions as necessary */
  311. return 0;
  312. } else if (r<0) {
  313. log_fn(LOG_INFO,"Unable to extend circuit path.");
  314. return -1;
  315. }
  316. hop = circ->cpath->prev;
  317. *(uint32_t*)payload = htonl(hop->addr);
  318. *(uint16_t*)(payload+4) = htons(hop->port);
  319. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), payload+6) < 0) {
  320. log_fn(LOG_WARN,"onion_skin_create failed.");
  321. return -1;
  322. }
  323. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  324. /* send it to hop->prev, because it will transfer
  325. * it to a create cell and then send to hop */
  326. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  327. payload, sizeof(payload), hop->prev) < 0)
  328. return 0; /* circuit is closed */
  329. hop->state = CPATH_STATE_AWAITING_KEYS;
  330. }
  331. return 0;
  332. }
  333. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  334. * sure we're connected to the next hop, and pass it the onion skin in
  335. * a create cell.
  336. */
  337. int circuit_extend(cell_t *cell, circuit_t *circ) {
  338. connection_t *n_conn;
  339. int circ_id_type;
  340. cell_t newcell;
  341. if(circ->n_conn) {
  342. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  343. return -1;
  344. }
  345. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  346. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  347. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  348. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  349. /* I've disabled making connections through OPs, but it's definitely
  350. * possible here. I'm not sure if it would be a bug or a feature.
  351. *
  352. * Note also that this will close circuits where the onion has the same
  353. * router twice in a row in the path. I think that's ok.
  354. */
  355. struct in_addr in;
  356. in.s_addr = htonl(circ->n_addr);
  357. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
  358. #if 0 /* if we do truncateds, no need to kill circ */
  359. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  360. NULL, 0, NULL);
  361. return 0;
  362. #endif
  363. circuit_mark_for_close(circ);
  364. return 0;
  365. }
  366. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  367. circ->n_port = n_conn->port;
  368. circ->n_conn = n_conn;
  369. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  370. circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
  371. // log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
  372. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  373. if(!circ->n_circ_id) {
  374. log_fn(LOG_WARN,"failed to get unique circID.");
  375. return -1;
  376. }
  377. log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
  378. memset(&newcell, 0, sizeof(cell_t));
  379. newcell.command = CELL_CREATE;
  380. newcell.circ_id = circ->n_circ_id;
  381. memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+2+4,
  382. ONIONSKIN_CHALLENGE_LEN);
  383. connection_or_write_cell_to_buf(&newcell, circ->n_conn);
  384. return 0;
  385. }
  386. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  387. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  388. * used as follows:
  389. * - 20 to initialize f_digest
  390. * - 20 to initialize b_digest
  391. * - 16 to key f_crypto
  392. * - 16 to key b_crypto
  393. *
  394. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  395. */
  396. int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  397. {
  398. crypto_digest_env_t *tmp_digest;
  399. crypto_cipher_env_t *tmp_crypto;
  400. tor_assert(cpath && key_data);
  401. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  402. cpath->f_digest || cpath->b_digest));
  403. log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  404. (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  405. cpath->f_digest = crypto_new_digest_env();
  406. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  407. cpath->b_digest = crypto_new_digest_env();
  408. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  409. log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  410. (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  411. if (!(cpath->f_crypto =
  412. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  413. log(LOG_WARN,"forward cipher initialization failed.");
  414. return -1;
  415. }
  416. if (!(cpath->b_crypto =
  417. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  418. log(LOG_WARN,"backward cipher initialization failed.");
  419. return -1;
  420. }
  421. if (reverse) {
  422. tmp_digest = cpath->f_digest;
  423. cpath->f_digest = cpath->b_digest;
  424. cpath->b_digest = tmp_digest;
  425. tmp_crypto = cpath->f_crypto;
  426. cpath->f_crypto = cpath->b_crypto;
  427. cpath->b_crypto = tmp_crypto;
  428. }
  429. return 0;
  430. }
  431. /** A created or extended cell came back to us on the circuit,
  432. * and it included <b>reply</b> (the second DH key, plus KH).
  433. *
  434. * Calculate the appropriate keys and digests, make sure KH is
  435. * correct, and initialize this hop of the cpath.
  436. *
  437. * Return -1 if we want to mark circ for close, else return 0.
  438. */
  439. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  440. unsigned char keys[CPATH_KEY_MATERIAL_LEN];
  441. crypt_path_t *hop;
  442. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  443. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  444. hop = circ->cpath;
  445. else {
  446. for(hop=circ->cpath->next;
  447. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  448. hop=hop->next) ;
  449. if(hop == circ->cpath) { /* got an extended when we're all done? */
  450. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  451. return -1;
  452. }
  453. }
  454. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  455. if(onion_skin_client_handshake(hop->handshake_state, reply, keys,
  456. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  457. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  458. return -1;
  459. }
  460. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  461. hop->handshake_state = NULL;
  462. /* Remember hash of g^xy */
  463. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  464. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  465. return -1;
  466. }
  467. hop->state = CPATH_STATE_OPEN;
  468. log_fn(LOG_INFO,"finished");
  469. circuit_log_path(LOG_INFO,circ);
  470. return 0;
  471. }
  472. /** We received a relay truncated cell on circ.
  473. *
  474. * Since we don't ask for truncates currently, getting a truncated
  475. * means that a connection broke or an extend failed. For now,
  476. * just give up: for circ to close, and return 0.
  477. */
  478. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  479. crypt_path_t *victim;
  480. connection_t *stream;
  481. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  482. tor_assert(layer);
  483. /* XXX Since we don't ask for truncates currently, getting a truncated
  484. * means that a connection broke or an extend failed. For now,
  485. * just give up.
  486. */
  487. circuit_mark_for_close(circ);
  488. return 0;
  489. while(layer->next != circ->cpath) {
  490. /* we need to clear out layer->next */
  491. victim = layer->next;
  492. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  493. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  494. if(stream->cpath_layer == victim) {
  495. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  496. /* no need to send 'end' relay cells,
  497. * because the other side's already dead
  498. */
  499. stream->has_sent_end = 1;
  500. connection_mark_for_close(stream);
  501. }
  502. }
  503. layer->next = victim->next;
  504. circuit_free_cpath_node(victim);
  505. }
  506. log_fn(LOG_INFO, "finished");
  507. return 0;
  508. }
  509. /** Decide whether the first bit of the circuit ID will be
  510. * 0 or 1, to avoid conflicts where each side randomly chooses
  511. * the same circuit ID.
  512. *
  513. * Return CIRC_ID_TYPE_LOWER if local_nick is NULL, or if
  514. * local_nick is lexographically smaller than remote_nick.
  515. * Else return CIRC_ID_TYPE_HIGHER.
  516. */
  517. static int decide_circ_id_type(char *local_nick, char *remote_nick) {
  518. int result;
  519. tor_assert(remote_nick);
  520. if(!local_nick)
  521. return CIRC_ID_TYPE_LOWER;
  522. result = strcasecmp(local_nick, remote_nick);
  523. tor_assert(result);
  524. if(result < 0)
  525. return CIRC_ID_TYPE_LOWER;
  526. return CIRC_ID_TYPE_HIGHER;
  527. }
  528. /** Given a response payload and keys, initialize, then send a created
  529. * cell back.
  530. */
  531. int onionskin_answer(circuit_t *circ, unsigned char *payload, unsigned char *keys) {
  532. cell_t cell;
  533. crypt_path_t *tmp_cpath;
  534. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  535. memset(&cell, 0, sizeof(cell_t));
  536. cell.command = CELL_CREATED;
  537. cell.circ_id = circ->p_circ_id;
  538. circ->state = CIRCUIT_STATE_OPEN;
  539. log_fn(LOG_DEBUG,"Entering.");
  540. memcpy(cell.payload, payload, ONIONSKIN_REPLY_LEN);
  541. log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
  542. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  543. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  544. log_fn(LOG_WARN,"Circuit initialization failed");
  545. tor_free(tmp_cpath);
  546. return -1;
  547. }
  548. circ->n_digest = tmp_cpath->f_digest;
  549. circ->n_crypto = tmp_cpath->f_crypto;
  550. circ->p_digest = tmp_cpath->b_digest;
  551. circ->p_crypto = tmp_cpath->b_crypto;
  552. tor_free(tmp_cpath);
  553. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  554. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  555. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  556. return 0;
  557. }
  558. extern int has_fetched_directory; /* from main.c */
  559. /** Choose a length for a circuit of purpose <b>purpose</b>.
  560. * Default length is 3 + the number of endpoints that would give something
  561. * away. If the routerlist <b>routers</b> doesn't have enough routers
  562. * to handle the desired path length, return as large a path length as
  563. * is feasible, except if it's less than 2, in which case return -1.
  564. */
  565. static int new_route_len(double cw, uint8_t purpose, smartlist_t *routers) {
  566. int num_acceptable_routers;
  567. int routelen;
  568. tor_assert((cw >= 0) && (cw < 1) && routers); /* valid parameters */
  569. #ifdef TOR_PERF
  570. routelen = 2;
  571. #else
  572. if(purpose == CIRCUIT_PURPOSE_C_GENERAL)
  573. routelen = 3;
  574. else if(purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  575. routelen = 4;
  576. else if(purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  577. routelen = 3;
  578. else if(purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  579. routelen = 3;
  580. else if(purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
  581. routelen = 4;
  582. else {
  583. log_fn(LOG_WARN,"Unhandled purpose %d", purpose);
  584. return -1;
  585. }
  586. #endif
  587. #if 0
  588. for(routelen = 3; ; routelen++) { /* 3, increment until coinflip says we're done */
  589. if (crypto_pseudo_rand_int(255) >= cw*255) /* don't extend */
  590. break;
  591. }
  592. #endif
  593. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen,
  594. smartlist_len(routers));
  595. num_acceptable_routers = count_acceptable_routers(routers);
  596. if(num_acceptable_routers < 2) {
  597. log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
  598. num_acceptable_routers);
  599. return -1;
  600. }
  601. if(num_acceptable_routers < routelen) {
  602. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
  603. routelen, num_acceptable_routers);
  604. routelen = num_acceptable_routers;
  605. }
  606. return routelen;
  607. }
  608. /** Return a pointer to a suitable router to be the exit node for the
  609. * general-purpose circuit we're about to build.
  610. *
  611. * Look through the connection array, and choose a router that maximizes
  612. * the number of pending streams that can exit from this router.
  613. *
  614. * Return NULL if we can't find any suitable routers.
  615. */
  616. static routerinfo_t *choose_good_exit_server_general(routerlist_t *dir)
  617. {
  618. int *n_supported;
  619. int i, j;
  620. int n_pending_connections = 0;
  621. connection_t **carray;
  622. int n_connections;
  623. int best_support = -1;
  624. int n_best_support=0;
  625. smartlist_t *sl, *preferredexits, *excludedexits;
  626. routerinfo_t *router;
  627. get_connection_array(&carray, &n_connections);
  628. /* Count how many connections are waiting for a circuit to be built.
  629. * We use this for log messages now, but in the future we may depend on it.
  630. */
  631. for (i = 0; i < n_connections; ++i) {
  632. if (carray[i]->type == CONN_TYPE_AP &&
  633. carray[i]->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  634. !carray[i]->marked_for_close &&
  635. !circuit_stream_is_being_handled(carray[i]))
  636. ++n_pending_connections;
  637. }
  638. log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  639. n_pending_connections);
  640. /* Now we count, for each of the routers in the directory, how many
  641. * of the pending connections could possibly exit from that
  642. * router (n_supported[i]). (We can't be sure about cases where we
  643. * don't know the IP address of the pending connection.)
  644. */
  645. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  646. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  647. router = smartlist_get(dir->routers, i);
  648. if(router_is_me(router)) {
  649. n_supported[i] = -1;
  650. log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  651. /* XXX there's probably a reverse predecessor attack here, but
  652. * it's slow. should we take this out? -RD
  653. */
  654. continue;
  655. }
  656. if(!router->is_running) {
  657. n_supported[i] = -1;
  658. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  659. router->nickname, i);
  660. continue; /* skip routers that are known to be down */
  661. }
  662. if(router_exit_policy_rejects_all(router)) {
  663. n_supported[i] = -1;
  664. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  665. router->nickname, i);
  666. continue; /* skip routers that reject all */
  667. }
  668. n_supported[i] = 0;
  669. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  670. if (carray[j]->type != CONN_TYPE_AP ||
  671. carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
  672. carray[j]->marked_for_close ||
  673. circuit_stream_is_being_handled(carray[j]))
  674. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  675. switch (connection_ap_can_use_exit(carray[j], router))
  676. {
  677. case ADDR_POLICY_REJECTED:
  678. log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  679. router->nickname, i);
  680. break; /* would be rejected; try next connection */
  681. case ADDR_POLICY_ACCEPTED:
  682. case ADDR_POLICY_UNKNOWN:
  683. ++n_supported[i];
  684. log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  685. router->nickname, i, n_supported[i]);
  686. }
  687. } /* End looping over connections. */
  688. if (n_supported[i] > best_support) {
  689. /* If this router is better than previous ones, remember its index
  690. * and goodness, and start counting how many routers are this good. */
  691. best_support = n_supported[i]; n_best_support=1;
  692. log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  693. router->nickname);
  694. } else if (n_supported[i] == best_support) {
  695. /* If this router is _as good_ as the best one, just increment the
  696. * count of equally good routers.*/
  697. ++n_best_support;
  698. }
  699. }
  700. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  701. n_best_support, best_support, n_pending_connections);
  702. preferredexits = smartlist_create();
  703. add_nickname_list_to_smartlist(preferredexits,options.ExitNodes);
  704. excludedexits = smartlist_create();
  705. add_nickname_list_to_smartlist(excludedexits,options.ExcludeNodes);
  706. sl = smartlist_create();
  707. /* If any routers definitely support any pending connections, choose one
  708. * at random. */
  709. if (best_support > 0) {
  710. for (i = 0; i < smartlist_len(dir->routers); i++)
  711. if (n_supported[i] == best_support)
  712. smartlist_add(sl, smartlist_get(dir->routers, i));
  713. smartlist_subtract(sl,excludedexits);
  714. if (smartlist_overlap(sl,preferredexits))
  715. smartlist_intersect(sl,preferredexits);
  716. router = smartlist_choose(sl);
  717. } else {
  718. /* Either there are no pending connections, or no routers even seem to
  719. * possibly support any of them. Choose a router at random. */
  720. if (best_support == -1) {
  721. log(LOG_WARN, "All routers are down or middleman -- choosing a doomed exit at random.");
  722. }
  723. for(i = 0; i < smartlist_len(dir->routers); i++)
  724. if(n_supported[i] != -1)
  725. smartlist_add(sl, smartlist_get(dir->routers, i));
  726. smartlist_subtract(sl,excludedexits);
  727. if (smartlist_overlap(sl,preferredexits))
  728. smartlist_intersect(sl,preferredexits);
  729. router = smartlist_choose(sl);
  730. }
  731. smartlist_free(preferredexits);
  732. smartlist_free(excludedexits);
  733. smartlist_free(sl);
  734. tor_free(n_supported);
  735. if(router) {
  736. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  737. return router;
  738. }
  739. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  740. return NULL;
  741. }
  742. /** Return a pointer to a suitable router to be the exit node for the
  743. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  744. * if no router is suitable).
  745. *
  746. * For general-purpose circuits, pass it off to
  747. * choose_good_exit_server_general()
  748. *
  749. * For client-side rendezvous circuits, choose a random node, weighted
  750. * toward the preferences in 'options'.
  751. */
  752. static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
  753. {
  754. routerinfo_t *r;
  755. switch(purpose) {
  756. case CIRCUIT_PURPOSE_C_GENERAL:
  757. return choose_good_exit_server_general(dir);
  758. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  759. r = router_choose_random_node(options.RendNodes, options.RendExcludeNodes, NULL);
  760. return r;
  761. default:
  762. log_fn(LOG_WARN,"unhandled purpose %d", purpose);
  763. tor_assert(0);
  764. }
  765. return NULL; /* never reached */
  766. }
  767. /** Allocate a cpath_build_state_t, populate it based on
  768. * <b>purpose</b> and <b>exit_nickname</b> (if specified), and
  769. * return it.
  770. */
  771. static cpath_build_state_t *
  772. onion_new_cpath_build_state(uint8_t purpose, const char *exit_nickname)
  773. {
  774. routerlist_t *rl;
  775. int r;
  776. cpath_build_state_t *info;
  777. routerinfo_t *exit;
  778. router_get_routerlist(&rl);
  779. r = new_route_len(options.PathlenCoinWeight, purpose, rl->routers);
  780. if (r < 0)
  781. return NULL;
  782. info = tor_malloc_zero(sizeof(cpath_build_state_t));
  783. info->desired_path_len = r;
  784. if(exit_nickname) { /* the circuit-builder pre-requested one */
  785. log_fn(LOG_INFO,"Using requested exit node '%s'", exit_nickname);
  786. info->chosen_exit = tor_strdup(exit_nickname);
  787. } else { /* we have to decide one */
  788. exit = choose_good_exit_server(purpose, rl);
  789. if(!exit) {
  790. log_fn(LOG_WARN,"failed to choose an exit server");
  791. tor_free(info);
  792. return NULL;
  793. }
  794. info->chosen_exit = tor_strdup(exit->nickname);
  795. }
  796. return info;
  797. }
  798. /** Return the number of routers in <b>routers</b> that are currently up
  799. * and available for building circuits through. Count sets of twins only
  800. * once.
  801. */
  802. static int count_acceptable_routers(smartlist_t *routers) {
  803. int i, j, n;
  804. int num=0;
  805. connection_t *conn;
  806. routerinfo_t *r, *r2;
  807. n = smartlist_len(routers);
  808. for(i=0;i<n;i++) {
  809. r = smartlist_get(routers, i);
  810. log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  811. i, r->nickname);
  812. if(r->is_running == 0) {
  813. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  814. goto next_i_loop;
  815. }
  816. if(options.ORPort) {
  817. conn = connection_exact_get_by_addr_port(r->addr, r->or_port);
  818. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  819. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  820. goto next_i_loop;
  821. }
  822. }
  823. for(j=0;j<i;j++) {
  824. r2 = smartlist_get(routers, j);
  825. if(!crypto_pk_cmp_keys(r->onion_pkey, r2->onion_pkey)) {
  826. /* these guys are twins. so we've already counted him. */
  827. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  828. goto next_i_loop;
  829. }
  830. }
  831. num++;
  832. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  833. next_i_loop:
  834. ; /* C requires an explicit statement after the label */
  835. }
  836. return num;
  837. }
  838. /** Go through smartlist <b>sl</b> of routers, and remove all elements that
  839. * have the same onion key as twin.
  840. */
  841. static void remove_twins_from_smartlist(smartlist_t *sl, routerinfo_t *twin) {
  842. int i;
  843. routerinfo_t *r;
  844. if(twin == NULL)
  845. return;
  846. for(i=0; i < smartlist_len(sl); i++) {
  847. r = smartlist_get(sl,i);
  848. if (!crypto_pk_cmp_keys(r->onion_pkey, twin->onion_pkey)) {
  849. smartlist_del(sl,i--);
  850. }
  851. }
  852. }
  853. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  854. *
  855. * This function is used to extend cpath by another hop.
  856. */
  857. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  858. {
  859. if (*head_ptr) {
  860. new_hop->next = (*head_ptr);
  861. new_hop->prev = (*head_ptr)->prev;
  862. (*head_ptr)->prev->next = new_hop;
  863. (*head_ptr)->prev = new_hop;
  864. } else {
  865. *head_ptr = new_hop;
  866. new_hop->prev = new_hop->next = new_hop;
  867. }
  868. }
  869. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  870. * based on <b>state</b>. Add the hop info to head_ptr, and return a
  871. * pointer to the chosen router in <b>router_out</b>.
  872. */
  873. static int
  874. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  875. *state, routerinfo_t **router_out)
  876. {
  877. int cur_len;
  878. crypt_path_t *cpath, *hop;
  879. routerinfo_t *r;
  880. routerinfo_t *choice;
  881. int i;
  882. smartlist_t *sl, *excludednodes;
  883. tor_assert(head_ptr);
  884. tor_assert(router_out);
  885. if (!*head_ptr) {
  886. cur_len = 0;
  887. } else {
  888. cur_len = 1;
  889. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  890. ++cur_len;
  891. }
  892. }
  893. if (cur_len >= state->desired_path_len) {
  894. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  895. state->desired_path_len);
  896. return 1;
  897. }
  898. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  899. state->desired_path_len);
  900. excludednodes = smartlist_create();
  901. add_nickname_list_to_smartlist(excludednodes,options.ExcludeNodes);
  902. if(cur_len == state->desired_path_len - 1) { /* Picking last node */
  903. log_fn(LOG_DEBUG, "Contemplating last hop: choice already made: %s",
  904. state->chosen_exit);
  905. choice = router_get_by_nickname(state->chosen_exit);
  906. smartlist_free(excludednodes);
  907. if(!choice) {
  908. log_fn(LOG_WARN,"Our chosen exit %s is no longer in the directory? Discarding this circuit.",
  909. state->chosen_exit);
  910. return -1;
  911. }
  912. } else if(cur_len == 0) { /* picking first node */
  913. /* try the nodes in EntryNodes first */
  914. sl = smartlist_create();
  915. add_nickname_list_to_smartlist(sl,options.EntryNodes);
  916. /* XXX one day, consider picking chosen_exit knowing what's in EntryNodes */
  917. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  918. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  919. smartlist_subtract(sl,excludednodes);
  920. choice = smartlist_choose(sl);
  921. smartlist_free(sl);
  922. if(!choice) {
  923. sl = smartlist_create();
  924. router_add_running_routers_to_smartlist(sl);
  925. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  926. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  927. smartlist_subtract(sl,excludednodes);
  928. choice = smartlist_choose(sl);
  929. smartlist_free(sl);
  930. }
  931. smartlist_free(excludednodes);
  932. if(!choice) {
  933. log_fn(LOG_WARN,"No acceptable routers while picking entry node. Discarding this circuit.");
  934. return -1;
  935. }
  936. } else {
  937. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  938. sl = smartlist_create();
  939. router_add_running_routers_to_smartlist(sl);
  940. remove_twins_from_smartlist(sl,router_get_by_nickname(state->chosen_exit));
  941. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  942. for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
  943. r = router_get_by_addr_port(cpath->addr, cpath->port);
  944. tor_assert(r);
  945. remove_twins_from_smartlist(sl,r);
  946. }
  947. smartlist_subtract(sl,excludednodes);
  948. choice = smartlist_choose(sl);
  949. smartlist_free(sl);
  950. smartlist_free(excludednodes);
  951. if(!choice) {
  952. log_fn(LOG_WARN,"No acceptable routers while picking intermediate node. Discarding this circuit.");
  953. return -1;
  954. }
  955. }
  956. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  957. choice->nickname, cur_len, state->chosen_exit);
  958. hop = tor_malloc_zero(sizeof(crypt_path_t));
  959. /* link hop into the cpath, at the end. */
  960. onion_append_to_cpath(head_ptr, hop);
  961. hop->state = CPATH_STATE_CLOSED;
  962. hop->port = choice->or_port;
  963. hop->addr = choice->addr;
  964. hop->package_window = CIRCWINDOW_START;
  965. hop->deliver_window = CIRCWINDOW_START;
  966. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  967. choice->nickname, cur_len);
  968. *router_out = choice;
  969. return 0;
  970. }
  971. /*
  972. Local Variables:
  973. mode:c
  974. indent-tabs-mode:nil
  975. c-basic-offset:2
  976. End:
  977. */