circuitbuild.c 87 KB

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