circuitbuild.c 105 KB

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