circuitbuild.c 89 KB

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