circuitbuild.c 104 KB

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