circuitbuild.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #include "or.h"
  11. #include "channel.h"
  12. #include "circpathbias.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "circuitstats.h"
  16. #include "circuituse.h"
  17. #include "command.h"
  18. #include "config.h"
  19. #include "confparse.h"
  20. #include "connection.h"
  21. #include "connection_edge.h"
  22. #include "connection_or.h"
  23. #include "control.h"
  24. #include "directory.h"
  25. #include "entrynodes.h"
  26. #include "main.h"
  27. #include "microdesc.h"
  28. #include "networkstatus.h"
  29. #include "nodelist.h"
  30. #include "onion.h"
  31. #include "onion_tap.h"
  32. #include "onion_fast.h"
  33. #include "policies.h"
  34. #include "transports.h"
  35. #include "relay.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #include "routerset.h"
  41. #include "crypto.h"
  42. #ifndef MIN
  43. #define MIN(a,b) ((a)<(b)?(a):(b))
  44. #endif
  45. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  46. uint16_t port,
  47. const char *id_digest);
  48. static int circuit_deliver_create_cell(circuit_t *circ,
  49. const create_cell_t *create_cell,
  50. int relayed);
  51. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  52. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  53. static int onion_extend_cpath(origin_circuit_t *circ);
  54. static int count_acceptable_nodes(smartlist_t *routers);
  55. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  56. /** This function tries to get a channel to the specified endpoint,
  57. * and then calls command_setup_channel() to give it the right
  58. * callbacks.
  59. */
  60. static channel_t *
  61. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  62. const char *id_digest)
  63. {
  64. channel_t *chan;
  65. chan = channel_connect(addr, port, id_digest);
  66. if (chan) command_setup_channel(chan);
  67. return chan;
  68. }
  69. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  70. * and with the high bit specified by conn-\>circ_id_type, until we get
  71. * a circ_id that is not in use by any other circuit on that conn.
  72. *
  73. * Return it, or 0 if can't get a unique circ_id.
  74. */
  75. static circid_t
  76. get_unique_circ_id_by_chan(channel_t *chan)
  77. {
  78. circid_t test_circ_id;
  79. circid_t attempts=0;
  80. circid_t high_bit, max_range;
  81. tor_assert(chan);
  82. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  83. log_warn(LD_BUG,
  84. "Trying to pick a circuit ID for a connection from "
  85. "a client with no identity.");
  86. return 0;
  87. }
  88. max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
  89. high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
  90. do {
  91. /* Sequentially iterate over test_circ_id=1...max_range until we find a
  92. * circID such that (high_bit|test_circ_id) is not already used. */
  93. test_circ_id = chan->next_circ_id++;
  94. if (test_circ_id == 0 || test_circ_id >= max_range) {
  95. test_circ_id = 1;
  96. chan->next_circ_id = 2;
  97. }
  98. if (++attempts > max_range) {
  99. /* Make sure we don't loop forever if all circ_id's are used. This
  100. * matters because it's an external DoS opportunity.
  101. */
  102. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  103. return 0;
  104. }
  105. test_circ_id |= high_bit;
  106. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  107. return test_circ_id;
  108. }
  109. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  110. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  111. * list information about link status in a more verbose format using spaces.
  112. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  113. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  114. * names.
  115. */
  116. static char *
  117. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  118. {
  119. crypt_path_t *hop;
  120. smartlist_t *elements;
  121. const char *states[] = {"closed", "waiting for keys", "open"};
  122. char *s;
  123. elements = smartlist_new();
  124. if (verbose) {
  125. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  126. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  127. circ->build_state->is_internal ? "internal" : "exit",
  128. circ->build_state->need_uptime ? " (high-uptime)" : "",
  129. circ->build_state->desired_path_len,
  130. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  131. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  132. (nickname?nickname:"*unnamed*"));
  133. }
  134. hop = circ->cpath;
  135. do {
  136. char *elt;
  137. const char *id;
  138. const node_t *node;
  139. if (!hop)
  140. break;
  141. if (!verbose && hop->state != CPATH_STATE_OPEN)
  142. break;
  143. if (!hop->extend_info)
  144. break;
  145. id = hop->extend_info->identity_digest;
  146. if (verbose_names) {
  147. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  148. if ((node = node_get_by_id(id))) {
  149. node_get_verbose_nickname(node, elt);
  150. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  151. elt[0] = '$';
  152. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  153. elt[HEX_DIGEST_LEN+1]= '~';
  154. strlcpy(elt+HEX_DIGEST_LEN+2,
  155. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  156. } else {
  157. elt[0] = '$';
  158. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  159. }
  160. } else { /* ! verbose_names */
  161. node = node_get_by_id(id);
  162. if (node && node_is_named(node)) {
  163. elt = tor_strdup(node_get_nickname(node));
  164. } else {
  165. elt = tor_malloc(HEX_DIGEST_LEN+2);
  166. elt[0] = '$';
  167. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  168. }
  169. }
  170. tor_assert(elt);
  171. if (verbose) {
  172. tor_assert(hop->state <= 2);
  173. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  174. tor_free(elt);
  175. } else {
  176. smartlist_add(elements, elt);
  177. }
  178. hop = hop->next;
  179. } while (hop != circ->cpath);
  180. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  181. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  182. smartlist_free(elements);
  183. return s;
  184. }
  185. /** If <b>verbose</b> is false, allocate and return a comma-separated
  186. * list of the currently built elements of <b>circ</b>. If
  187. * <b>verbose</b> is true, also list information about link status in
  188. * a more verbose format using spaces.
  189. */
  190. char *
  191. circuit_list_path(origin_circuit_t *circ, int verbose)
  192. {
  193. return circuit_list_path_impl(circ, verbose, 0);
  194. }
  195. /** Allocate and return a comma-separated list of the currently built elements
  196. * of <b>circ</b>, giving each as a verbose nickname.
  197. */
  198. char *
  199. circuit_list_path_for_controller(origin_circuit_t *circ)
  200. {
  201. return circuit_list_path_impl(circ, 0, 1);
  202. }
  203. /** Log, at severity <b>severity</b>, the nicknames of each router in
  204. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  205. * exit point.
  206. */
  207. void
  208. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  209. {
  210. char *s = circuit_list_path(circ,1);
  211. tor_log(severity,domain,"%s",s);
  212. tor_free(s);
  213. }
  214. /** Tell the rep(utation)hist(ory) module about the status of the links
  215. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  216. * extended; the _first_ hop that isn't open (if any) is marked as
  217. * unable to extend.
  218. */
  219. /* XXXX Someday we should learn from OR circuits too. */
  220. void
  221. circuit_rep_hist_note_result(origin_circuit_t *circ)
  222. {
  223. crypt_path_t *hop;
  224. const char *prev_digest = NULL;
  225. hop = circ->cpath;
  226. if (!hop) /* circuit hasn't started building yet. */
  227. return;
  228. if (server_mode(get_options())) {
  229. const routerinfo_t *me = router_get_my_routerinfo();
  230. if (!me)
  231. return;
  232. prev_digest = me->cache_info.identity_digest;
  233. }
  234. do {
  235. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  236. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  237. if (prev_digest) {
  238. if (hop->state == CPATH_STATE_OPEN)
  239. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  240. else {
  241. rep_hist_note_extend_failed(prev_digest, node->identity);
  242. break;
  243. }
  244. }
  245. prev_digest = node->identity;
  246. } else {
  247. prev_digest = NULL;
  248. }
  249. hop=hop->next;
  250. } while (hop!=circ->cpath);
  251. }
  252. /** Pick all the entries in our cpath. Stop and return 0 when we're
  253. * happy, or return -1 if an error occurs. */
  254. static int
  255. onion_populate_cpath(origin_circuit_t *circ)
  256. {
  257. int r;
  258. again:
  259. r = onion_extend_cpath(circ);
  260. if (r < 0) {
  261. log_info(LD_CIRC,"Generating cpath hop failed.");
  262. return -1;
  263. }
  264. if (r == 0)
  265. goto again;
  266. return 0; /* if r == 1 */
  267. }
  268. /** Create and return a new origin circuit. Initialize its purpose and
  269. * build-state based on our arguments. The <b>flags</b> argument is a
  270. * bitfield of CIRCLAUNCH_* flags. */
  271. origin_circuit_t *
  272. origin_circuit_init(uint8_t purpose, int flags)
  273. {
  274. /* sets circ->p_circ_id and circ->p_chan */
  275. origin_circuit_t *circ = origin_circuit_new();
  276. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  277. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  278. circ->build_state->onehop_tunnel =
  279. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  280. circ->build_state->need_uptime =
  281. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  282. circ->build_state->need_capacity =
  283. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  284. circ->build_state->is_internal =
  285. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  286. circ->base_.purpose = purpose;
  287. return circ;
  288. }
  289. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  290. * is defined, then use that as your exit router, else choose a suitable
  291. * exit node.
  292. *
  293. * Also launch a connection to the first OR in the chosen path, if
  294. * it's not open already.
  295. */
  296. origin_circuit_t *
  297. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  298. {
  299. origin_circuit_t *circ;
  300. int err_reason = 0;
  301. circ = origin_circuit_init(purpose, flags);
  302. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  303. onion_populate_cpath(circ) < 0) {
  304. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  305. return NULL;
  306. }
  307. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  308. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  309. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  310. return NULL;
  311. }
  312. return circ;
  313. }
  314. /** Start establishing the first hop of our circuit. Figure out what
  315. * OR we should connect to, and if necessary start the connection to
  316. * it. If we're already connected, then send the 'create' cell.
  317. * Return 0 for ok, -reason if circ should be marked-for-close. */
  318. int
  319. circuit_handle_first_hop(origin_circuit_t *circ)
  320. {
  321. crypt_path_t *firsthop;
  322. channel_t *n_chan;
  323. int err_reason = 0;
  324. const char *msg = NULL;
  325. int should_launch = 0;
  326. firsthop = onion_next_hop_in_cpath(circ->cpath);
  327. tor_assert(firsthop);
  328. tor_assert(firsthop->extend_info);
  329. /* now see if we're already connected to the first OR in 'route' */
  330. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  331. fmt_addrport(&firsthop->extend_info->addr,
  332. firsthop->extend_info->port));
  333. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  334. &firsthop->extend_info->addr,
  335. &msg,
  336. &should_launch);
  337. if (!n_chan) {
  338. /* not currently connected in a useful way. */
  339. log_info(LD_CIRC, "Next router is %s: %s",
  340. safe_str_client(extend_info_describe(firsthop->extend_info)),
  341. msg?msg:"???");
  342. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  343. if (should_launch) {
  344. if (circ->build_state->onehop_tunnel)
  345. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  346. n_chan = channel_connect_for_circuit(
  347. &firsthop->extend_info->addr,
  348. firsthop->extend_info->port,
  349. firsthop->extend_info->identity_digest);
  350. if (!n_chan) { /* connect failed, forget the whole thing */
  351. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  352. return -END_CIRC_REASON_CONNECTFAILED;
  353. }
  354. }
  355. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  356. /* return success. The onion/circuit/etc will be taken care of
  357. * automatically (may already have been) whenever n_chan reaches
  358. * OR_CONN_STATE_OPEN.
  359. */
  360. return 0;
  361. } else { /* it's already open. use it. */
  362. tor_assert(!circ->base_.n_hop);
  363. circ->base_.n_chan = n_chan;
  364. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  365. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  366. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  367. return err_reason;
  368. }
  369. }
  370. return 0;
  371. }
  372. /** Find any circuits that are waiting on <b>or_conn</b> to become
  373. * open and get them to send their create cells forward.
  374. *
  375. * Status is 1 if connect succeeded, or 0 if connect failed.
  376. */
  377. void
  378. circuit_n_chan_done(channel_t *chan, int status)
  379. {
  380. smartlist_t *pending_circs;
  381. int err_reason = 0;
  382. tor_assert(chan);
  383. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  384. chan->nickname ? chan->nickname : "NULL",
  385. channel_get_canonical_remote_descr(chan), status);
  386. pending_circs = smartlist_new();
  387. circuit_get_all_pending_on_channel(pending_circs, chan);
  388. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  389. {
  390. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  391. * leaving them in in case it's possible for the status of a circuit to
  392. * change as we're going down the list. */
  393. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  394. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  395. continue;
  396. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  397. /* Look at addr/port. This is an unkeyed connection. */
  398. if (!channel_matches_extend_info(chan, circ->n_hop))
  399. continue;
  400. } else {
  401. /* We expected a key. See if it's the right one. */
  402. if (tor_memneq(chan->identity_digest,
  403. circ->n_hop->identity_digest, DIGEST_LEN))
  404. continue;
  405. }
  406. if (!status) { /* chan failed; close circ */
  407. log_info(LD_CIRC,"Channel failed; closing circ.");
  408. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  409. continue;
  410. }
  411. log_debug(LD_CIRC, "Found circ, sending create cell.");
  412. /* circuit_deliver_create_cell will set n_circ_id and add us to
  413. * chan_circuid_circuit_map, so we don't need to call
  414. * set_circid_chan here. */
  415. circ->n_chan = chan;
  416. extend_info_free(circ->n_hop);
  417. circ->n_hop = NULL;
  418. if (CIRCUIT_IS_ORIGIN(circ)) {
  419. if ((err_reason =
  420. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  421. log_info(LD_CIRC,
  422. "send_next_onion_skin failed; circuit marked for closing.");
  423. circuit_mark_for_close(circ, -err_reason);
  424. continue;
  425. /* XXX could this be bad, eg if next_onion_skin failed because conn
  426. * died? */
  427. }
  428. } else {
  429. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  430. tor_assert(circ->n_chan_create_cell);
  431. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  432. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  433. continue;
  434. }
  435. tor_free(circ->n_chan_create_cell);
  436. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  437. }
  438. }
  439. SMARTLIST_FOREACH_END(circ);
  440. smartlist_free(pending_circs);
  441. }
  442. /** Find a new circid that isn't currently in use on the circ->n_chan
  443. * for the outgoing
  444. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  445. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  446. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  447. * it. Return -1 if we failed to find a suitable circid, else return 0.
  448. */
  449. static int
  450. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  451. int relayed)
  452. {
  453. cell_t cell;
  454. circid_t id;
  455. int r;
  456. tor_assert(circ);
  457. tor_assert(circ->n_chan);
  458. tor_assert(create_cell);
  459. tor_assert(create_cell->cell_type == CELL_CREATE ||
  460. create_cell->cell_type == CELL_CREATE_FAST ||
  461. create_cell->cell_type == CELL_CREATE2);
  462. id = get_unique_circ_id_by_chan(circ->n_chan);
  463. if (!id) {
  464. log_warn(LD_CIRC,"failed to get unique circID.");
  465. return -1;
  466. }
  467. log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
  468. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  469. memset(&cell, 0, sizeof(cell_t));
  470. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  471. : create_cell_format(&cell, create_cell);
  472. if (r < 0) {
  473. log_warn(LD_CIRC,"Couldn't format create cell");
  474. return -1;
  475. }
  476. cell.circ_id = circ->n_circ_id;
  477. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  478. CELL_DIRECTION_OUT, 0);
  479. if (CIRCUIT_IS_ORIGIN(circ)) {
  480. /* Update began timestamp for circuits starting their first hop */
  481. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  482. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  483. log_warn(LD_CIRC,
  484. "Got first hop for a circuit without an opened channel. "
  485. "State: %s.", channel_state_to_string(circ->n_chan->state));
  486. tor_fragile_assert();
  487. }
  488. tor_gettimeofday(&circ->timestamp_began);
  489. }
  490. /* mark it so it gets better rate limiting treatment. */
  491. channel_timestamp_client(circ->n_chan);
  492. }
  493. return 0;
  494. }
  495. /** We've decided to start our reachability testing. If all
  496. * is set, log this to the user. Return 1 if we did, or 0 if
  497. * we chose not to log anything. */
  498. int
  499. inform_testing_reachability(void)
  500. {
  501. char dirbuf[128];
  502. const routerinfo_t *me = router_get_my_routerinfo();
  503. if (!me)
  504. return 0;
  505. control_event_server_status(LOG_NOTICE,
  506. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  507. me->address, me->or_port);
  508. if (me->dir_port) {
  509. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  510. me->address, me->dir_port);
  511. control_event_server_status(LOG_NOTICE,
  512. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  513. me->address, me->dir_port);
  514. }
  515. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  516. "(this may take up to %d minutes -- look for log "
  517. "messages indicating success)",
  518. me->address, me->or_port,
  519. me->dir_port ? dirbuf : "",
  520. me->dir_port ? "are" : "is",
  521. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  522. return 1;
  523. }
  524. /** Return true iff we should send a create_fast cell to start building a given
  525. * circuit */
  526. static INLINE int
  527. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  528. {
  529. const or_options_t *options = get_options();
  530. tor_assert(circ->cpath);
  531. tor_assert(circ->cpath->extend_info);
  532. if (!circ->cpath->extend_info->onion_key)
  533. return 1; /* our hand is forced: only a create_fast will work. */
  534. if (!options->FastFirstHopPK)
  535. return 0; /* we prefer to avoid create_fast */
  536. if (public_server_mode(options)) {
  537. /* We're a server, and we know an onion key. We can choose.
  538. * Prefer to blend our circuit into the other circuits we are
  539. * creating on behalf of others. */
  540. return 0;
  541. }
  542. return 1;
  543. }
  544. /** Return true if <b>circ</b> is the type of circuit we want to count
  545. * timeouts from. In particular, we want it to have not completed yet
  546. * (already completing indicates we cannibalized it), and we want it to
  547. * have exactly three hops.
  548. */
  549. int
  550. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  551. {
  552. return !circ->has_opened
  553. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  554. }
  555. #ifdef CURVE25519_ENABLED
  556. /** Return true if the ntor handshake is enabled in the configuration, or if
  557. * it's been set to "auto" in the configuration and it's enabled in the
  558. * consensus. */
  559. static int
  560. circuits_can_use_ntor(void)
  561. {
  562. const or_options_t *options = get_options();
  563. if (options->UseNTorHandshake != -1)
  564. return options->UseNTorHandshake;
  565. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  566. }
  567. #endif
  568. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  569. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  570. * accordingly. */
  571. static void
  572. circuit_pick_create_handshake(uint8_t *cell_type_out,
  573. uint16_t *handshake_type_out,
  574. const extend_info_t *ei)
  575. {
  576. #ifdef CURVE25519_ENABLED
  577. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  578. CURVE25519_PUBKEY_LEN) &&
  579. circuits_can_use_ntor()) {
  580. *cell_type_out = CELL_CREATE2;
  581. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  582. return;
  583. }
  584. #else
  585. (void) ei;
  586. #endif
  587. *cell_type_out = CELL_CREATE;
  588. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  589. }
  590. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  591. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  592. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  593. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  594. * *<b>create_cell_type_out</b> accordingly. */
  595. static void
  596. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  597. uint8_t *create_cell_type_out,
  598. uint16_t *handshake_type_out,
  599. const node_t *node_prev,
  600. const extend_info_t *ei)
  601. {
  602. uint8_t t;
  603. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  604. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  605. * proxy for whether it can do extend2 cells; once a version that
  606. * handles extend2 cells is out, remove it. */
  607. if (node_prev &&
  608. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  609. (node_has_curve25519_onion_key(node_prev) ||
  610. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  611. *cell_type_out = RELAY_COMMAND_EXTEND2;
  612. *create_cell_type_out = CELL_CREATE2;
  613. } else {
  614. *cell_type_out = RELAY_COMMAND_EXTEND;
  615. *create_cell_type_out = CELL_CREATE;
  616. }
  617. }
  618. /** This is the backbone function for building circuits.
  619. *
  620. * If circ's first hop is closed, then we need to build a create
  621. * cell and send it forward.
  622. *
  623. * Otherwise, we need to build a relay extend cell and send it
  624. * forward.
  625. *
  626. * Return -reason if we want to tear down circ, else return 0.
  627. */
  628. int
  629. circuit_send_next_onion_skin(origin_circuit_t *circ)
  630. {
  631. crypt_path_t *hop;
  632. const node_t *node;
  633. tor_assert(circ);
  634. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  635. /* This is the first hop. */
  636. create_cell_t cc;
  637. int fast;
  638. int len;
  639. log_debug(LD_CIRC,"First skin; sending create cell.");
  640. memset(&cc, 0, sizeof(cc));
  641. if (circ->build_state->onehop_tunnel)
  642. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  643. else
  644. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  645. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  646. fast = should_use_create_fast_for_circuit(circ);
  647. if (!fast) {
  648. /* We are an OR and we know the right onion key: we should
  649. * send a create cell.
  650. */
  651. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  652. circ->cpath->extend_info);
  653. note_request("cell: create", 1);
  654. } else {
  655. /* We are not an OR, and we're building the first hop of a circuit to a
  656. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  657. * and a DH operation. */
  658. cc.cell_type = CELL_CREATE_FAST;
  659. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  660. note_request("cell: create fast", 1);
  661. }
  662. len = onion_skin_create(cc.handshake_type,
  663. circ->cpath->extend_info,
  664. &circ->cpath->handshake_state,
  665. cc.onionskin);
  666. if (len < 0) {
  667. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  668. return - END_CIRC_REASON_INTERNAL;
  669. }
  670. cc.handshake_len = len;
  671. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  672. return - END_CIRC_REASON_RESOURCELIMIT;
  673. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  674. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  675. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  676. fast ? "CREATE_FAST" : "CREATE",
  677. node ? node_describe(node) : "<unnamed>");
  678. } else {
  679. extend_cell_t ec;
  680. int len;
  681. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  682. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  683. log_debug(LD_CIRC,"starting to send subsequent skin.");
  684. hop = onion_next_hop_in_cpath(circ->cpath);
  685. memset(&ec, 0, sizeof(ec));
  686. if (!hop) {
  687. /* done building the circuit. whew. */
  688. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  689. if (circuit_timeout_want_to_count_circ(circ)) {
  690. struct timeval end;
  691. long timediff;
  692. tor_gettimeofday(&end);
  693. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  694. /*
  695. * If the circuit build time is much greater than we would have cut
  696. * it off at, we probably had a suspend event along this codepath,
  697. * and we should discard the value.
  698. */
  699. if (timediff < 0 ||
  700. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  701. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  702. "Assuming clock jump. Purpose %d (%s)", timediff,
  703. circ->base_.purpose,
  704. circuit_purpose_to_string(circ->base_.purpose));
  705. } else if (!circuit_build_times_disabled()) {
  706. /* Only count circuit times if the network is live */
  707. if (circuit_build_times_network_check_live(
  708. get_circuit_build_times())) {
  709. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  710. (build_time_t)timediff);
  711. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  712. }
  713. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  714. circuit_build_times_network_circ_success(
  715. get_circuit_build_times_mutable());
  716. }
  717. }
  718. }
  719. log_info(LD_CIRC,"circuit built!");
  720. circuit_reset_failure_count(0);
  721. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  722. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  723. }
  724. pathbias_count_build_success(circ);
  725. circuit_rep_hist_note_result(circ);
  726. circuit_has_opened(circ); /* do other actions as necessary */
  727. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  728. const or_options_t *options = get_options();
  729. can_complete_circuit=1;
  730. /* FFFF Log a count of known routers here */
  731. log_notice(LD_GENERAL,
  732. "Tor has successfully opened a circuit. "
  733. "Looks like client functionality is working.");
  734. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  735. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  736. clear_broken_connection_map(1);
  737. if (server_mode(options) && !check_whether_orport_reachable()) {
  738. inform_testing_reachability();
  739. consider_testing_reachability(1, 1);
  740. }
  741. }
  742. /* We're done with measurement circuits here. Just close them */
  743. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  744. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  745. }
  746. return 0;
  747. }
  748. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  749. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  750. return - END_CIRC_REASON_INTERNAL;
  751. }
  752. {
  753. const node_t *prev_node;
  754. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  755. circuit_pick_extend_handshake(&ec.cell_type,
  756. &ec.create_cell.cell_type,
  757. &ec.create_cell.handshake_type,
  758. prev_node,
  759. hop->extend_info);
  760. }
  761. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  762. ec.orport_ipv4.port = hop->extend_info->port;
  763. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  764. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  765. len = onion_skin_create(ec.create_cell.handshake_type,
  766. hop->extend_info,
  767. &hop->handshake_state,
  768. ec.create_cell.onionskin);
  769. if (len < 0) {
  770. log_warn(LD_CIRC,"onion_skin_create failed.");
  771. return - END_CIRC_REASON_INTERNAL;
  772. }
  773. ec.create_cell.handshake_len = len;
  774. log_info(LD_CIRC,"Sending extend relay cell.");
  775. note_request("cell: extend", 1);
  776. {
  777. uint8_t command = 0;
  778. uint16_t payload_len=0;
  779. uint8_t payload[RELAY_PAYLOAD_SIZE];
  780. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  781. log_warn(LD_CIRC,"Couldn't format extend cell");
  782. return -END_CIRC_REASON_INTERNAL;
  783. }
  784. /* send it to hop->prev, because it will transfer
  785. * it to a create cell and then send to hop */
  786. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  787. command,
  788. (char*)payload, payload_len,
  789. hop->prev) < 0)
  790. return 0; /* circuit is closed */
  791. }
  792. hop->state = CPATH_STATE_AWAITING_KEYS;
  793. }
  794. return 0;
  795. }
  796. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  797. * something has also gone wrong with our network: notify the user,
  798. * and abandon all not-yet-used circuits. */
  799. void
  800. circuit_note_clock_jumped(int seconds_elapsed)
  801. {
  802. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  803. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  804. "assuming established circuits no longer work.",
  805. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  806. seconds_elapsed >=0 ? "forward" : "backward");
  807. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  808. seconds_elapsed);
  809. can_complete_circuit=0; /* so it'll log when it works again */
  810. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  811. "CLOCK_JUMPED");
  812. circuit_mark_all_unused_circs();
  813. circuit_mark_all_dirty_circs_as_unusable();
  814. }
  815. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  816. * skin and identity digest for the next hop. If we're already connected,
  817. * pass the onion skin to the next hop using a create cell; otherwise
  818. * launch a new OR connection, and <b>circ</b> will notice when the
  819. * connection succeeds or fails.
  820. *
  821. * Return -1 if we want to warn and tear down the circuit, else return 0.
  822. */
  823. int
  824. circuit_extend(cell_t *cell, circuit_t *circ)
  825. {
  826. channel_t *n_chan;
  827. relay_header_t rh;
  828. extend_cell_t ec;
  829. const char *msg = NULL;
  830. int should_launch = 0;
  831. if (circ->n_chan) {
  832. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  833. "n_chan already set. Bug/attack. Closing.");
  834. return -1;
  835. }
  836. if (circ->n_hop) {
  837. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  838. "conn to next hop already launched. Bug/attack. Closing.");
  839. return -1;
  840. }
  841. if (!server_mode(get_options())) {
  842. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  843. "Got an extend cell, but running as a client. Closing.");
  844. return -1;
  845. }
  846. relay_header_unpack(&rh, cell->payload);
  847. if (extend_cell_parse(&ec, rh.command,
  848. cell->payload+RELAY_HEADER_SIZE,
  849. rh.length) < 0) {
  850. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  851. "Can't parse extend cell. Closing circuit.");
  852. return -1;
  853. }
  854. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  855. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  856. "Client asked me to extend to zero destination port or addr.");
  857. return -1;
  858. }
  859. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  860. !get_options()->ExtendAllowPrivateAddresses) {
  861. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  862. "Client asked me to extend to a private address");
  863. return -1;
  864. }
  865. /* Check if they asked us for 0000..0000. We support using
  866. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  867. * but we don't want to let people send us extend cells for empty
  868. * fingerprints -- a) because it opens the user up to a mitm attack,
  869. * and b) because it lets an attacker force the relay to hold open a
  870. * new TLS connection for each extend request. */
  871. if (tor_digest_is_zero((const char*)ec.node_id)) {
  872. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  873. "Client asked me to extend without specifying an id_digest.");
  874. return -1;
  875. }
  876. /* Next, check if we're being asked to connect to the hop that the
  877. * extend cell came from. There isn't any reason for that, and it can
  878. * assist circular-path attacks. */
  879. if (tor_memeq(ec.node_id,
  880. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  881. DIGEST_LEN)) {
  882. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  883. "Client asked me to extend back to the previous hop.");
  884. return -1;
  885. }
  886. n_chan = channel_get_for_extend((const char*)ec.node_id,
  887. &ec.orport_ipv4.addr,
  888. &msg,
  889. &should_launch);
  890. if (!n_chan) {
  891. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  892. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  893. msg?msg:"????");
  894. circ->n_hop = extend_info_new(NULL /*nickname*/,
  895. (const char*)ec.node_id,
  896. NULL /*onion_key*/,
  897. NULL /*curve25519_key*/,
  898. &ec.orport_ipv4.addr,
  899. ec.orport_ipv4.port);
  900. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  901. sizeof(ec.create_cell));
  902. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  903. if (should_launch) {
  904. /* we should try to open a connection */
  905. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  906. ec.orport_ipv4.port,
  907. (const char*)ec.node_id);
  908. if (!n_chan) {
  909. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  910. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  911. return 0;
  912. }
  913. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  914. }
  915. /* return success. The onion/circuit/etc will be taken care of
  916. * automatically (may already have been) whenever n_chan reaches
  917. * OR_CONN_STATE_OPEN.
  918. */
  919. return 0;
  920. }
  921. tor_assert(!circ->n_hop); /* Connection is already established. */
  922. circ->n_chan = n_chan;
  923. log_debug(LD_CIRC,
  924. "n_chan is %s",
  925. channel_get_canonical_remote_descr(n_chan));
  926. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  927. return -1;
  928. return 0;
  929. }
  930. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  931. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  932. * used as follows:
  933. * - 20 to initialize f_digest
  934. * - 20 to initialize b_digest
  935. * - 16 to key f_crypto
  936. * - 16 to key b_crypto
  937. *
  938. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  939. */
  940. int
  941. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  942. int reverse)
  943. {
  944. crypto_digest_t *tmp_digest;
  945. crypto_cipher_t *tmp_crypto;
  946. tor_assert(cpath);
  947. tor_assert(key_data);
  948. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  949. cpath->f_digest || cpath->b_digest));
  950. cpath->f_digest = crypto_digest_new();
  951. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  952. cpath->b_digest = crypto_digest_new();
  953. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  954. if (!(cpath->f_crypto =
  955. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  956. log_warn(LD_BUG,"Forward cipher initialization failed.");
  957. return -1;
  958. }
  959. if (!(cpath->b_crypto =
  960. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  961. log_warn(LD_BUG,"Backward cipher initialization failed.");
  962. return -1;
  963. }
  964. if (reverse) {
  965. tmp_digest = cpath->f_digest;
  966. cpath->f_digest = cpath->b_digest;
  967. cpath->b_digest = tmp_digest;
  968. tmp_crypto = cpath->f_crypto;
  969. cpath->f_crypto = cpath->b_crypto;
  970. cpath->b_crypto = tmp_crypto;
  971. }
  972. return 0;
  973. }
  974. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  975. * (The body of <b>reply</b> varies depending on what sort of handshake
  976. * this is.)
  977. *
  978. * Calculate the appropriate keys and digests, make sure KH is
  979. * correct, and initialize this hop of the cpath.
  980. *
  981. * Return - reason if we want to mark circ for close, else return 0.
  982. */
  983. int
  984. circuit_finish_handshake(origin_circuit_t *circ,
  985. const created_cell_t *reply)
  986. {
  987. char keys[CPATH_KEY_MATERIAL_LEN];
  988. crypt_path_t *hop;
  989. int rv;
  990. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  991. return rv;
  992. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  993. hop = circ->cpath;
  994. } else {
  995. hop = onion_next_hop_in_cpath(circ->cpath);
  996. if (!hop) { /* got an extended when we're all done? */
  997. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  998. return - END_CIRC_REASON_TORPROTOCOL;
  999. }
  1000. }
  1001. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1002. {
  1003. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1004. &hop->handshake_state,
  1005. reply->reply, reply->handshake_len,
  1006. (uint8_t*)keys, sizeof(keys),
  1007. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1008. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1009. return -END_CIRC_REASON_TORPROTOCOL;
  1010. }
  1011. }
  1012. onion_handshake_state_release(&hop->handshake_state);
  1013. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1014. return -END_CIRC_REASON_TORPROTOCOL;
  1015. }
  1016. hop->state = CPATH_STATE_OPEN;
  1017. log_info(LD_CIRC,"Finished building circuit hop:");
  1018. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1019. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1020. return 0;
  1021. }
  1022. /** We received a relay truncated cell on circ.
  1023. *
  1024. * Since we don't send truncates currently, getting a truncated
  1025. * means that a connection broke or an extend failed. For now,
  1026. * just give up: force circ to close, and return 0.
  1027. */
  1028. int
  1029. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1030. {
  1031. // crypt_path_t *victim;
  1032. // connection_t *stream;
  1033. tor_assert(circ);
  1034. tor_assert(layer);
  1035. /* XXX Since we don't send truncates currently, getting a truncated
  1036. * means that a connection broke or an extend failed. For now,
  1037. * just give up.
  1038. */
  1039. circuit_mark_for_close(TO_CIRCUIT(circ),
  1040. END_CIRC_REASON_FLAG_REMOTE|reason);
  1041. return 0;
  1042. #if 0
  1043. while (layer->next != circ->cpath) {
  1044. /* we need to clear out layer->next */
  1045. victim = layer->next;
  1046. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1047. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1048. if (stream->cpath_layer == victim) {
  1049. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1050. stream->stream_id);
  1051. /* no need to send 'end' relay cells,
  1052. * because the other side's already dead
  1053. */
  1054. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1055. }
  1056. }
  1057. layer->next = victim->next;
  1058. circuit_free_cpath_node(victim);
  1059. }
  1060. log_info(LD_CIRC, "finished");
  1061. return 0;
  1062. #endif
  1063. }
  1064. /** Given a response payload and keys, initialize, then send a created
  1065. * cell back.
  1066. */
  1067. int
  1068. onionskin_answer(or_circuit_t *circ,
  1069. const created_cell_t *created_cell,
  1070. const char *keys,
  1071. const uint8_t *rend_circ_nonce)
  1072. {
  1073. cell_t cell;
  1074. crypt_path_t *tmp_cpath;
  1075. if (created_cell_format(&cell, created_cell) < 0) {
  1076. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1077. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1078. return -1;
  1079. }
  1080. cell.circ_id = circ->p_circ_id;
  1081. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1082. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1083. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1084. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1085. (unsigned int)get_uint32(keys),
  1086. (unsigned int)get_uint32(keys+20));
  1087. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1088. log_warn(LD_BUG,"Circuit initialization failed");
  1089. tor_free(tmp_cpath);
  1090. return -1;
  1091. }
  1092. circ->n_digest = tmp_cpath->f_digest;
  1093. circ->n_crypto = tmp_cpath->f_crypto;
  1094. circ->p_digest = tmp_cpath->b_digest;
  1095. circ->p_crypto = tmp_cpath->b_crypto;
  1096. tmp_cpath->magic = 0;
  1097. tor_free(tmp_cpath);
  1098. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1099. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1100. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1101. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1102. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1103. circ->is_first_hop ? "created_fast" : "created");
  1104. if (!channel_is_local(circ->p_chan) &&
  1105. !channel_is_outgoing(circ->p_chan)) {
  1106. /* record that we could process create cells from a non-local conn
  1107. * that we didn't initiate; presumably this means that create cells
  1108. * can reach us too. */
  1109. router_orport_found_reachable();
  1110. }
  1111. return 0;
  1112. }
  1113. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  1114. * number of endpoints that would give something away about our destination.
  1115. *
  1116. * If the routerlist <b>nodes</b> doesn't have enough routers
  1117. * to handle the desired path length, return -1.
  1118. */
  1119. static int
  1120. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  1121. {
  1122. int num_acceptable_routers;
  1123. int routelen;
  1124. tor_assert(nodes);
  1125. routelen = DEFAULT_ROUTE_LEN;
  1126. if (exit &&
  1127. purpose != CIRCUIT_PURPOSE_TESTING &&
  1128. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1129. routelen++;
  1130. num_acceptable_routers = count_acceptable_nodes(nodes);
  1131. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1132. routelen, num_acceptable_routers, smartlist_len(nodes));
  1133. if (num_acceptable_routers < routelen) {
  1134. log_info(LD_CIRC,
  1135. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1136. num_acceptable_routers, routelen);
  1137. return -1;
  1138. }
  1139. return routelen;
  1140. }
  1141. /** Return a newly allocated list of uint16_t * for each predicted port not
  1142. * handled by a current circuit. */
  1143. static smartlist_t *
  1144. circuit_get_unhandled_ports(time_t now)
  1145. {
  1146. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1147. circuit_remove_handled_ports(dest);
  1148. return dest;
  1149. }
  1150. /** Return 1 if we already have circuits present or on the way for
  1151. * all anticipated ports. Return 0 if we should make more.
  1152. *
  1153. * If we're returning 0, set need_uptime and need_capacity to
  1154. * indicate any requirements that the unhandled ports have.
  1155. */
  1156. int
  1157. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1158. int *need_capacity)
  1159. {
  1160. int i, enough;
  1161. uint16_t *port;
  1162. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1163. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1164. tor_assert(need_uptime);
  1165. tor_assert(need_capacity);
  1166. // Always predict need_capacity
  1167. *need_capacity = 1;
  1168. enough = (smartlist_len(sl) == 0);
  1169. for (i = 0; i < smartlist_len(sl); ++i) {
  1170. port = smartlist_get(sl, i);
  1171. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1172. *need_uptime = 1;
  1173. tor_free(port);
  1174. }
  1175. smartlist_free(sl);
  1176. return enough;
  1177. }
  1178. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1179. * <b>needed_ports</b>, else return 0.
  1180. */
  1181. static int
  1182. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1183. { /* XXXX MOVE */
  1184. int i;
  1185. uint16_t port;
  1186. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1187. addr_policy_result_t r;
  1188. /* alignment issues aren't a worry for this dereference, since
  1189. needed_ports is explicitly a smartlist of uint16_t's */
  1190. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1191. tor_assert(port);
  1192. if (node)
  1193. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1194. else
  1195. continue;
  1196. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1197. return 1;
  1198. }
  1199. return 0;
  1200. }
  1201. /** Return true iff <b>conn</b> needs another general circuit to be
  1202. * built. */
  1203. static int
  1204. ap_stream_wants_exit_attention(connection_t *conn)
  1205. {
  1206. entry_connection_t *entry;
  1207. if (conn->type != CONN_TYPE_AP)
  1208. return 0;
  1209. entry = TO_ENTRY_CONN(conn);
  1210. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1211. !conn->marked_for_close &&
  1212. !(entry->want_onehop) && /* ignore one-hop streams */
  1213. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1214. !(entry->chosen_exit_name) && /* ignore defined streams */
  1215. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1216. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1217. MIN_CIRCUITS_HANDLING_STREAM))
  1218. return 1;
  1219. return 0;
  1220. }
  1221. /** Return a pointer to a suitable router to be the exit node for the
  1222. * general-purpose circuit we're about to build.
  1223. *
  1224. * Look through the connection array, and choose a router that maximizes
  1225. * the number of pending streams that can exit from this router.
  1226. *
  1227. * Return NULL if we can't find any suitable routers.
  1228. */
  1229. static const node_t *
  1230. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1231. {
  1232. int *n_supported;
  1233. int n_pending_connections = 0;
  1234. smartlist_t *connections;
  1235. int best_support = -1;
  1236. int n_best_support=0;
  1237. const or_options_t *options = get_options();
  1238. const smartlist_t *the_nodes;
  1239. const node_t *node=NULL;
  1240. connections = get_connection_array();
  1241. /* Count how many connections are waiting for a circuit to be built.
  1242. * We use this for log messages now, but in the future we may depend on it.
  1243. */
  1244. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1245. {
  1246. if (ap_stream_wants_exit_attention(conn))
  1247. ++n_pending_connections;
  1248. });
  1249. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1250. // n_pending_connections);
  1251. /* Now we count, for each of the routers in the directory, how many
  1252. * of the pending connections could possibly exit from that
  1253. * router (n_supported[i]). (We can't be sure about cases where we
  1254. * don't know the IP address of the pending connection.)
  1255. *
  1256. * -1 means "Don't use this router at all."
  1257. */
  1258. the_nodes = nodelist_get_list();
  1259. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1260. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1261. const int i = node_sl_idx;
  1262. if (router_digest_is_me(node->identity)) {
  1263. n_supported[i] = -1;
  1264. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1265. /* XXX there's probably a reverse predecessor attack here, but
  1266. * it's slow. should we take this out? -RD
  1267. */
  1268. continue;
  1269. }
  1270. if (!node_has_descriptor(node)) {
  1271. n_supported[i] = -1;
  1272. continue;
  1273. }
  1274. if (!node->is_running || node->is_bad_exit) {
  1275. n_supported[i] = -1;
  1276. continue; /* skip routers that are known to be down or bad exits */
  1277. }
  1278. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1279. /* never pick a non-general node as a random exit. */
  1280. n_supported[i] = -1;
  1281. continue;
  1282. }
  1283. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1284. n_supported[i] = -1;
  1285. continue; /* user asked us not to use it, no matter what */
  1286. }
  1287. if (options->ExitNodes &&
  1288. !routerset_contains_node(options->ExitNodes, node)) {
  1289. n_supported[i] = -1;
  1290. continue; /* not one of our chosen exit nodes */
  1291. }
  1292. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1293. n_supported[i] = -1;
  1294. continue; /* skip routers that are not suitable. Don't worry if
  1295. * this makes us reject all the possible routers: if so,
  1296. * we'll retry later in this function with need_update and
  1297. * need_capacity set to 0. */
  1298. }
  1299. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1300. /* if it's invalid and we don't want it */
  1301. n_supported[i] = -1;
  1302. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1303. // router->nickname, i);
  1304. continue; /* skip invalid routers */
  1305. }
  1306. if (options->ExcludeSingleHopRelays &&
  1307. node_allows_single_hop_exits(node)) {
  1308. n_supported[i] = -1;
  1309. continue;
  1310. }
  1311. if (node_exit_policy_rejects_all(node)) {
  1312. n_supported[i] = -1;
  1313. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1314. // router->nickname, i);
  1315. continue; /* skip routers that reject all */
  1316. }
  1317. n_supported[i] = 0;
  1318. /* iterate over connections */
  1319. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1320. if (!ap_stream_wants_exit_attention(conn))
  1321. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1322. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1323. ++n_supported[i];
  1324. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1325. // router->nickname, i, n_supported[i]);
  1326. } else {
  1327. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1328. // router->nickname, i);
  1329. }
  1330. } SMARTLIST_FOREACH_END(conn);
  1331. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1332. /* Leave best_support at -1 if that's where it is, so we can
  1333. * distinguish it later. */
  1334. continue;
  1335. }
  1336. if (n_supported[i] > best_support) {
  1337. /* If this router is better than previous ones, remember its index
  1338. * and goodness, and start counting how many routers are this good. */
  1339. best_support = n_supported[i]; n_best_support=1;
  1340. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1341. // router->nickname);
  1342. } else if (n_supported[i] == best_support) {
  1343. /* If this router is _as good_ as the best one, just increment the
  1344. * count of equally good routers.*/
  1345. ++n_best_support;
  1346. }
  1347. } SMARTLIST_FOREACH_END(node);
  1348. log_info(LD_CIRC,
  1349. "Found %d servers that might support %d/%d pending connections.",
  1350. n_best_support, best_support >= 0 ? best_support : 0,
  1351. n_pending_connections);
  1352. /* If any routers definitely support any pending connections, choose one
  1353. * at random. */
  1354. if (best_support > 0) {
  1355. smartlist_t *supporting = smartlist_new();
  1356. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1357. if (n_supported[node_sl_idx] == best_support)
  1358. smartlist_add(supporting, (void*)node);
  1359. });
  1360. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1361. smartlist_free(supporting);
  1362. } else {
  1363. /* Either there are no pending connections, or no routers even seem to
  1364. * possibly support any of them. Choose a router at random that satisfies
  1365. * at least one predicted exit port. */
  1366. int attempt;
  1367. smartlist_t *needed_ports, *supporting;
  1368. if (best_support == -1) {
  1369. if (need_uptime || need_capacity) {
  1370. log_info(LD_CIRC,
  1371. "We couldn't find any live%s%s routers; falling back "
  1372. "to list of all routers.",
  1373. need_capacity?", fast":"",
  1374. need_uptime?", stable":"");
  1375. tor_free(n_supported);
  1376. return choose_good_exit_server_general(0, 0);
  1377. }
  1378. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1379. "choosing a doomed exit at random.",
  1380. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1381. }
  1382. supporting = smartlist_new();
  1383. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1384. for (attempt = 0; attempt < 2; attempt++) {
  1385. /* try once to pick only from routers that satisfy a needed port,
  1386. * then if there are none, pick from any that support exiting. */
  1387. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1388. if (n_supported[node_sl_idx] != -1 &&
  1389. (attempt || node_handles_some_port(node, needed_ports))) {
  1390. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1391. // try, router->nickname);
  1392. smartlist_add(supporting, (void*)node);
  1393. }
  1394. } SMARTLIST_FOREACH_END(node);
  1395. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1396. if (node)
  1397. break;
  1398. smartlist_clear(supporting);
  1399. /* If we reach this point, we can't actually support any unhandled
  1400. * predicted ports, so clear all the remaining ones. */
  1401. if (smartlist_len(needed_ports))
  1402. rep_hist_remove_predicted_ports(needed_ports);
  1403. }
  1404. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1405. smartlist_free(needed_ports);
  1406. smartlist_free(supporting);
  1407. }
  1408. tor_free(n_supported);
  1409. if (node) {
  1410. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1411. return node;
  1412. }
  1413. if (options->ExitNodes) {
  1414. log_warn(LD_CIRC,
  1415. "No specified %sexit routers seem to be running: "
  1416. "can't choose an exit.",
  1417. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1418. }
  1419. return NULL;
  1420. }
  1421. /** Return a pointer to a suitable router to be the exit node for the
  1422. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1423. * if no router is suitable).
  1424. *
  1425. * For general-purpose circuits, pass it off to
  1426. * choose_good_exit_server_general()
  1427. *
  1428. * For client-side rendezvous circuits, choose a random node, weighted
  1429. * toward the preferences in 'options'.
  1430. */
  1431. static const node_t *
  1432. choose_good_exit_server(uint8_t purpose,
  1433. int need_uptime, int need_capacity, int is_internal)
  1434. {
  1435. const or_options_t *options = get_options();
  1436. router_crn_flags_t flags = CRN_NEED_DESC;
  1437. if (need_uptime)
  1438. flags |= CRN_NEED_UPTIME;
  1439. if (need_capacity)
  1440. flags |= CRN_NEED_CAPACITY;
  1441. switch (purpose) {
  1442. case CIRCUIT_PURPOSE_C_GENERAL:
  1443. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1444. flags |= CRN_ALLOW_INVALID;
  1445. if (is_internal) /* pick it like a middle hop */
  1446. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1447. else
  1448. return choose_good_exit_server_general(need_uptime,need_capacity);
  1449. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1450. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1451. flags |= CRN_ALLOW_INVALID;
  1452. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1453. }
  1454. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1455. tor_fragile_assert();
  1456. return NULL;
  1457. }
  1458. /** Log a warning if the user specified an exit for the circuit that
  1459. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1460. static void
  1461. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1462. {
  1463. const or_options_t *options = get_options();
  1464. routerset_t *rs = options->ExcludeNodes;
  1465. const char *description;
  1466. uint8_t purpose = circ->base_.purpose;
  1467. if (circ->build_state->onehop_tunnel)
  1468. return;
  1469. switch (purpose)
  1470. {
  1471. default:
  1472. case CIRCUIT_PURPOSE_OR:
  1473. case CIRCUIT_PURPOSE_INTRO_POINT:
  1474. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1475. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1476. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1477. (int)purpose,
  1478. circuit_purpose_to_string(purpose));
  1479. return;
  1480. case CIRCUIT_PURPOSE_C_GENERAL:
  1481. if (circ->build_state->is_internal)
  1482. return;
  1483. description = "requested exit node";
  1484. rs = options->ExcludeExitNodesUnion_;
  1485. break;
  1486. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1487. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1488. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1489. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1490. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1491. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1492. case CIRCUIT_PURPOSE_TESTING:
  1493. return;
  1494. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1495. case CIRCUIT_PURPOSE_C_REND_READY:
  1496. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1497. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1498. description = "chosen rendezvous point";
  1499. break;
  1500. case CIRCUIT_PURPOSE_CONTROLLER:
  1501. rs = options->ExcludeExitNodesUnion_;
  1502. description = "controller-selected circuit target";
  1503. break;
  1504. }
  1505. if (routerset_contains_extendinfo(rs, exit)) {
  1506. /* We should never get here if StrictNodes is set to 1. */
  1507. if (options->StrictNodes) {
  1508. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1509. "even though StrictNodes is set. Please report. "
  1510. "(Circuit purpose: %s)",
  1511. description, extend_info_describe(exit),
  1512. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1513. circuit_purpose_to_string(purpose));
  1514. } else {
  1515. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1516. "ExcludeNodes%s, because no better options were available. To "
  1517. "prevent this (and possibly break your Tor functionality), "
  1518. "set the StrictNodes configuration option. "
  1519. "(Circuit purpose: %s)",
  1520. description, extend_info_describe(exit),
  1521. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1522. circuit_purpose_to_string(purpose));
  1523. }
  1524. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1525. }
  1526. return;
  1527. }
  1528. /** Decide a suitable length for circ's cpath, and pick an exit
  1529. * router (or use <b>exit</b> if provided). Store these in the
  1530. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1531. static int
  1532. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1533. {
  1534. cpath_build_state_t *state = circ->build_state;
  1535. if (state->onehop_tunnel) {
  1536. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1537. state->desired_path_len = 1;
  1538. } else {
  1539. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1540. if (r < 1) /* must be at least 1 */
  1541. return -1;
  1542. state->desired_path_len = r;
  1543. }
  1544. if (exit) { /* the circuit-builder pre-requested one */
  1545. warn_if_last_router_excluded(circ, exit);
  1546. log_info(LD_CIRC,"Using requested exit node '%s'",
  1547. extend_info_describe(exit));
  1548. exit = extend_info_dup(exit);
  1549. } else { /* we have to decide one */
  1550. const node_t *node =
  1551. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1552. state->need_capacity, state->is_internal);
  1553. if (!node) {
  1554. log_warn(LD_CIRC,"failed to choose an exit server");
  1555. return -1;
  1556. }
  1557. exit = extend_info_from_node(node, 0);
  1558. tor_assert(exit);
  1559. }
  1560. state->chosen_exit = exit;
  1561. return 0;
  1562. }
  1563. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1564. * hop to the cpath reflecting this. Don't send the next extend cell --
  1565. * the caller will do this if it wants to.
  1566. */
  1567. int
  1568. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1569. {
  1570. cpath_build_state_t *state;
  1571. tor_assert(exit);
  1572. tor_assert(circ);
  1573. state = circ->build_state;
  1574. tor_assert(state);
  1575. extend_info_free(state->chosen_exit);
  1576. state->chosen_exit = extend_info_dup(exit);
  1577. ++circ->build_state->desired_path_len;
  1578. onion_append_hop(&circ->cpath, exit);
  1579. return 0;
  1580. }
  1581. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1582. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1583. * send the next extend cell to begin connecting to that hop.
  1584. */
  1585. int
  1586. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1587. {
  1588. int err_reason = 0;
  1589. warn_if_last_router_excluded(circ, exit);
  1590. tor_gettimeofday(&circ->base_.timestamp_began);
  1591. circuit_append_new_exit(circ, exit);
  1592. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1593. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1594. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1595. extend_info_describe(exit));
  1596. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1597. return -1;
  1598. }
  1599. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  1600. return 0;
  1601. }
  1602. /** Return the number of routers in <b>routers</b> that are currently up
  1603. * and available for building circuits through.
  1604. */
  1605. static int
  1606. count_acceptable_nodes(smartlist_t *nodes)
  1607. {
  1608. int num=0;
  1609. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1610. // log_debug(LD_CIRC,
  1611. // "Contemplating whether router %d (%s) is a new option.",
  1612. // i, r->nickname);
  1613. if (! node->is_running)
  1614. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1615. continue;
  1616. if (! node->is_valid)
  1617. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1618. continue;
  1619. if (! node_has_descriptor(node))
  1620. continue;
  1621. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1622. * allows this node in some places, then we're getting an inaccurate
  1623. * count. For now, be conservative and don't count it. But later we
  1624. * should try to be smarter. */
  1625. ++num;
  1626. } SMARTLIST_FOREACH_END(node);
  1627. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1628. return num;
  1629. }
  1630. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1631. * This function is used to extend cpath by another hop.
  1632. */
  1633. void
  1634. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1635. {
  1636. if (*head_ptr) {
  1637. new_hop->next = (*head_ptr);
  1638. new_hop->prev = (*head_ptr)->prev;
  1639. (*head_ptr)->prev->next = new_hop;
  1640. (*head_ptr)->prev = new_hop;
  1641. } else {
  1642. *head_ptr = new_hop;
  1643. new_hop->prev = new_hop->next = new_hop;
  1644. }
  1645. }
  1646. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1647. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1648. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1649. * circuit. In particular, make sure we don't pick the exit node or its
  1650. * family, and make sure we don't duplicate any previous nodes or their
  1651. * families. */
  1652. static const node_t *
  1653. choose_good_middle_server(uint8_t purpose,
  1654. cpath_build_state_t *state,
  1655. crypt_path_t *head,
  1656. int cur_len)
  1657. {
  1658. int i;
  1659. const node_t *r, *choice;
  1660. crypt_path_t *cpath;
  1661. smartlist_t *excluded;
  1662. const or_options_t *options = get_options();
  1663. router_crn_flags_t flags = CRN_NEED_DESC;
  1664. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1665. purpose <= CIRCUIT_PURPOSE_MAX_);
  1666. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1667. excluded = smartlist_new();
  1668. if ((r = build_state_get_exit_node(state))) {
  1669. nodelist_add_node_and_family(excluded, r);
  1670. }
  1671. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1672. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1673. nodelist_add_node_and_family(excluded, r);
  1674. }
  1675. }
  1676. if (state->need_uptime)
  1677. flags |= CRN_NEED_UPTIME;
  1678. if (state->need_capacity)
  1679. flags |= CRN_NEED_CAPACITY;
  1680. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1681. flags |= CRN_ALLOW_INVALID;
  1682. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1683. smartlist_free(excluded);
  1684. return choice;
  1685. }
  1686. /** Pick a good entry server for the circuit to be built according to
  1687. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1688. * router (if we're an OR), and respect firewall settings; if we're
  1689. * configured to use entry guards, return one.
  1690. *
  1691. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1692. * guard, not for any particular circuit.
  1693. */
  1694. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1695. const node_t *
  1696. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1697. {
  1698. const node_t *choice;
  1699. smartlist_t *excluded;
  1700. const or_options_t *options = get_options();
  1701. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1702. const node_t *node;
  1703. if (state && options->UseEntryGuards &&
  1704. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1705. /* This request is for an entry server to use for a regular circuit,
  1706. * and we use entry guard nodes. Just return one of the guard nodes. */
  1707. return choose_random_entry(state);
  1708. }
  1709. excluded = smartlist_new();
  1710. if (state && (node = build_state_get_exit_node(state))) {
  1711. /* Exclude the exit node from the state, if we have one. Also exclude its
  1712. * family. */
  1713. nodelist_add_node_and_family(excluded, node);
  1714. }
  1715. if (firewall_is_fascist_or()) {
  1716. /* Exclude all ORs that we can't reach through our firewall */
  1717. smartlist_t *nodes = nodelist_get_list();
  1718. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1719. if (!fascist_firewall_allows_node(node))
  1720. smartlist_add(excluded, (void*)node);
  1721. });
  1722. }
  1723. /* and exclude current entry guards and their families, if applicable */
  1724. /*XXXX025 use the using_as_guard flag to accomplish this.*/
  1725. if (options->UseEntryGuards) {
  1726. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1727. {
  1728. if ((node = node_get_by_id(entry->identity))) {
  1729. nodelist_add_node_and_family(excluded, node);
  1730. }
  1731. });
  1732. }
  1733. if (state) {
  1734. if (state->need_uptime)
  1735. flags |= CRN_NEED_UPTIME;
  1736. if (state->need_capacity)
  1737. flags |= CRN_NEED_CAPACITY;
  1738. }
  1739. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1740. flags |= CRN_ALLOW_INVALID;
  1741. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1742. smartlist_free(excluded);
  1743. return choice;
  1744. }
  1745. /** Return the first non-open hop in cpath, or return NULL if all
  1746. * hops are open. */
  1747. static crypt_path_t *
  1748. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1749. {
  1750. crypt_path_t *hop = cpath;
  1751. do {
  1752. if (hop->state != CPATH_STATE_OPEN)
  1753. return hop;
  1754. hop = hop->next;
  1755. } while (hop != cpath);
  1756. return NULL;
  1757. }
  1758. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1759. * based on <b>state</b>. Append the hop info to head_ptr.
  1760. */
  1761. static int
  1762. onion_extend_cpath(origin_circuit_t *circ)
  1763. {
  1764. uint8_t purpose = circ->base_.purpose;
  1765. cpath_build_state_t *state = circ->build_state;
  1766. int cur_len = circuit_get_cpath_len(circ);
  1767. extend_info_t *info = NULL;
  1768. if (cur_len >= state->desired_path_len) {
  1769. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1770. state->desired_path_len);
  1771. return 1;
  1772. }
  1773. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1774. state->desired_path_len);
  1775. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1776. info = extend_info_dup(state->chosen_exit);
  1777. } else if (cur_len == 0) { /* picking first node */
  1778. const node_t *r = choose_good_entry_server(purpose, state);
  1779. if (r) {
  1780. /* If we're a client, use the preferred address rather than the
  1781. primary address, for potentially connecting to an IPv6 OR
  1782. port. */
  1783. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  1784. tor_assert(info);
  1785. }
  1786. } else {
  1787. const node_t *r =
  1788. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1789. if (r) {
  1790. info = extend_info_from_node(r, 0);
  1791. tor_assert(info);
  1792. }
  1793. }
  1794. if (!info) {
  1795. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1796. "this circuit.", cur_len);
  1797. return -1;
  1798. }
  1799. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1800. extend_info_describe(info),
  1801. cur_len+1, build_state_get_exit_nickname(state));
  1802. onion_append_hop(&circ->cpath, info);
  1803. extend_info_free(info);
  1804. return 0;
  1805. }
  1806. /** Create a new hop, annotate it with information about its
  1807. * corresponding router <b>choice</b>, and append it to the
  1808. * end of the cpath <b>head_ptr</b>. */
  1809. static int
  1810. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1811. {
  1812. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1813. /* link hop into the cpath, at the end. */
  1814. onion_append_to_cpath(head_ptr, hop);
  1815. hop->magic = CRYPT_PATH_MAGIC;
  1816. hop->state = CPATH_STATE_CLOSED;
  1817. hop->extend_info = extend_info_dup(choice);
  1818. hop->package_window = circuit_initial_package_window();
  1819. hop->deliver_window = CIRCWINDOW_START;
  1820. return 0;
  1821. }
  1822. /** Allocate a new extend_info object based on the various arguments. */
  1823. extend_info_t *
  1824. extend_info_new(const char *nickname, const char *digest,
  1825. crypto_pk_t *onion_key,
  1826. const curve25519_public_key_t *curve25519_key,
  1827. const tor_addr_t *addr, uint16_t port)
  1828. {
  1829. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1830. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1831. if (nickname)
  1832. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1833. if (onion_key)
  1834. info->onion_key = crypto_pk_dup_key(onion_key);
  1835. #ifdef CURVE25519_ENABLED
  1836. if (curve25519_key)
  1837. memcpy(&info->curve25519_onion_key, curve25519_key,
  1838. sizeof(curve25519_public_key_t));
  1839. #else
  1840. (void)curve25519_key;
  1841. #endif
  1842. tor_addr_copy(&info->addr, addr);
  1843. info->port = port;
  1844. return info;
  1845. }
  1846. /** Allocate and return a new extend_info that can be used to build a
  1847. * circuit to or through the node <b>node</b>. Use the primary address
  1848. * of the node (i.e. its IPv4 address) unless
  1849. * <b>for_direct_connect</b> is true, in which case the preferred
  1850. * address is used instead. May return NULL if there is not enough
  1851. * info about <b>node</b> to extend to it--for example, if there is no
  1852. * routerinfo_t or microdesc_t.
  1853. **/
  1854. extend_info_t *
  1855. extend_info_from_node(const node_t *node, int for_direct_connect)
  1856. {
  1857. tor_addr_port_t ap;
  1858. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  1859. return NULL;
  1860. if (for_direct_connect)
  1861. node_get_pref_orport(node, &ap);
  1862. else
  1863. node_get_prim_orport(node, &ap);
  1864. log_debug(LD_CIRC, "using %s for %s",
  1865. fmt_addrport(&ap.addr, ap.port),
  1866. node->ri ? node->ri->nickname : node->rs->nickname);
  1867. if (node->ri)
  1868. return extend_info_new(node->ri->nickname,
  1869. node->identity,
  1870. node->ri->onion_pkey,
  1871. node->ri->onion_curve25519_pkey,
  1872. &ap.addr,
  1873. ap.port);
  1874. else if (node->rs && node->md)
  1875. return extend_info_new(node->rs->nickname,
  1876. node->identity,
  1877. node->md->onion_pkey,
  1878. node->md->onion_curve25519_pkey,
  1879. &ap.addr,
  1880. ap.port);
  1881. else
  1882. return NULL;
  1883. }
  1884. /** Release storage held by an extend_info_t struct. */
  1885. void
  1886. extend_info_free(extend_info_t *info)
  1887. {
  1888. if (!info)
  1889. return;
  1890. crypto_pk_free(info->onion_key);
  1891. tor_free(info);
  1892. }
  1893. /** Allocate and return a new extend_info_t with the same contents as
  1894. * <b>info</b>. */
  1895. extend_info_t *
  1896. extend_info_dup(extend_info_t *info)
  1897. {
  1898. extend_info_t *newinfo;
  1899. tor_assert(info);
  1900. newinfo = tor_malloc(sizeof(extend_info_t));
  1901. memcpy(newinfo, info, sizeof(extend_info_t));
  1902. if (info->onion_key)
  1903. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1904. else
  1905. newinfo->onion_key = NULL;
  1906. return newinfo;
  1907. }
  1908. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1909. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1910. * the chosen exit, return NULL.
  1911. */
  1912. const node_t *
  1913. build_state_get_exit_node(cpath_build_state_t *state)
  1914. {
  1915. if (!state || !state->chosen_exit)
  1916. return NULL;
  1917. return node_get_by_id(state->chosen_exit->identity_digest);
  1918. }
  1919. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1920. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1921. * chosen exit, return NULL.
  1922. */
  1923. const char *
  1924. build_state_get_exit_nickname(cpath_build_state_t *state)
  1925. {
  1926. if (!state || !state->chosen_exit)
  1927. return NULL;
  1928. return state->chosen_exit->nickname;
  1929. }