circuitbuild.c 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #include "or.h"
  11. #include "channel.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuitstats.h"
  15. #include "circuituse.h"
  16. #include "command.h"
  17. #include "config.h"
  18. #include "confparse.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "directory.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "onion.h"
  29. #include "onion_tap.h"
  30. #include "onion_fast.h"
  31. #include "policies.h"
  32. #include "transports.h"
  33. #include "relay.h"
  34. #include "rephist.h"
  35. #include "router.h"
  36. #include "routerlist.h"
  37. #include "routerparse.h"
  38. #include "routerset.h"
  39. #include "crypto.h"
  40. #include "connection_edge.h"
  41. #ifndef MIN
  42. #define MIN(a,b) ((a)<(b)?(a):(b))
  43. #endif
  44. /********* START VARIABLES **********/
  45. /** A global list of all circuits at this hop. */
  46. extern circuit_t *global_circuitlist;
  47. /********* END VARIABLES ************/
  48. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  49. uint16_t port,
  50. const char *id_digest);
  51. static int circuit_deliver_create_cell(circuit_t *circ,
  52. const create_cell_t *create_cell,
  53. int relayed);
  54. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  55. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  56. static int onion_extend_cpath(origin_circuit_t *circ);
  57. static int count_acceptable_nodes(smartlist_t *routers);
  58. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  59. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  60. static void pathbias_count_build_success(origin_circuit_t *circ);
  61. static void pathbias_count_successful_close(origin_circuit_t *circ);
  62. static void pathbias_count_collapse(origin_circuit_t *circ);
  63. static void pathbias_count_use_failed(origin_circuit_t *circ);
  64. static int pathbias_check_use_rate(entry_guard_t *guard);
  65. static int pathbias_check_close_rate(entry_guard_t *guard);
  66. /** This function tries to get a channel to the specified endpoint,
  67. * and then calls command_setup_channel() to give it the right
  68. * callbacks.
  69. */
  70. static channel_t *
  71. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  72. const char *id_digest)
  73. {
  74. channel_t *chan;
  75. chan = channel_connect(addr, port, id_digest);
  76. if (chan) command_setup_channel(chan);
  77. return chan;
  78. }
  79. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  80. * and with the high bit specified by conn-\>circ_id_type, until we get
  81. * a circ_id that is not in use by any other circuit on that conn.
  82. *
  83. * Return it, or 0 if can't get a unique circ_id.
  84. */
  85. static circid_t
  86. get_unique_circ_id_by_chan(channel_t *chan)
  87. {
  88. circid_t test_circ_id;
  89. circid_t attempts=0;
  90. circid_t high_bit;
  91. tor_assert(chan);
  92. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  93. log_warn(LD_BUG,
  94. "Trying to pick a circuit ID for a connection from "
  95. "a client with no identity.");
  96. return 0;
  97. }
  98. high_bit =
  99. (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  100. do {
  101. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  102. * circID such that (high_bit|test_circ_id) is not already used. */
  103. test_circ_id = chan->next_circ_id++;
  104. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  105. test_circ_id = 1;
  106. chan->next_circ_id = 2;
  107. }
  108. if (++attempts > 1<<15) {
  109. /* Make sure we don't loop forever if all circ_id's are used. This
  110. * matters because it's an external DoS opportunity.
  111. */
  112. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  113. return 0;
  114. }
  115. test_circ_id |= high_bit;
  116. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  117. return test_circ_id;
  118. }
  119. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  120. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  121. * list information about link status in a more verbose format using spaces.
  122. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  123. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  124. * names.
  125. */
  126. static char *
  127. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  128. {
  129. crypt_path_t *hop;
  130. smartlist_t *elements;
  131. const char *states[] = {"closed", "waiting for keys", "open"};
  132. char *s;
  133. elements = smartlist_new();
  134. if (verbose) {
  135. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  136. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  137. circ->build_state->is_internal ? "internal" : "exit",
  138. circ->build_state->need_uptime ? " (high-uptime)" : "",
  139. circ->build_state->desired_path_len,
  140. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  141. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  142. (nickname?nickname:"*unnamed*"));
  143. }
  144. hop = circ->cpath;
  145. do {
  146. char *elt;
  147. const char *id;
  148. const node_t *node;
  149. if (!hop)
  150. break;
  151. if (!verbose && hop->state != CPATH_STATE_OPEN)
  152. break;
  153. if (!hop->extend_info)
  154. break;
  155. id = hop->extend_info->identity_digest;
  156. if (verbose_names) {
  157. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  158. if ((node = node_get_by_id(id))) {
  159. node_get_verbose_nickname(node, elt);
  160. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  161. elt[0] = '$';
  162. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  163. elt[HEX_DIGEST_LEN+1]= '~';
  164. strlcpy(elt+HEX_DIGEST_LEN+2,
  165. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  166. } else {
  167. elt[0] = '$';
  168. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  169. }
  170. } else { /* ! verbose_names */
  171. node = node_get_by_id(id);
  172. if (node && node_is_named(node)) {
  173. elt = tor_strdup(node_get_nickname(node));
  174. } else {
  175. elt = tor_malloc(HEX_DIGEST_LEN+2);
  176. elt[0] = '$';
  177. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  178. }
  179. }
  180. tor_assert(elt);
  181. if (verbose) {
  182. tor_assert(hop->state <= 2);
  183. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  184. tor_free(elt);
  185. } else {
  186. smartlist_add(elements, elt);
  187. }
  188. hop = hop->next;
  189. } while (hop != circ->cpath);
  190. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  191. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  192. smartlist_free(elements);
  193. return s;
  194. }
  195. /** If <b>verbose</b> is false, allocate and return a comma-separated
  196. * list of the currently built elements of <b>circ</b>. If
  197. * <b>verbose</b> is true, also list information about link status in
  198. * a more verbose format using spaces.
  199. */
  200. char *
  201. circuit_list_path(origin_circuit_t *circ, int verbose)
  202. {
  203. return circuit_list_path_impl(circ, verbose, 0);
  204. }
  205. /** Allocate and return a comma-separated list of the currently built elements
  206. * of <b>circ</b>, giving each as a verbose nickname.
  207. */
  208. char *
  209. circuit_list_path_for_controller(origin_circuit_t *circ)
  210. {
  211. return circuit_list_path_impl(circ, 0, 1);
  212. }
  213. /** Log, at severity <b>severity</b>, the nicknames of each router in
  214. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  215. * exit point.
  216. */
  217. void
  218. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  219. {
  220. char *s = circuit_list_path(circ,1);
  221. tor_log(severity,domain,"%s",s);
  222. tor_free(s);
  223. }
  224. /** Tell the rep(utation)hist(ory) module about the status of the links
  225. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  226. * extended; the _first_ hop that isn't open (if any) is marked as
  227. * unable to extend.
  228. */
  229. /* XXXX Someday we should learn from OR circuits too. */
  230. void
  231. circuit_rep_hist_note_result(origin_circuit_t *circ)
  232. {
  233. crypt_path_t *hop;
  234. const char *prev_digest = NULL;
  235. hop = circ->cpath;
  236. if (!hop) /* circuit hasn't started building yet. */
  237. return;
  238. if (server_mode(get_options())) {
  239. const routerinfo_t *me = router_get_my_routerinfo();
  240. if (!me)
  241. return;
  242. prev_digest = me->cache_info.identity_digest;
  243. }
  244. do {
  245. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  246. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  247. if (prev_digest) {
  248. if (hop->state == CPATH_STATE_OPEN)
  249. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  250. else {
  251. rep_hist_note_extend_failed(prev_digest, node->identity);
  252. break;
  253. }
  254. }
  255. prev_digest = node->identity;
  256. } else {
  257. prev_digest = NULL;
  258. }
  259. hop=hop->next;
  260. } while (hop!=circ->cpath);
  261. }
  262. /** Pick all the entries in our cpath. Stop and return 0 when we're
  263. * happy, or return -1 if an error occurs. */
  264. static int
  265. onion_populate_cpath(origin_circuit_t *circ)
  266. {
  267. int r;
  268. again:
  269. r = onion_extend_cpath(circ);
  270. if (r < 0) {
  271. log_info(LD_CIRC,"Generating cpath hop failed.");
  272. return -1;
  273. }
  274. if (r == 0)
  275. goto again;
  276. return 0; /* if r == 1 */
  277. }
  278. /** Create and return a new origin circuit. Initialize its purpose and
  279. * build-state based on our arguments. The <b>flags</b> argument is a
  280. * bitfield of CIRCLAUNCH_* flags. */
  281. origin_circuit_t *
  282. origin_circuit_init(uint8_t purpose, int flags)
  283. {
  284. /* sets circ->p_circ_id and circ->p_chan */
  285. origin_circuit_t *circ = origin_circuit_new();
  286. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  287. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  288. circ->build_state->onehop_tunnel =
  289. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  290. circ->build_state->need_uptime =
  291. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  292. circ->build_state->need_capacity =
  293. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  294. circ->build_state->is_internal =
  295. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  296. circ->base_.purpose = purpose;
  297. return circ;
  298. }
  299. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  300. * is defined, then use that as your exit router, else choose a suitable
  301. * exit node.
  302. *
  303. * Also launch a connection to the first OR in the chosen path, if
  304. * it's not open already.
  305. */
  306. origin_circuit_t *
  307. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  308. {
  309. origin_circuit_t *circ;
  310. int err_reason = 0;
  311. circ = origin_circuit_init(purpose, flags);
  312. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  313. onion_populate_cpath(circ) < 0) {
  314. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  315. return NULL;
  316. }
  317. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  318. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  319. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  320. return NULL;
  321. }
  322. return circ;
  323. }
  324. /** Start establishing the first hop of our circuit. Figure out what
  325. * OR we should connect to, and if necessary start the connection to
  326. * it. If we're already connected, then send the 'create' cell.
  327. * Return 0 for ok, -reason if circ should be marked-for-close. */
  328. int
  329. circuit_handle_first_hop(origin_circuit_t *circ)
  330. {
  331. crypt_path_t *firsthop;
  332. channel_t *n_chan;
  333. int err_reason = 0;
  334. const char *msg = NULL;
  335. int should_launch = 0;
  336. firsthop = onion_next_hop_in_cpath(circ->cpath);
  337. tor_assert(firsthop);
  338. tor_assert(firsthop->extend_info);
  339. /* now see if we're already connected to the first OR in 'route' */
  340. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  341. fmt_addrport(&firsthop->extend_info->addr,
  342. firsthop->extend_info->port));
  343. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  344. &firsthop->extend_info->addr,
  345. &msg,
  346. &should_launch);
  347. if (!n_chan) {
  348. /* not currently connected in a useful way. */
  349. log_info(LD_CIRC, "Next router is %s: %s",
  350. safe_str_client(extend_info_describe(firsthop->extend_info)),
  351. msg?msg:"???");
  352. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  353. if (should_launch) {
  354. if (circ->build_state->onehop_tunnel)
  355. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  356. n_chan = channel_connect_for_circuit(
  357. &firsthop->extend_info->addr,
  358. firsthop->extend_info->port,
  359. firsthop->extend_info->identity_digest);
  360. if (!n_chan) { /* connect failed, forget the whole thing */
  361. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  362. return -END_CIRC_REASON_CONNECTFAILED;
  363. }
  364. }
  365. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  366. /* return success. The onion/circuit/etc will be taken care of
  367. * automatically (may already have been) whenever n_chan reaches
  368. * OR_CONN_STATE_OPEN.
  369. */
  370. return 0;
  371. } else { /* it's already open. use it. */
  372. tor_assert(!circ->base_.n_hop);
  373. circ->base_.n_chan = n_chan;
  374. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  375. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  376. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  377. return err_reason;
  378. }
  379. }
  380. return 0;
  381. }
  382. /** Find any circuits that are waiting on <b>or_conn</b> to become
  383. * open and get them to send their create cells forward.
  384. *
  385. * Status is 1 if connect succeeded, or 0 if connect failed.
  386. */
  387. void
  388. circuit_n_chan_done(channel_t *chan, int status)
  389. {
  390. smartlist_t *pending_circs;
  391. int err_reason = 0;
  392. tor_assert(chan);
  393. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  394. chan->nickname ? chan->nickname : "NULL",
  395. channel_get_canonical_remote_descr(chan), status);
  396. pending_circs = smartlist_new();
  397. circuit_get_all_pending_on_channel(pending_circs, chan);
  398. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  399. {
  400. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  401. * leaving them in in case it's possible for the status of a circuit to
  402. * change as we're going down the list. */
  403. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  404. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  405. continue;
  406. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  407. /* Look at addr/port. This is an unkeyed connection. */
  408. if (!channel_matches_extend_info(chan, circ->n_hop))
  409. continue;
  410. } else {
  411. /* We expected a key. See if it's the right one. */
  412. if (tor_memneq(chan->identity_digest,
  413. circ->n_hop->identity_digest, DIGEST_LEN))
  414. continue;
  415. }
  416. if (!status) { /* chan failed; close circ */
  417. log_info(LD_CIRC,"Channel failed; closing circ.");
  418. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  419. continue;
  420. }
  421. log_debug(LD_CIRC, "Found circ, sending create cell.");
  422. /* circuit_deliver_create_cell will set n_circ_id and add us to
  423. * chan_circuid_circuit_map, so we don't need to call
  424. * set_circid_chan here. */
  425. circ->n_chan = chan;
  426. extend_info_free(circ->n_hop);
  427. circ->n_hop = NULL;
  428. if (CIRCUIT_IS_ORIGIN(circ)) {
  429. if ((err_reason =
  430. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  431. log_info(LD_CIRC,
  432. "send_next_onion_skin failed; circuit marked for closing.");
  433. circuit_mark_for_close(circ, -err_reason);
  434. continue;
  435. /* XXX could this be bad, eg if next_onion_skin failed because conn
  436. * died? */
  437. }
  438. } else {
  439. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  440. tor_assert(circ->n_chan_create_cell);
  441. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  442. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  443. continue;
  444. }
  445. tor_free(circ->n_chan_create_cell);
  446. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  447. }
  448. }
  449. SMARTLIST_FOREACH_END(circ);
  450. smartlist_free(pending_circs);
  451. }
  452. /** Find a new circid that isn't currently in use on the circ->n_chan
  453. * for the outgoing
  454. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  455. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  456. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  457. * it. Return -1 if we failed to find a suitable circid, else return 0.
  458. */
  459. static int
  460. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  461. int relayed)
  462. {
  463. cell_t cell;
  464. circid_t id;
  465. int r;
  466. tor_assert(circ);
  467. tor_assert(circ->n_chan);
  468. tor_assert(create_cell);
  469. tor_assert(create_cell->cell_type == CELL_CREATE ||
  470. create_cell->cell_type == CELL_CREATE_FAST ||
  471. create_cell->cell_type == CELL_CREATE2);
  472. id = get_unique_circ_id_by_chan(circ->n_chan);
  473. if (!id) {
  474. log_warn(LD_CIRC,"failed to get unique circID.");
  475. return -1;
  476. }
  477. log_debug(LD_CIRC,"Chosen circID %u.", id);
  478. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  479. memset(&cell, 0, sizeof(cell_t));
  480. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  481. : create_cell_format(&cell, create_cell);
  482. if (r < 0) {
  483. log_warn(LD_CIRC,"Couldn't format create cell");
  484. return -1;
  485. }
  486. cell.circ_id = circ->n_circ_id;
  487. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  488. CELL_DIRECTION_OUT, 0);
  489. if (CIRCUIT_IS_ORIGIN(circ)) {
  490. /* Update began timestamp for circuits starting their first hop */
  491. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  492. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  493. log_warn(LD_CIRC,
  494. "Got first hop for a circuit without an opened channel. "
  495. "State: %s.", channel_state_to_string(circ->n_chan->state));
  496. tor_fragile_assert();
  497. }
  498. tor_gettimeofday(&circ->timestamp_began);
  499. }
  500. /* mark it so it gets better rate limiting treatment. */
  501. channel_timestamp_client(circ->n_chan);
  502. }
  503. return 0;
  504. }
  505. /** We've decided to start our reachability testing. If all
  506. * is set, log this to the user. Return 1 if we did, or 0 if
  507. * we chose not to log anything. */
  508. int
  509. inform_testing_reachability(void)
  510. {
  511. char dirbuf[128];
  512. const routerinfo_t *me = router_get_my_routerinfo();
  513. if (!me)
  514. return 0;
  515. control_event_server_status(LOG_NOTICE,
  516. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  517. me->address, me->or_port);
  518. if (me->dir_port) {
  519. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  520. me->address, me->dir_port);
  521. control_event_server_status(LOG_NOTICE,
  522. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  523. me->address, me->dir_port);
  524. }
  525. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  526. "(this may take up to %d minutes -- look for log "
  527. "messages indicating success)",
  528. me->address, me->or_port,
  529. me->dir_port ? dirbuf : "",
  530. me->dir_port ? "are" : "is",
  531. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  532. return 1;
  533. }
  534. /** Return true iff we should send a create_fast cell to start building a given
  535. * circuit */
  536. static INLINE int
  537. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  538. {
  539. const or_options_t *options = get_options();
  540. tor_assert(circ->cpath);
  541. tor_assert(circ->cpath->extend_info);
  542. if (!circ->cpath->extend_info->onion_key)
  543. return 1; /* our hand is forced: only a create_fast will work. */
  544. if (!options->FastFirstHopPK)
  545. return 0; /* we prefer to avoid create_fast */
  546. if (public_server_mode(options)) {
  547. /* We're a server, and we know an onion key. We can choose.
  548. * Prefer to blend our circuit into the other circuits we are
  549. * creating on behalf of others. */
  550. return 0;
  551. }
  552. return 1;
  553. }
  554. /** Return true if <b>circ</b> is the type of circuit we want to count
  555. * timeouts from. In particular, we want it to have not completed yet
  556. * (already completing indicates we cannibalized it), and we want it to
  557. * have exactly three hops.
  558. */
  559. int
  560. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  561. {
  562. return !circ->has_opened
  563. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  564. }
  565. #ifdef CURVE25519_ENABLED
  566. /** Return true if the ntor handshake is enabled in the configuration, or if
  567. * it's been set to "auto" in the configuration and it's enabled in the
  568. * consensus. */
  569. static int
  570. circuits_can_use_ntor(void)
  571. {
  572. const or_options_t *options = get_options();
  573. if (options->UseNTorHandshake != -1)
  574. return options->UseNTorHandshake;
  575. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  576. }
  577. #endif
  578. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  579. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  580. * accordingly. */
  581. static void
  582. circuit_pick_create_handshake(uint8_t *cell_type_out,
  583. uint16_t *handshake_type_out,
  584. const extend_info_t *ei)
  585. {
  586. #ifdef CURVE25519_ENABLED
  587. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  588. CURVE25519_PUBKEY_LEN) &&
  589. circuits_can_use_ntor()) {
  590. *cell_type_out = CELL_CREATE2;
  591. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  592. return;
  593. }
  594. #else
  595. (void) ei;
  596. #endif
  597. *cell_type_out = CELL_CREATE;
  598. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  599. }
  600. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  601. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  602. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  603. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  604. * *<b>create_cell_type_out</b> accordingly. */
  605. static void
  606. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  607. uint8_t *create_cell_type_out,
  608. uint16_t *handshake_type_out,
  609. const node_t *node_prev,
  610. const extend_info_t *ei)
  611. {
  612. uint8_t t;
  613. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  614. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  615. * proxy for whether it can do extend2 cells; once a version that
  616. * handles extend2 cells is out, remove it. */
  617. if (node_prev &&
  618. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  619. (node_has_curve25519_onion_key(node_prev) ||
  620. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  621. *cell_type_out = RELAY_COMMAND_EXTEND2;
  622. *create_cell_type_out = CELL_CREATE2;
  623. } else {
  624. *cell_type_out = RELAY_COMMAND_EXTEND;
  625. *create_cell_type_out = CELL_CREATE;
  626. }
  627. }
  628. /** This is the backbone function for building circuits.
  629. *
  630. * If circ's first hop is closed, then we need to build a create
  631. * cell and send it forward.
  632. *
  633. * Otherwise, we need to build a relay extend cell and send it
  634. * forward.
  635. *
  636. * Return -reason if we want to tear down circ, else return 0.
  637. */
  638. int
  639. circuit_send_next_onion_skin(origin_circuit_t *circ)
  640. {
  641. crypt_path_t *hop;
  642. const node_t *node;
  643. tor_assert(circ);
  644. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  645. /* This is the first hop. */
  646. create_cell_t cc;
  647. int fast;
  648. int len;
  649. log_debug(LD_CIRC,"First skin; sending create cell.");
  650. memset(&cc, 0, sizeof(cc));
  651. if (circ->build_state->onehop_tunnel)
  652. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  653. else
  654. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  655. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  656. fast = should_use_create_fast_for_circuit(circ);
  657. if (!fast) {
  658. /* We are an OR and we know the right onion key: we should
  659. * send a create cell.
  660. */
  661. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  662. circ->cpath->extend_info);
  663. note_request("cell: create", 1);
  664. } else {
  665. /* We are not an OR, and we're building the first hop of a circuit to a
  666. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  667. * and a DH operation. */
  668. cc.cell_type = CELL_CREATE_FAST;
  669. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  670. note_request("cell: create fast", 1);
  671. }
  672. len = onion_skin_create(cc.handshake_type,
  673. circ->cpath->extend_info,
  674. &circ->cpath->handshake_state,
  675. cc.onionskin);
  676. if (len < 0) {
  677. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  678. return - END_CIRC_REASON_INTERNAL;
  679. }
  680. cc.handshake_len = len;
  681. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  682. return - END_CIRC_REASON_RESOURCELIMIT;
  683. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  684. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  685. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  686. fast ? "CREATE_FAST" : "CREATE",
  687. node ? node_describe(node) : "<unnamed>");
  688. } else {
  689. extend_cell_t ec;
  690. int len;
  691. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  692. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  693. log_debug(LD_CIRC,"starting to send subsequent skin.");
  694. hop = onion_next_hop_in_cpath(circ->cpath);
  695. memset(&ec, 0, sizeof(ec));
  696. if (!hop) {
  697. /* done building the circuit. whew. */
  698. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  699. if (circuit_timeout_want_to_count_circ(circ)) {
  700. struct timeval end;
  701. long timediff;
  702. tor_gettimeofday(&end);
  703. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  704. /*
  705. * If the circuit build time is much greater than we would have cut
  706. * it off at, we probably had a suspend event along this codepath,
  707. * and we should discard the value.
  708. */
  709. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  710. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  711. "Assuming clock jump. Purpose %d (%s)", timediff,
  712. circ->base_.purpose,
  713. circuit_purpose_to_string(circ->base_.purpose));
  714. } else if (!circuit_build_times_disabled()) {
  715. /* Only count circuit times if the network is live */
  716. if (circuit_build_times_network_check_live(&circ_times)) {
  717. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  718. circuit_build_times_set_timeout(&circ_times);
  719. }
  720. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  721. circuit_build_times_network_circ_success(&circ_times);
  722. }
  723. }
  724. }
  725. log_info(LD_CIRC,"circuit built!");
  726. circuit_reset_failure_count(0);
  727. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  728. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  729. }
  730. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  731. const or_options_t *options = get_options();
  732. can_complete_circuit=1;
  733. /* FFFF Log a count of known routers here */
  734. log_notice(LD_GENERAL,
  735. "Tor has successfully opened a circuit. "
  736. "Looks like client functionality is working.");
  737. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  738. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  739. clear_broken_connection_map(1);
  740. if (server_mode(options) && !check_whether_orport_reachable()) {
  741. inform_testing_reachability();
  742. consider_testing_reachability(1, 1);
  743. }
  744. }
  745. pathbias_count_build_success(circ);
  746. circuit_rep_hist_note_result(circ);
  747. circuit_has_opened(circ); /* do other actions as necessary */
  748. /* We're done with measurement circuits here. Just close them */
  749. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  750. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  751. }
  752. return 0;
  753. }
  754. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  755. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  756. return - END_CIRC_REASON_INTERNAL;
  757. }
  758. {
  759. const node_t *prev_node;
  760. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  761. circuit_pick_extend_handshake(&ec.cell_type,
  762. &ec.create_cell.cell_type,
  763. &ec.create_cell.handshake_type,
  764. prev_node,
  765. hop->extend_info);
  766. }
  767. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  768. ec.orport_ipv4.port = hop->extend_info->port;
  769. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  770. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  771. len = onion_skin_create(ec.create_cell.handshake_type,
  772. hop->extend_info,
  773. &hop->handshake_state,
  774. ec.create_cell.onionskin);
  775. if (len < 0) {
  776. log_warn(LD_CIRC,"onion_skin_create failed.");
  777. return - END_CIRC_REASON_INTERNAL;
  778. }
  779. ec.create_cell.handshake_len = len;
  780. log_info(LD_CIRC,"Sending extend relay cell.");
  781. note_request("cell: extend", 1);
  782. {
  783. uint8_t command = 0;
  784. uint16_t payload_len=0;
  785. uint8_t payload[RELAY_PAYLOAD_SIZE];
  786. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  787. log_warn(LD_CIRC,"Couldn't format extend cell");
  788. return -END_CIRC_REASON_INTERNAL;
  789. }
  790. /* send it to hop->prev, because it will transfer
  791. * it to a create cell and then send to hop */
  792. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  793. command,
  794. (char*)payload, payload_len,
  795. hop->prev) < 0)
  796. return 0; /* circuit is closed */
  797. }
  798. hop->state = CPATH_STATE_AWAITING_KEYS;
  799. }
  800. return 0;
  801. }
  802. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  803. * something has also gone wrong with our network: notify the user,
  804. * and abandon all not-yet-used circuits. */
  805. void
  806. circuit_note_clock_jumped(int seconds_elapsed)
  807. {
  808. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  809. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  810. "assuming established circuits no longer work.",
  811. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  812. seconds_elapsed >=0 ? "forward" : "backward");
  813. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  814. seconds_elapsed);
  815. can_complete_circuit=0; /* so it'll log when it works again */
  816. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  817. "CLOCK_JUMPED");
  818. circuit_mark_all_unused_circs();
  819. circuit_expire_all_dirty_circs();
  820. }
  821. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  822. * skin and identity digest for the next hop. If we're already connected,
  823. * pass the onion skin to the next hop using a create cell; otherwise
  824. * launch a new OR connection, and <b>circ</b> will notice when the
  825. * connection succeeds or fails.
  826. *
  827. * Return -1 if we want to warn and tear down the circuit, else return 0.
  828. */
  829. int
  830. circuit_extend(cell_t *cell, circuit_t *circ)
  831. {
  832. channel_t *n_chan;
  833. relay_header_t rh;
  834. extend_cell_t ec;
  835. const char *msg = NULL;
  836. int should_launch = 0;
  837. if (circ->n_chan) {
  838. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  839. "n_chan already set. Bug/attack. Closing.");
  840. return -1;
  841. }
  842. if (circ->n_hop) {
  843. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  844. "conn to next hop already launched. Bug/attack. Closing.");
  845. return -1;
  846. }
  847. if (!server_mode(get_options())) {
  848. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  849. "Got an extend cell, but running as a client. Closing.");
  850. return -1;
  851. }
  852. relay_header_unpack(&rh, cell->payload);
  853. if (extend_cell_parse(&ec, rh.command,
  854. cell->payload+RELAY_HEADER_SIZE,
  855. rh.length) < 0) {
  856. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  857. "Can't parse extend cell. Closing circuit.");
  858. return -1;
  859. }
  860. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  861. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  862. "Client asked me to extend to zero destination port or addr.");
  863. return -1;
  864. }
  865. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  866. !get_options()->ExtendAllowPrivateAddresses) {
  867. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  868. "Client asked me to extend to a private address");
  869. return -1;
  870. }
  871. /* Check if they asked us for 0000..0000. We support using
  872. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  873. * but we don't want to let people send us extend cells for empty
  874. * fingerprints -- a) because it opens the user up to a mitm attack,
  875. * and b) because it lets an attacker force the relay to hold open a
  876. * new TLS connection for each extend request. */
  877. if (tor_digest_is_zero((const char*)ec.node_id)) {
  878. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  879. "Client asked me to extend without specifying an id_digest.");
  880. return -1;
  881. }
  882. /* Next, check if we're being asked to connect to the hop that the
  883. * extend cell came from. There isn't any reason for that, and it can
  884. * assist circular-path attacks. */
  885. if (tor_memeq(ec.node_id,
  886. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  887. DIGEST_LEN)) {
  888. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  889. "Client asked me to extend back to the previous hop.");
  890. return -1;
  891. }
  892. n_chan = channel_get_for_extend((const char*)ec.node_id,
  893. &ec.orport_ipv4.addr,
  894. &msg,
  895. &should_launch);
  896. if (!n_chan) {
  897. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  898. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  899. msg?msg:"????");
  900. circ->n_hop = extend_info_new(NULL /*nickname*/,
  901. (const char*)ec.node_id,
  902. NULL /*onion_key*/,
  903. NULL /*curve25519_key*/,
  904. &ec.orport_ipv4.addr,
  905. ec.orport_ipv4.port);
  906. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  907. sizeof(ec.create_cell));
  908. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  909. if (should_launch) {
  910. /* we should try to open a connection */
  911. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  912. ec.orport_ipv4.port,
  913. (const char*)ec.node_id);
  914. if (!n_chan) {
  915. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  916. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  917. return 0;
  918. }
  919. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  920. }
  921. /* return success. The onion/circuit/etc will be taken care of
  922. * automatically (may already have been) whenever n_chan reaches
  923. * OR_CONN_STATE_OPEN.
  924. */
  925. return 0;
  926. }
  927. tor_assert(!circ->n_hop); /* Connection is already established. */
  928. circ->n_chan = n_chan;
  929. log_debug(LD_CIRC,
  930. "n_chan is %s",
  931. channel_get_canonical_remote_descr(n_chan));
  932. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  933. return -1;
  934. return 0;
  935. }
  936. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  937. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  938. * used as follows:
  939. * - 20 to initialize f_digest
  940. * - 20 to initialize b_digest
  941. * - 16 to key f_crypto
  942. * - 16 to key b_crypto
  943. *
  944. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  945. */
  946. int
  947. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  948. int reverse)
  949. {
  950. crypto_digest_t *tmp_digest;
  951. crypto_cipher_t *tmp_crypto;
  952. tor_assert(cpath);
  953. tor_assert(key_data);
  954. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  955. cpath->f_digest || cpath->b_digest));
  956. cpath->f_digest = crypto_digest_new();
  957. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  958. cpath->b_digest = crypto_digest_new();
  959. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  960. if (!(cpath->f_crypto =
  961. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  962. log_warn(LD_BUG,"Forward cipher initialization failed.");
  963. return -1;
  964. }
  965. if (!(cpath->b_crypto =
  966. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  967. log_warn(LD_BUG,"Backward cipher initialization failed.");
  968. return -1;
  969. }
  970. if (reverse) {
  971. tmp_digest = cpath->f_digest;
  972. cpath->f_digest = cpath->b_digest;
  973. cpath->b_digest = tmp_digest;
  974. tmp_crypto = cpath->f_crypto;
  975. cpath->f_crypto = cpath->b_crypto;
  976. cpath->b_crypto = tmp_crypto;
  977. }
  978. return 0;
  979. }
  980. /** The minimum number of circuit attempts before we start
  981. * thinking about warning about path bias and dropping guards */
  982. static int
  983. pathbias_get_min_circs(const or_options_t *options)
  984. {
  985. #define DFLT_PATH_BIAS_MIN_CIRC 150
  986. if (options->PathBiasCircThreshold >= 5)
  987. return options->PathBiasCircThreshold;
  988. else
  989. return networkstatus_get_param(NULL, "pb_mincircs",
  990. DFLT_PATH_BIAS_MIN_CIRC,
  991. 5, INT32_MAX);
  992. }
  993. /** The circuit success rate below which we issue a notice */
  994. static double
  995. pathbias_get_notice_rate(const or_options_t *options)
  996. {
  997. #define DFLT_PATH_BIAS_NOTICE_PCT 70
  998. if (options->PathBiasNoticeRate >= 0.0)
  999. return options->PathBiasNoticeRate;
  1000. else
  1001. return networkstatus_get_param(NULL, "pb_noticepct",
  1002. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  1003. }
  1004. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1005. /** The circuit success rate below which we issue a warn */
  1006. static double
  1007. pathbias_get_warn_rate(const or_options_t *options)
  1008. {
  1009. #define DFLT_PATH_BIAS_WARN_PCT 50
  1010. if (options->PathBiasWarnRate >= 0.0)
  1011. return options->PathBiasWarnRate;
  1012. else
  1013. return networkstatus_get_param(NULL, "pb_warnpct",
  1014. DFLT_PATH_BIAS_WARN_PCT, 0, 100)/100.0;
  1015. }
  1016. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1017. /**
  1018. * The extreme rate is the rate at which we would drop the guard,
  1019. * if pb_dropguard is also set. Otherwise we just warn.
  1020. */
  1021. double
  1022. pathbias_get_extreme_rate(const or_options_t *options)
  1023. {
  1024. #define DFLT_PATH_BIAS_EXTREME_PCT 30
  1025. if (options->PathBiasExtremeRate >= 0.0)
  1026. return options->PathBiasExtremeRate;
  1027. else
  1028. return networkstatus_get_param(NULL, "pb_extremepct",
  1029. DFLT_PATH_BIAS_EXTREME_PCT, 0, 100)/100.0;
  1030. }
  1031. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1032. /**
  1033. * If 1, we actually disable use of guards that fall below
  1034. * the extreme_pct.
  1035. */
  1036. int
  1037. pathbias_get_dropguards(const or_options_t *options)
  1038. {
  1039. #define DFLT_PATH_BIAS_DROP_GUARDS 0
  1040. if (options->PathBiasDropGuards >= 0)
  1041. return options->PathBiasDropGuards;
  1042. else
  1043. return networkstatus_get_param(NULL, "pb_dropguards",
  1044. DFLT_PATH_BIAS_DROP_GUARDS, 0, 1);
  1045. }
  1046. /**
  1047. * This is the number of circuits at which we scale our
  1048. * counts by mult_factor/scale_factor. Note, this count is
  1049. * not exact, as we only perform the scaling in the event
  1050. * of no integer truncation.
  1051. */
  1052. static int
  1053. pathbias_get_scale_threshold(const or_options_t *options)
  1054. {
  1055. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
  1056. if (options->PathBiasScaleThreshold >= 10)
  1057. return options->PathBiasScaleThreshold;
  1058. else
  1059. return networkstatus_get_param(NULL, "pb_scalecircs",
  1060. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  1061. INT32_MAX);
  1062. }
  1063. /**
  1064. * The scale factor is the denominator for our scaling
  1065. * of circuit counts for our path bias window.
  1066. *
  1067. * Note that our use of doubles for the path bias state
  1068. * file means that powers of 2 work best here.
  1069. */
  1070. static int
  1071. pathbias_get_scale_factor(const or_options_t *options)
  1072. {
  1073. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  1074. if (options->PathBiasScaleFactor >= 1)
  1075. return options->PathBiasScaleFactor;
  1076. else
  1077. return networkstatus_get_param(NULL, "pb_scalefactor",
  1078. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  1079. }
  1080. /**
  1081. * The mult factor is the numerator for our scaling
  1082. * of circuit counts for our path bias window. It
  1083. * allows us to scale by fractions.
  1084. */
  1085. static int
  1086. pathbias_get_mult_factor(const or_options_t *options)
  1087. {
  1088. #define DFLT_PATH_BIAS_MULT_FACTOR 1
  1089. if (options->PathBiasMultFactor >= 1)
  1090. return options->PathBiasMultFactor;
  1091. else
  1092. return networkstatus_get_param(NULL, "pb_multfactor",
  1093. DFLT_PATH_BIAS_MULT_FACTOR, 1,
  1094. pathbias_get_scale_factor(options));
  1095. }
  1096. /** The minimum number of circuit usage attempts before we start
  1097. * thinking about warning about path use bias and dropping guards */
  1098. static int
  1099. pathbias_get_min_use(const or_options_t *options)
  1100. {
  1101. #define DFLT_PATH_BIAS_MIN_USE 20
  1102. if (options->PathBiasUseThreshold >= 3)
  1103. return options->PathBiasUseThreshold;
  1104. else
  1105. return networkstatus_get_param(NULL, "pb_minuse",
  1106. DFLT_PATH_BIAS_MIN_USE,
  1107. 3, INT32_MAX);
  1108. }
  1109. /** The circuit use success rate below which we issue a notice */
  1110. static double
  1111. pathbias_get_notice_use_rate(const or_options_t *options)
  1112. {
  1113. #define DFLT_PATH_BIAS_NOTICE_USE_PCT 90
  1114. if (options->PathBiasNoticeUseRate >= 0.0)
  1115. return options->PathBiasNoticeUseRate;
  1116. else
  1117. return networkstatus_get_param(NULL, "pb_noticeusepct",
  1118. DFLT_PATH_BIAS_NOTICE_USE_PCT,
  1119. 0, 100)/100.0;
  1120. }
  1121. /**
  1122. * The extreme use rate is the rate at which we would drop the guard,
  1123. * if pb_dropguard is also set. Otherwise we just warn.
  1124. */
  1125. double
  1126. pathbias_get_extreme_use_rate(const or_options_t *options)
  1127. {
  1128. #define DFLT_PATH_BIAS_EXTREME_USE_PCT 70
  1129. if (options->PathBiasExtremeUseRate >= 0.0)
  1130. return options->PathBiasExtremeUseRate;
  1131. else
  1132. return networkstatus_get_param(NULL, "pb_extremeusepct",
  1133. DFLT_PATH_BIAS_EXTREME_USE_PCT,
  1134. 0, 100)/100.0;
  1135. }
  1136. /**
  1137. * This is the number of circuits at which we scale our
  1138. * use counts by mult_factor/scale_factor. Note, this count is
  1139. * not exact, as we only perform the scaling in the event
  1140. * of no integer truncation.
  1141. */
  1142. static int
  1143. pathbias_get_scale_use_threshold(const or_options_t *options)
  1144. {
  1145. #define DFLT_PATH_BIAS_SCALE_USE_THRESHOLD 100
  1146. if (options->PathBiasScaleUseThreshold >= 10)
  1147. return options->PathBiasScaleUseThreshold;
  1148. else
  1149. return networkstatus_get_param(NULL, "pb_scaleuse",
  1150. DFLT_PATH_BIAS_SCALE_USE_THRESHOLD,
  1151. 10, INT32_MAX);
  1152. }
  1153. /**
  1154. * Convert a Guard's path state to string.
  1155. */
  1156. static const char *
  1157. pathbias_state_to_string(path_state_t state)
  1158. {
  1159. switch (state) {
  1160. case PATH_STATE_NEW_CIRC:
  1161. return "new";
  1162. case PATH_STATE_BUILD_ATTEMPTED:
  1163. return "build attempted";
  1164. case PATH_STATE_BUILD_SUCCEEDED:
  1165. return "build succeeded";
  1166. case PATH_STATE_USE_ATTEMPTED:
  1167. return "use attempted";
  1168. case PATH_STATE_USE_SUCCEEDED:
  1169. return "use succeeded";
  1170. case PATH_STATE_USE_FAILED:
  1171. return "use failed";
  1172. case PATH_STATE_ALREADY_COUNTED:
  1173. return "already counted";
  1174. }
  1175. return "unknown";
  1176. }
  1177. /**
  1178. * This function decides if a circuit has progressed far enough to count
  1179. * as a circuit "attempt". As long as end-to-end tagging is possible,
  1180. * we assume the adversary will use it over hop-to-hop failure. Therefore,
  1181. * we only need to account bias for the last hop. This should make us
  1182. * much more resilient to ambient circuit failure, and also make that
  1183. * failure easier to measure (we only need to measure Exit failure rates).
  1184. */
  1185. static int
  1186. pathbias_is_new_circ_attempt(origin_circuit_t *circ)
  1187. {
  1188. #define N2N_TAGGING_IS_POSSIBLE
  1189. #ifdef N2N_TAGGING_IS_POSSIBLE
  1190. /* cpath is a circular list. We want circs with more than one hop,
  1191. * and the second hop must be waiting for keys still (it's just
  1192. * about to get them). */
  1193. return circ->cpath->next != circ->cpath &&
  1194. circ->cpath->next->state == CPATH_STATE_AWAITING_KEYS;
  1195. #else
  1196. /* If tagging attacks are no longer possible, we probably want to
  1197. * count bias from the first hop. However, one could argue that
  1198. * timing-based tagging is still more useful than per-hop failure.
  1199. * In which case, we'd never want to use this.
  1200. */
  1201. return circ->cpath->state == CPATH_STATE_AWAITING_KEYS;
  1202. #endif
  1203. }
  1204. /**
  1205. * Decide if the path bias code should count a circuit.
  1206. *
  1207. * @returns 1 if we should count it, 0 otherwise.
  1208. */
  1209. static int
  1210. pathbias_should_count(origin_circuit_t *circ)
  1211. {
  1212. #define PATHBIAS_COUNT_INTERVAL (600)
  1213. static ratelim_t count_limit =
  1214. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  1215. char *rate_msg = NULL;
  1216. /* We can't do path bias accounting without entry guards.
  1217. * Testing and controller circuits also have no guards.
  1218. *
  1219. * We also don't count server-side rends, because their
  1220. * endpoint could be chosen maliciously.
  1221. * Similarly, we can't count client-side intro attempts,
  1222. * because clients can be manipulated into connecting to
  1223. * malicious intro points. */
  1224. if (get_options()->UseEntryGuards == 0 ||
  1225. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1226. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  1227. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1228. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  1229. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1230. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  1231. return 0;
  1232. }
  1233. /* Completely ignore one hop circuits */
  1234. if (circ->build_state->onehop_tunnel ||
  1235. circ->build_state->desired_path_len == 1) {
  1236. /* Check for inconsistency */
  1237. if (circ->build_state->desired_path_len != 1 ||
  1238. !circ->build_state->onehop_tunnel) {
  1239. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  1240. log_notice(LD_BUG,
  1241. "One-hop circuit has length %d. Path state is %s. "
  1242. "Circuit is a %s currently %s.%s",
  1243. circ->build_state->desired_path_len,
  1244. pathbias_state_to_string(circ->path_state),
  1245. circuit_purpose_to_string(circ->base_.purpose),
  1246. circuit_state_to_string(circ->base_.state),
  1247. rate_msg);
  1248. tor_free(rate_msg);
  1249. }
  1250. tor_fragile_assert();
  1251. }
  1252. return 0;
  1253. }
  1254. return 1;
  1255. }
  1256. /**
  1257. * Check our circuit state to see if this is a successful circuit attempt.
  1258. * If so, record it in the current guard's path bias circ_attempt count.
  1259. *
  1260. * Also check for several potential error cases for bug #6475.
  1261. */
  1262. static int
  1263. pathbias_count_build_attempt(origin_circuit_t *circ)
  1264. {
  1265. #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
  1266. static ratelim_t circ_attempt_notice_limit =
  1267. RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL);
  1268. char *rate_msg = NULL;
  1269. if (!pathbias_should_count(circ)) {
  1270. return 0;
  1271. }
  1272. if (pathbias_is_new_circ_attempt(circ)) {
  1273. /* Help track down the real cause of bug #6475: */
  1274. if (circ->has_opened && circ->path_state != PATH_STATE_BUILD_ATTEMPTED) {
  1275. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1276. approx_time()))) {
  1277. log_info(LD_BUG,
  1278. "Opened circuit is in strange path state %s. "
  1279. "Circuit is a %s currently %s.%s",
  1280. pathbias_state_to_string(circ->path_state),
  1281. circuit_purpose_to_string(circ->base_.purpose),
  1282. circuit_state_to_string(circ->base_.state),
  1283. rate_msg);
  1284. tor_free(rate_msg);
  1285. }
  1286. }
  1287. /* Don't re-count cannibalized circs.. */
  1288. if (!circ->has_opened) {
  1289. entry_guard_t *guard = NULL;
  1290. if (circ->cpath && circ->cpath->extend_info) {
  1291. guard = entry_guard_get_by_id_digest(
  1292. circ->cpath->extend_info->identity_digest);
  1293. } else if (circ->base_.n_chan) {
  1294. guard =
  1295. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1296. }
  1297. if (guard) {
  1298. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1299. circ->path_state = PATH_STATE_BUILD_ATTEMPTED;
  1300. if (entry_guard_inc_circ_attempt_count(guard) < 0) {
  1301. /* Bogus guard; we already warned. */
  1302. return -END_CIRC_REASON_TORPROTOCOL;
  1303. }
  1304. } else {
  1305. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1306. approx_time()))) {
  1307. log_info(LD_BUG,
  1308. "Unopened circuit has strange path state %s. "
  1309. "Circuit is a %s currently %s.%s",
  1310. pathbias_state_to_string(circ->path_state),
  1311. circuit_purpose_to_string(circ->base_.purpose),
  1312. circuit_state_to_string(circ->base_.state),
  1313. rate_msg);
  1314. tor_free(rate_msg);
  1315. }
  1316. }
  1317. } else {
  1318. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1319. approx_time()))) {
  1320. log_info(LD_CIRC,
  1321. "Unopened circuit has no known guard. "
  1322. "Circuit is a %s currently %s.%s",
  1323. circuit_purpose_to_string(circ->base_.purpose),
  1324. circuit_state_to_string(circ->base_.state),
  1325. rate_msg);
  1326. tor_free(rate_msg);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. return 0;
  1332. }
  1333. /**
  1334. * Check our circuit state to see if this is a successful circuit
  1335. * completion. If so, record it in the current guard's path bias
  1336. * success count.
  1337. *
  1338. * Also check for several potential error cases for bug #6475.
  1339. */
  1340. static void
  1341. pathbias_count_build_success(origin_circuit_t *circ)
  1342. {
  1343. #define SUCCESS_NOTICE_INTERVAL (600)
  1344. static ratelim_t success_notice_limit =
  1345. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1346. char *rate_msg = NULL;
  1347. entry_guard_t *guard = NULL;
  1348. if (!pathbias_should_count(circ)) {
  1349. return;
  1350. }
  1351. /* Don't count cannibalized/reused circs for path bias
  1352. * "build" success, since they get counted under "use" success. */
  1353. if (!circ->has_opened) {
  1354. if (circ->cpath && circ->cpath->extend_info) {
  1355. guard = entry_guard_get_by_id_digest(
  1356. circ->cpath->extend_info->identity_digest);
  1357. }
  1358. if (guard) {
  1359. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  1360. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  1361. guard->circ_successes++;
  1362. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  1363. guard->circ_successes, guard->circ_attempts,
  1364. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1365. } else {
  1366. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1367. approx_time()))) {
  1368. log_info(LD_BUG,
  1369. "Succeeded circuit is in strange path state %s. "
  1370. "Circuit is a %s currently %s.%s",
  1371. pathbias_state_to_string(circ->path_state),
  1372. circuit_purpose_to_string(circ->base_.purpose),
  1373. circuit_state_to_string(circ->base_.state),
  1374. rate_msg);
  1375. tor_free(rate_msg);
  1376. }
  1377. }
  1378. if (guard->circ_attempts < guard->circ_successes) {
  1379. log_notice(LD_BUG, "Unexpectedly high successes counts (%f/%f) "
  1380. "for guard %s=%s",
  1381. guard->circ_successes, guard->circ_attempts,
  1382. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1383. }
  1384. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1385. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1386. * No need to log that case. */
  1387. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1388. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1389. approx_time()))) {
  1390. log_info(LD_CIRC,
  1391. "Completed circuit has no known guard. "
  1392. "Circuit is a %s currently %s.%s",
  1393. circuit_purpose_to_string(circ->base_.purpose),
  1394. circuit_state_to_string(circ->base_.state),
  1395. rate_msg);
  1396. tor_free(rate_msg);
  1397. }
  1398. }
  1399. } else {
  1400. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1401. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1402. approx_time()))) {
  1403. log_info(LD_BUG,
  1404. "Opened circuit is in strange path state %s. "
  1405. "Circuit is a %s currently %s.%s",
  1406. pathbias_state_to_string(circ->path_state),
  1407. circuit_purpose_to_string(circ->base_.purpose),
  1408. circuit_state_to_string(circ->base_.state),
  1409. rate_msg);
  1410. tor_free(rate_msg);
  1411. }
  1412. }
  1413. }
  1414. }
  1415. /**
  1416. * Record an attempt to use a circuit. Changes the circuit's
  1417. * path state and update its guard's usage counter.
  1418. *
  1419. * Used for path bias usage accounting.
  1420. */
  1421. void
  1422. pathbias_count_use_attempt(origin_circuit_t *circ)
  1423. {
  1424. entry_guard_t *guard;
  1425. if (!pathbias_should_count(circ)) {
  1426. return;
  1427. }
  1428. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1429. log_notice(LD_BUG,
  1430. "Used circuit is in strange path state %s. "
  1431. "Circuit is a %s currently %s.",
  1432. pathbias_state_to_string(circ->path_state),
  1433. circuit_purpose_to_string(circ->base_.purpose),
  1434. circuit_state_to_string(circ->base_.state));
  1435. } else if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  1436. guard = entry_guard_get_by_id_digest(
  1437. circ->cpath->extend_info->identity_digest);
  1438. if (guard) {
  1439. pathbias_check_use_rate(guard);
  1440. guard->use_attempts++;
  1441. log_debug(LD_CIRC,
  1442. "Marked circuit %d (%f/%f) as used for guard %s=%s.",
  1443. circ->global_identifier,
  1444. guard->use_successes, guard->use_attempts,
  1445. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1446. }
  1447. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  1448. } else {
  1449. /* Harmless but educational log message */
  1450. log_info(LD_CIRC,
  1451. "Used circuit %d is already in path state %s. "
  1452. "Circuit is a %s currently %s.",
  1453. circ->global_identifier,
  1454. pathbias_state_to_string(circ->path_state),
  1455. circuit_purpose_to_string(circ->base_.purpose),
  1456. circuit_state_to_string(circ->base_.state));
  1457. }
  1458. return;
  1459. }
  1460. /**
  1461. * Check the circuit's path stat is appropriate and it as successfully
  1462. * used.
  1463. *
  1464. * We don't actually increment the guard's counters until
  1465. * pathbias_check_close().
  1466. *
  1467. * Used for path bias usage accounting.
  1468. */
  1469. void
  1470. pathbias_mark_use_success(origin_circuit_t *circ)
  1471. {
  1472. if (!pathbias_should_count(circ)) {
  1473. return;
  1474. }
  1475. if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  1476. log_notice(LD_BUG,
  1477. "Used circuit %d is in strange path state %s. "
  1478. "Circuit is a %s currently %s.",
  1479. circ->global_identifier,
  1480. pathbias_state_to_string(circ->path_state),
  1481. circuit_purpose_to_string(circ->base_.purpose),
  1482. circuit_state_to_string(circ->base_.state));
  1483. pathbias_count_use_attempt(circ);
  1484. }
  1485. /* We don't do any accounting at the guard until actual circuit close */
  1486. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  1487. return;
  1488. }
  1489. /**
  1490. * Actually count a circuit success towards a guard's usage counters
  1491. * if the path state is appropriate.
  1492. */
  1493. static void
  1494. pathbias_count_use_success(origin_circuit_t *circ)
  1495. {
  1496. entry_guard_t *guard;
  1497. if (!pathbias_should_count(circ)) {
  1498. return;
  1499. }
  1500. if (circ->path_state != PATH_STATE_USE_SUCCEEDED) {
  1501. log_notice(LD_BUG,
  1502. "Successfully used circuit %d is in strange path state %s. "
  1503. "Circuit is a %s currently %s.",
  1504. circ->global_identifier,
  1505. pathbias_state_to_string(circ->path_state),
  1506. circuit_purpose_to_string(circ->base_.purpose),
  1507. circuit_state_to_string(circ->base_.state));
  1508. } else {
  1509. guard = entry_guard_get_by_id_digest(
  1510. circ->cpath->extend_info->identity_digest);
  1511. if (guard) {
  1512. guard->use_successes++;
  1513. log_debug(LD_CIRC,
  1514. "Marked circuit %d (%f/%f) as used successfully for guard "
  1515. "%s=%s.",
  1516. circ->global_identifier, guard->use_successes,
  1517. guard->use_attempts, guard->nickname,
  1518. hex_str(guard->identity, DIGEST_LEN));
  1519. }
  1520. }
  1521. return;
  1522. }
  1523. /**
  1524. * Send a probe down a circuit that the client attempted to use,
  1525. * but for which the stream timed out/failed. The probe is a
  1526. * RELAY_BEGIN cell with a 0.a.b.c destination address, which
  1527. * the exit will reject and reply back, echoing that address.
  1528. *
  1529. * The reason for such probes is because it is possible to bias
  1530. * a user's paths simply by causing timeouts, and these timeouts
  1531. * are not possible to differentiate from unresponsive servers.
  1532. *
  1533. * The probe is sent at the end of the circuit lifetime for two
  1534. * reasons: to prevent cryptographic taggers from being able to
  1535. * drop cells to cause timeouts, and to prevent easy recognition
  1536. * of probes before any real client traffic happens.
  1537. *
  1538. * Returns -1 if we couldn't probe, 0 otherwise.
  1539. */
  1540. static int
  1541. pathbias_send_usable_probe(circuit_t *circ)
  1542. {
  1543. /* Based on connection_ap_handshake_send_begin() */
  1544. char payload[CELL_PAYLOAD_SIZE];
  1545. int payload_len;
  1546. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1547. crypt_path_t *cpath_layer = NULL;
  1548. char *probe_nonce = NULL;
  1549. tor_assert(ocirc);
  1550. cpath_layer = ocirc->cpath->prev;
  1551. if (cpath_layer->state != CPATH_STATE_OPEN) {
  1552. /* This can happen for cannibalized circuits. Their
  1553. * last hop isn't yet open */
  1554. log_info(LD_CIRC,
  1555. "Got pathbias probe request for unopened circuit %d. "
  1556. "Opened %d, len %d", ocirc->global_identifier,
  1557. ocirc->has_opened, ocirc->build_state->desired_path_len);
  1558. return -1;
  1559. }
  1560. /* We already went down this road. */
  1561. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING &&
  1562. ocirc->pathbias_probe_id) {
  1563. log_info(LD_CIRC,
  1564. "Got pathbias probe request for circuit %d with "
  1565. "outstanding probe", ocirc->global_identifier);
  1566. return -1;
  1567. }
  1568. /* Can't probe if the channel isn't open */
  1569. if (circ->n_chan == NULL ||
  1570. (circ->n_chan->state != CHANNEL_STATE_OPEN
  1571. && circ->n_chan->state != CHANNEL_STATE_MAINT)) {
  1572. log_info(LD_CIRC,
  1573. "Skipping pathbias probe for circuit %d: Channel is not open.",
  1574. ocirc->global_identifier);
  1575. return -1;
  1576. }
  1577. circuit_change_purpose(circ, CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1578. /* Update timestamp for when circuit_expire_building() should kill us */
  1579. tor_gettimeofday(&circ->timestamp_began);
  1580. /* Generate a random address for the nonce */
  1581. crypto_rand((char*)&ocirc->pathbias_probe_nonce,
  1582. sizeof(ocirc->pathbias_probe_nonce));
  1583. ocirc->pathbias_probe_nonce &= 0x00ffffff;
  1584. probe_nonce = tor_dup_ip(ocirc->pathbias_probe_nonce);
  1585. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:25", probe_nonce);
  1586. payload_len = (int)strlen(payload)+1;
  1587. // XXX: need this? Can we assume ipv4 will always be supported?
  1588. // If not, how do we tell?
  1589. //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  1590. // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  1591. // payload_len += 4;
  1592. //}
  1593. /* Generate+Store stream id, make sure it's non-zero */
  1594. ocirc->pathbias_probe_id = get_unique_stream_id_by_circ(ocirc);
  1595. if (ocirc->pathbias_probe_id==0) {
  1596. log_warn(LD_CIRC,
  1597. "Ran out of stream IDs on circuit %u during "
  1598. "pathbias probe attempt.", ocirc->global_identifier);
  1599. tor_free(probe_nonce);
  1600. return -1;
  1601. }
  1602. log_info(LD_CIRC,
  1603. "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
  1604. probe_nonce, ocirc->pathbias_probe_id, ocirc->global_identifier);
  1605. tor_free(probe_nonce);
  1606. /* Send a test relay cell */
  1607. if (relay_send_command_from_edge(ocirc->pathbias_probe_id, circ,
  1608. RELAY_COMMAND_BEGIN, payload,
  1609. payload_len, cpath_layer) < 0) {
  1610. log_notice(LD_CIRC,
  1611. "Failed to send pathbias probe cell on circuit %d.",
  1612. ocirc->global_identifier);
  1613. return -1;
  1614. }
  1615. /* Mark it freshly dirty so it doesn't get expired in the meantime */
  1616. circ->timestamp_dirty = time(NULL);
  1617. return 0;
  1618. }
  1619. /**
  1620. * Check the response to a pathbias probe, to ensure the
  1621. * cell is recognized and the nonce and other probe
  1622. * characteristics are as expected.
  1623. *
  1624. * If the response is valid, return 0. Otherwise return < 0.
  1625. */
  1626. int
  1627. pathbias_check_probe_response(circuit_t *circ, const cell_t *cell)
  1628. {
  1629. /* Based on connection_edge_process_relay_cell() */
  1630. relay_header_t rh;
  1631. int reason;
  1632. uint32_t ipv4_host;
  1633. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1634. tor_assert(cell);
  1635. tor_assert(ocirc);
  1636. tor_assert(circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1637. relay_header_unpack(&rh, cell->payload);
  1638. reason = rh.length > 0 ?
  1639. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1640. if (rh.command == RELAY_COMMAND_END &&
  1641. reason == END_STREAM_REASON_EXITPOLICY &&
  1642. ocirc->pathbias_probe_id == rh.stream_id) {
  1643. /* Check length+extract host: It is in network order after the reason code.
  1644. * See connection_edge_end(). */
  1645. if (rh.length < 9) { /* reason+ipv4+dns_ttl */
  1646. log_notice(LD_PROTOCOL,
  1647. "Short path bias probe response length field (%d).", rh.length);
  1648. return - END_CIRC_REASON_TORPROTOCOL;
  1649. }
  1650. ipv4_host = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  1651. /* Check nonce */
  1652. if (ipv4_host == ocirc->pathbias_probe_nonce) {
  1653. pathbias_mark_use_success(ocirc);
  1654. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1655. log_info(LD_CIRC,
  1656. "Got valid path bias probe back for circ %d, stream %d.",
  1657. ocirc->global_identifier, ocirc->pathbias_probe_id);
  1658. return 0;
  1659. } else {
  1660. log_notice(LD_CIRC,
  1661. "Got strange probe value 0x%x vs 0x%x back for circ %d, "
  1662. "stream %d.", ipv4_host, ocirc->pathbias_probe_nonce,
  1663. ocirc->global_identifier, ocirc->pathbias_probe_id);
  1664. return -1;
  1665. }
  1666. }
  1667. log_info(LD_CIRC,
  1668. "Got another cell back back on pathbias probe circuit %d: "
  1669. "Command: %d, Reason: %d, Stream-id: %d",
  1670. ocirc->global_identifier, rh.command, reason, rh.stream_id);
  1671. return -1;
  1672. }
  1673. /**
  1674. * Check if a circuit was used and/or closed successfully.
  1675. *
  1676. * If we attempted to use the circuit to carry a stream but failed
  1677. * for whatever reason, or if the circuit mysteriously died before
  1678. * we could attach any streams, record these two cases.
  1679. *
  1680. * If we *have* successfully used the circuit, or it appears to
  1681. * have been closed by us locally, count it as a success.
  1682. *
  1683. * Returns 0 if we're done making decisions with the circ,
  1684. * or -1 if we want to probe it first.
  1685. */
  1686. int
  1687. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  1688. {
  1689. circuit_t *circ = &ocirc->base_;
  1690. if (!pathbias_should_count(ocirc)) {
  1691. return 0;
  1692. }
  1693. switch (ocirc->path_state) {
  1694. /* If the circuit was closed after building, but before use, we need
  1695. * to ensure we were the ones who tried to close it (and not a remote
  1696. * actor). */
  1697. case PATH_STATE_BUILD_SUCCEEDED:
  1698. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  1699. /* Remote circ close reasons on an unused circuit all could be bias */
  1700. log_info(LD_CIRC,
  1701. "Circuit %d remote-closed without successful use for reason %d. "
  1702. "Circuit purpose %d currently %d,%s. Len %d.",
  1703. ocirc->global_identifier,
  1704. reason, circ->purpose, ocirc->has_opened,
  1705. circuit_state_to_string(circ->state),
  1706. ocirc->build_state->desired_path_len);
  1707. pathbias_count_collapse(ocirc);
  1708. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  1709. == END_CIRC_REASON_CHANNEL_CLOSED &&
  1710. circ->n_chan &&
  1711. circ->n_chan->reason_for_closing
  1712. != CHANNEL_CLOSE_REQUESTED) {
  1713. /* If we didn't close the channel ourselves, it could be bias */
  1714. /* XXX: Only count bias if the network is live?
  1715. * What about clock jumps/suspends? */
  1716. log_info(LD_CIRC,
  1717. "Circuit %d's channel closed without successful use for reason "
  1718. "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
  1719. "%d.", ocirc->global_identifier,
  1720. reason, circ->n_chan->reason_for_closing,
  1721. circ->purpose, ocirc->has_opened,
  1722. circuit_state_to_string(circ->state),
  1723. ocirc->build_state->desired_path_len);
  1724. pathbias_count_collapse(ocirc);
  1725. } else {
  1726. pathbias_count_successful_close(ocirc);
  1727. }
  1728. break;
  1729. /* If we tried to use a circuit but failed, we should probe it to ensure
  1730. * it has not been tampered with. */
  1731. case PATH_STATE_USE_ATTEMPTED:
  1732. /* XXX: Only probe and/or count failure if the network is live?
  1733. * What about clock jumps/suspends? */
  1734. if (pathbias_send_usable_probe(circ) == 0)
  1735. return -1;
  1736. else
  1737. pathbias_count_use_failed(ocirc);
  1738. /* Any circuit where there were attempted streams but no successful
  1739. * streams could be bias */
  1740. log_info(LD_CIRC,
  1741. "Circuit %d closed without successful use for reason %d. "
  1742. "Circuit purpose %d currently %d,%s. Len %d.",
  1743. ocirc->global_identifier,
  1744. reason, circ->purpose, ocirc->has_opened,
  1745. circuit_state_to_string(circ->state),
  1746. ocirc->build_state->desired_path_len);
  1747. break;
  1748. case PATH_STATE_USE_SUCCEEDED:
  1749. pathbias_count_successful_close(ocirc);
  1750. pathbias_count_use_success(ocirc);
  1751. break;
  1752. default:
  1753. // Other states are uninteresting. No stats to count.
  1754. break;
  1755. }
  1756. ocirc->path_state = PATH_STATE_ALREADY_COUNTED;
  1757. return 0;
  1758. }
  1759. /**
  1760. * Count a successfully closed circuit.
  1761. */
  1762. static void
  1763. pathbias_count_successful_close(origin_circuit_t *circ)
  1764. {
  1765. entry_guard_t *guard = NULL;
  1766. if (!pathbias_should_count(circ)) {
  1767. return;
  1768. }
  1769. if (circ->cpath && circ->cpath->extend_info) {
  1770. guard = entry_guard_get_by_id_digest(
  1771. circ->cpath->extend_info->identity_digest);
  1772. }
  1773. if (guard) {
  1774. /* In the long run: circuit_success ~= successful_circuit_close +
  1775. * circ_failure + stream_failure */
  1776. guard->successful_circuits_closed++;
  1777. entry_guards_changed();
  1778. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1779. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1780. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1781. * No need to log that case. */
  1782. log_info(LD_CIRC,
  1783. "Successfully closed circuit has no known guard. "
  1784. "Circuit is a %s currently %s",
  1785. circuit_purpose_to_string(circ->base_.purpose),
  1786. circuit_state_to_string(circ->base_.state));
  1787. }
  1788. }
  1789. /**
  1790. * Count a circuit that fails after it is built, but before it can
  1791. * carry any traffic.
  1792. *
  1793. * This is needed because there are ways to destroy a
  1794. * circuit after it has successfully completed. Right now, this is
  1795. * used for purely informational/debugging purposes.
  1796. */
  1797. static void
  1798. pathbias_count_collapse(origin_circuit_t *circ)
  1799. {
  1800. entry_guard_t *guard = NULL;
  1801. if (!pathbias_should_count(circ)) {
  1802. return;
  1803. }
  1804. if (circ->cpath && circ->cpath->extend_info) {
  1805. guard = entry_guard_get_by_id_digest(
  1806. circ->cpath->extend_info->identity_digest);
  1807. }
  1808. if (guard) {
  1809. guard->collapsed_circuits++;
  1810. entry_guards_changed();
  1811. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1812. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1813. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1814. * No need to log that case. */
  1815. log_info(LD_CIRC,
  1816. "Destroyed circuit has no known guard. "
  1817. "Circuit is a %s currently %s",
  1818. circuit_purpose_to_string(circ->base_.purpose),
  1819. circuit_state_to_string(circ->base_.state));
  1820. }
  1821. }
  1822. /**
  1823. * Count a known failed circuit (because we could not probe it).
  1824. *
  1825. * This counter is informational.
  1826. */
  1827. static void
  1828. pathbias_count_use_failed(origin_circuit_t *circ)
  1829. {
  1830. entry_guard_t *guard = NULL;
  1831. if (!pathbias_should_count(circ)) {
  1832. return;
  1833. }
  1834. if (circ->cpath && circ->cpath->extend_info) {
  1835. guard = entry_guard_get_by_id_digest(
  1836. circ->cpath->extend_info->identity_digest);
  1837. }
  1838. if (guard) {
  1839. guard->unusable_circuits++;
  1840. entry_guards_changed();
  1841. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1842. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1843. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1844. * No need to log that case. */
  1845. /* XXX note cut-and-paste code in this function compared to nearby
  1846. * functions. Would be nice to refactor. -RD */
  1847. log_info(LD_CIRC,
  1848. "Stream-failing circuit has no known guard. "
  1849. "Circuit is a %s currently %s",
  1850. circuit_purpose_to_string(circ->base_.purpose),
  1851. circuit_state_to_string(circ->base_.state));
  1852. }
  1853. }
  1854. /**
  1855. * Count timeouts for path bias log messages.
  1856. *
  1857. * These counts are purely informational.
  1858. */
  1859. void
  1860. pathbias_count_timeout(origin_circuit_t *circ)
  1861. {
  1862. entry_guard_t *guard = NULL;
  1863. if (!pathbias_should_count(circ)) {
  1864. return;
  1865. }
  1866. /* For hidden service circs, they can actually be used
  1867. * successfully and then time out later (because
  1868. * the other side declines to use them). */
  1869. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1870. return;
  1871. }
  1872. if (circ->cpath && circ->cpath->extend_info) {
  1873. guard = entry_guard_get_by_id_digest(
  1874. circ->cpath->extend_info->identity_digest);
  1875. }
  1876. if (guard) {
  1877. guard->timeouts++;
  1878. entry_guards_changed();
  1879. }
  1880. }
  1881. /**
  1882. * Helper function to count all of the currently opened circuits
  1883. * for a guard that are in a given path state range. The state
  1884. * range is inclusive on both ends.
  1885. */
  1886. static int
  1887. pathbias_count_circs_in_states(entry_guard_t *guard,
  1888. path_state_t from,
  1889. path_state_t to)
  1890. {
  1891. circuit_t *circ = global_circuitlist;
  1892. int open_circuits = 0;
  1893. /* Count currently open circuits. Give them the benefit of the doubt */
  1894. for ( ; circ; circ = circ->next) {
  1895. origin_circuit_t *ocirc = NULL;
  1896. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1897. circ->marked_for_close) /* already counted */
  1898. continue;
  1899. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1900. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1901. continue;
  1902. if (ocirc->path_state >= from &&
  1903. ocirc->path_state <= to &&
  1904. pathbias_should_count(ocirc) &&
  1905. fast_memeq(guard->identity,
  1906. ocirc->cpath->extend_info->identity_digest,
  1907. DIGEST_LEN)) {
  1908. log_debug(LD_CIRC, "Found opened circuit %d in path_state %s",
  1909. ocirc->global_identifier,
  1910. pathbias_state_to_string(ocirc->path_state));
  1911. open_circuits++;
  1912. }
  1913. }
  1914. return open_circuits;
  1915. }
  1916. /**
  1917. * Return the number of circuits counted as successfully closed for
  1918. * this guard.
  1919. *
  1920. * Also add in the currently open circuits to give them the benefit
  1921. * of the doubt.
  1922. */
  1923. double
  1924. pathbias_get_close_success_count(entry_guard_t *guard)
  1925. {
  1926. return guard->successful_circuits_closed +
  1927. pathbias_count_circs_in_states(guard,
  1928. PATH_STATE_BUILD_SUCCEEDED,
  1929. PATH_STATE_USE_SUCCEEDED);
  1930. }
  1931. /**
  1932. * Return the number of circuits counted as successfully used
  1933. * this guard.
  1934. *
  1935. * Also add in the currently open circuits that we are attempting
  1936. * to use to give them the benefit of the doubt.
  1937. */
  1938. double
  1939. pathbias_get_use_success_count(entry_guard_t *guard)
  1940. {
  1941. return guard->use_successes +
  1942. pathbias_count_circs_in_states(guard,
  1943. PATH_STATE_USE_ATTEMPTED,
  1944. PATH_STATE_USE_SUCCEEDED);
  1945. }
  1946. /**
  1947. * Check the path bias use rate against our consensus parameter limits.
  1948. *
  1949. * Emits a log message if the use success rates are too low.
  1950. *
  1951. * If pathbias_get_dropguards() is set, we also disable the use of
  1952. * very failure prone guards.
  1953. *
  1954. * Returns -1 if we decided to disable the guard, 0 otherwise.
  1955. */
  1956. static int
  1957. pathbias_check_use_rate(entry_guard_t *guard)
  1958. {
  1959. const or_options_t *options = get_options();
  1960. if (guard->use_attempts > pathbias_get_min_use(options)) {
  1961. /* Note: We rely on the < comparison here to allow us to set a 0
  1962. * rate and disable the feature entirely. If refactoring, don't
  1963. * change to <= */
  1964. if (pathbias_get_use_success_count(guard)/guard->use_attempts
  1965. < pathbias_get_extreme_use_rate(options)) {
  1966. /* Dropping is currently disabled by default. */
  1967. if (pathbias_get_dropguards(options)) {
  1968. if (!guard->path_bias_disabled) {
  1969. log_warn(LD_CIRC,
  1970. "Your Guard %s=%s is failing to carry an extremely large "
  1971. "amount of stream on its circuits. "
  1972. "To avoid potential route manipluation attacks, Tor has "
  1973. "disabled use of this guard. "
  1974. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1975. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1976. "and %ld timed out. "
  1977. "For reference, your timeout cutoff is %ld seconds.",
  1978. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1979. tor_lround(pathbias_get_use_success_count(guard)),
  1980. tor_lround(guard->use_attempts),
  1981. tor_lround(pathbias_get_close_success_count(guard)),
  1982. tor_lround(guard->circ_attempts),
  1983. tor_lround(guard->circ_successes),
  1984. tor_lround(guard->unusable_circuits),
  1985. tor_lround(guard->collapsed_circuits),
  1986. tor_lround(guard->timeouts),
  1987. tor_lround(circ_times.close_ms/1000));
  1988. guard->path_bias_disabled = 1;
  1989. guard->bad_since = approx_time();
  1990. return -1;
  1991. }
  1992. } else if (!guard->path_bias_extreme) {
  1993. guard->path_bias_extreme = 1;
  1994. log_warn(LD_CIRC,
  1995. "Your Guard %s=%s is failing to carry an extremely large "
  1996. "amount of streams on its circuits. "
  1997. "This could indicate a route manipulation attack, network "
  1998. "overload, bad local network connectivity, or a bug. "
  1999. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  2000. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2001. "and %ld timed out. "
  2002. "For reference, your timeout cutoff is %ld seconds.",
  2003. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2004. tor_lround(pathbias_get_use_success_count(guard)),
  2005. tor_lround(guard->use_attempts),
  2006. tor_lround(pathbias_get_close_success_count(guard)),
  2007. tor_lround(guard->circ_attempts),
  2008. tor_lround(guard->circ_successes),
  2009. tor_lround(guard->unusable_circuits),
  2010. tor_lround(guard->collapsed_circuits),
  2011. tor_lround(guard->timeouts),
  2012. tor_lround(circ_times.close_ms/1000));
  2013. }
  2014. } else if (pathbias_get_use_success_count(guard)/guard->use_attempts
  2015. < pathbias_get_notice_use_rate(options)) {
  2016. if (!guard->path_bias_noticed) {
  2017. guard->path_bias_noticed = 1;
  2018. log_notice(LD_CIRC,
  2019. "Your Guard %s=%s is failing to carry more streams on its "
  2020. "circuits than usual. "
  2021. "Most likely this means the Tor network is overloaded "
  2022. "or your network connection is poor. "
  2023. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  2024. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2025. "and %ld timed out. "
  2026. "For reference, your timeout cutoff is %ld seconds.",
  2027. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2028. tor_lround(pathbias_get_use_success_count(guard)),
  2029. tor_lround(guard->use_attempts),
  2030. tor_lround(pathbias_get_close_success_count(guard)),
  2031. tor_lround(guard->circ_attempts),
  2032. tor_lround(guard->circ_successes),
  2033. tor_lround(guard->unusable_circuits),
  2034. tor_lround(guard->collapsed_circuits),
  2035. tor_lround(guard->timeouts),
  2036. tor_lround(circ_times.close_ms/1000));
  2037. }
  2038. }
  2039. }
  2040. /* If we get a ton of circuits, just scale everything down */
  2041. if (guard->use_attempts > pathbias_get_scale_use_threshold(options)) {
  2042. const int scale_factor = pathbias_get_scale_factor(options);
  2043. const int mult_factor = pathbias_get_mult_factor(options);
  2044. int opened_attempts = pathbias_count_circs_in_states(guard,
  2045. PATH_STATE_USE_ATTEMPTED, PATH_STATE_USE_SUCCEEDED);
  2046. guard->use_attempts -= opened_attempts;
  2047. guard->use_attempts *= mult_factor;
  2048. guard->use_successes *= mult_factor;
  2049. guard->use_attempts /= scale_factor;
  2050. guard->use_successes /= scale_factor;
  2051. guard->use_attempts += opened_attempts;
  2052. log_info(LD_CIRC,
  2053. "Scaled pathbias use counts to %f/%f (%d open) for guard %s=%s",
  2054. guard->use_successes, guard->use_attempts, opened_attempts,
  2055. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  2056. }
  2057. return 0;
  2058. }
  2059. /**
  2060. * Check the path bias circuit close status rates against our consensus
  2061. * parameter limits.
  2062. *
  2063. * Emits a log message if the use success rates are too low.
  2064. *
  2065. * If pathbias_get_dropguards() is set, we also disable the use of
  2066. * very failure prone guards.
  2067. *
  2068. * Returns -1 if we decided to disable the guard, 0 otherwise.
  2069. */
  2070. static int
  2071. pathbias_check_close_rate(entry_guard_t *guard)
  2072. {
  2073. const or_options_t *options = get_options();
  2074. if (guard->circ_attempts > pathbias_get_min_circs(options)) {
  2075. /* Note: We rely on the < comparison here to allow us to set a 0
  2076. * rate and disable the feature entirely. If refactoring, don't
  2077. * change to <= */
  2078. if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2079. < pathbias_get_extreme_rate(options)) {
  2080. /* Dropping is currently disabled by default. */
  2081. if (pathbias_get_dropguards(options)) {
  2082. if (!guard->path_bias_disabled) {
  2083. log_warn(LD_CIRC,
  2084. "Your Guard %s=%s is failing an extremely large "
  2085. "amount of circuits. "
  2086. "To avoid potential route manipluation attacks, Tor has "
  2087. "disabled use of this guard. "
  2088. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2089. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2090. "and %ld timed out. "
  2091. "For reference, your timeout cutoff is %ld seconds.",
  2092. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2093. tor_lround(pathbias_get_close_success_count(guard)),
  2094. tor_lround(guard->circ_attempts),
  2095. tor_lround(pathbias_get_use_success_count(guard)),
  2096. tor_lround(guard->use_attempts),
  2097. tor_lround(guard->circ_successes),
  2098. tor_lround(guard->unusable_circuits),
  2099. tor_lround(guard->collapsed_circuits),
  2100. tor_lround(guard->timeouts),
  2101. tor_lround(circ_times.close_ms/1000));
  2102. guard->path_bias_disabled = 1;
  2103. guard->bad_since = approx_time();
  2104. return -1;
  2105. }
  2106. } else if (!guard->path_bias_extreme) {
  2107. guard->path_bias_extreme = 1;
  2108. log_warn(LD_CIRC,
  2109. "Your Guard %s=%s is failing an extremely large "
  2110. "amount of circuits. "
  2111. "This could indicate a route manipulation attack, "
  2112. "extreme network overload, or a bug. "
  2113. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2114. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2115. "and %ld timed out. "
  2116. "For reference, your timeout cutoff is %ld seconds.",
  2117. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2118. tor_lround(pathbias_get_close_success_count(guard)),
  2119. tor_lround(guard->circ_attempts),
  2120. tor_lround(pathbias_get_use_success_count(guard)),
  2121. tor_lround(guard->use_attempts),
  2122. tor_lround(guard->circ_successes),
  2123. tor_lround(guard->unusable_circuits),
  2124. tor_lround(guard->collapsed_circuits),
  2125. tor_lround(guard->timeouts),
  2126. tor_lround(circ_times.close_ms/1000));
  2127. }
  2128. } else if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2129. < pathbias_get_warn_rate(options)) {
  2130. if (!guard->path_bias_warned) {
  2131. guard->path_bias_warned = 1;
  2132. log_warn(LD_CIRC,
  2133. "Your Guard %s=%s is failing a very large "
  2134. "amount of circuits. "
  2135. "Most likely this means the Tor network is "
  2136. "overloaded, but it could also mean an attack against "
  2137. "you or the potentially the guard itself. "
  2138. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2139. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2140. "and %ld timed out. "
  2141. "For reference, your timeout cutoff is %ld seconds.",
  2142. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2143. tor_lround(pathbias_get_close_success_count(guard)),
  2144. tor_lround(guard->circ_attempts),
  2145. tor_lround(pathbias_get_use_success_count(guard)),
  2146. tor_lround(guard->use_attempts),
  2147. tor_lround(guard->circ_successes),
  2148. tor_lround(guard->unusable_circuits),
  2149. tor_lround(guard->collapsed_circuits),
  2150. tor_lround(guard->timeouts),
  2151. tor_lround(circ_times.close_ms/1000));
  2152. }
  2153. } else if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2154. < pathbias_get_notice_rate(options)) {
  2155. if (!guard->path_bias_noticed) {
  2156. guard->path_bias_noticed = 1;
  2157. log_notice(LD_CIRC,
  2158. "Your Guard %s=%s is failing more circuits than "
  2159. "usual. "
  2160. "Most likely this means the Tor network is overloaded. "
  2161. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2162. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2163. "and %ld timed out. "
  2164. "For reference, your timeout cutoff is %ld seconds.",
  2165. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2166. tor_lround(pathbias_get_close_success_count(guard)),
  2167. tor_lround(guard->circ_attempts),
  2168. tor_lround(pathbias_get_use_success_count(guard)),
  2169. tor_lround(guard->use_attempts),
  2170. tor_lround(guard->circ_successes),
  2171. tor_lround(guard->unusable_circuits),
  2172. tor_lround(guard->collapsed_circuits),
  2173. tor_lround(guard->timeouts),
  2174. tor_lround(circ_times.close_ms/1000));
  2175. }
  2176. }
  2177. }
  2178. /* If we get a ton of circuits, just scale everything down */
  2179. if (guard->circ_attempts > pathbias_get_scale_threshold(options)) {
  2180. const int scale_factor = pathbias_get_scale_factor(options);
  2181. const int mult_factor = pathbias_get_mult_factor(options);
  2182. int opened_attempts = pathbias_count_circs_in_states(guard,
  2183. PATH_STATE_BUILD_ATTEMPTED, PATH_STATE_BUILD_ATTEMPTED);
  2184. int opened_built = pathbias_count_circs_in_states(guard,
  2185. PATH_STATE_BUILD_SUCCEEDED,
  2186. PATH_STATE_USE_FAILED);
  2187. guard->circ_attempts -= opened_attempts;
  2188. guard->circ_successes -= opened_built;
  2189. guard->circ_attempts *= mult_factor;
  2190. guard->circ_successes *= mult_factor;
  2191. guard->timeouts *= mult_factor;
  2192. guard->successful_circuits_closed *= mult_factor;
  2193. guard->collapsed_circuits *= mult_factor;
  2194. guard->unusable_circuits *= mult_factor;
  2195. guard->circ_attempts /= scale_factor;
  2196. guard->circ_successes /= scale_factor;
  2197. guard->timeouts /= scale_factor;
  2198. guard->successful_circuits_closed /= scale_factor;
  2199. guard->collapsed_circuits /= scale_factor;
  2200. guard->unusable_circuits /= scale_factor;
  2201. guard->circ_attempts += opened_attempts;
  2202. guard->circ_successes += opened_built;
  2203. log_info(LD_CIRC,
  2204. "Scaled pathbias counts to (%f,%f)/%f (%d/%d open) for guard "
  2205. "%s=%s",
  2206. guard->circ_successes, guard->successful_circuits_closed,
  2207. guard->circ_attempts, opened_built, opened_attempts,
  2208. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  2209. }
  2210. return 0;
  2211. }
  2212. /** Increment the number of times we successfully extended a circuit to
  2213. * 'guard', first checking if the failure rate is high enough that we should
  2214. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  2215. * guard looks fine. */
  2216. static int
  2217. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  2218. {
  2219. entry_guards_changed();
  2220. if (pathbias_check_close_rate(guard) < 0)
  2221. return -1;
  2222. guard->circ_attempts++;
  2223. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  2224. guard->circ_successes, guard->circ_attempts, guard->nickname,
  2225. hex_str(guard->identity, DIGEST_LEN));
  2226. return 0;
  2227. }
  2228. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  2229. * (The body of <b>reply</b> varies depending on what sort of handshake
  2230. * this is.)
  2231. *
  2232. * Calculate the appropriate keys and digests, make sure KH is
  2233. * correct, and initialize this hop of the cpath.
  2234. *
  2235. * Return - reason if we want to mark circ for close, else return 0.
  2236. */
  2237. int
  2238. circuit_finish_handshake(origin_circuit_t *circ,
  2239. const created_cell_t *reply)
  2240. {
  2241. char keys[CPATH_KEY_MATERIAL_LEN];
  2242. crypt_path_t *hop;
  2243. int rv;
  2244. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  2245. return rv;
  2246. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  2247. hop = circ->cpath;
  2248. } else {
  2249. hop = onion_next_hop_in_cpath(circ->cpath);
  2250. if (!hop) { /* got an extended when we're all done? */
  2251. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  2252. return - END_CIRC_REASON_TORPROTOCOL;
  2253. }
  2254. }
  2255. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  2256. {
  2257. if (onion_skin_client_handshake(hop->handshake_state.tag,
  2258. &hop->handshake_state,
  2259. reply->reply, reply->handshake_len,
  2260. (uint8_t*)keys, sizeof(keys),
  2261. (uint8_t*)hop->rend_circ_nonce) < 0) {
  2262. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  2263. return -END_CIRC_REASON_TORPROTOCOL;
  2264. }
  2265. }
  2266. onion_handshake_state_release(&hop->handshake_state);
  2267. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  2268. return -END_CIRC_REASON_TORPROTOCOL;
  2269. }
  2270. hop->state = CPATH_STATE_OPEN;
  2271. log_info(LD_CIRC,"Finished building circuit hop:");
  2272. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  2273. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  2274. return 0;
  2275. }
  2276. /** We received a relay truncated cell on circ.
  2277. *
  2278. * Since we don't send truncates currently, getting a truncated
  2279. * means that a connection broke or an extend failed. For now,
  2280. * just give up: force circ to close, and return 0.
  2281. */
  2282. int
  2283. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  2284. {
  2285. // crypt_path_t *victim;
  2286. // connection_t *stream;
  2287. tor_assert(circ);
  2288. tor_assert(layer);
  2289. /* XXX Since we don't send truncates currently, getting a truncated
  2290. * means that a connection broke or an extend failed. For now,
  2291. * just give up.
  2292. */
  2293. circuit_mark_for_close(TO_CIRCUIT(circ),
  2294. END_CIRC_REASON_FLAG_REMOTE|reason);
  2295. return 0;
  2296. #if 0
  2297. while (layer->next != circ->cpath) {
  2298. /* we need to clear out layer->next */
  2299. victim = layer->next;
  2300. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  2301. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  2302. if (stream->cpath_layer == victim) {
  2303. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  2304. stream->stream_id);
  2305. /* no need to send 'end' relay cells,
  2306. * because the other side's already dead
  2307. */
  2308. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  2309. }
  2310. }
  2311. layer->next = victim->next;
  2312. circuit_free_cpath_node(victim);
  2313. }
  2314. log_info(LD_CIRC, "finished");
  2315. return 0;
  2316. #endif
  2317. }
  2318. /** Given a response payload and keys, initialize, then send a created
  2319. * cell back.
  2320. */
  2321. int
  2322. onionskin_answer(or_circuit_t *circ,
  2323. const created_cell_t *created_cell,
  2324. const char *keys,
  2325. const uint8_t *rend_circ_nonce)
  2326. {
  2327. cell_t cell;
  2328. crypt_path_t *tmp_cpath;
  2329. if (created_cell_format(&cell, created_cell) < 0) {
  2330. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  2331. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  2332. return -1;
  2333. }
  2334. cell.circ_id = circ->p_circ_id;
  2335. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  2336. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  2337. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2338. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  2339. (unsigned int)get_uint32(keys),
  2340. (unsigned int)get_uint32(keys+20));
  2341. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  2342. log_warn(LD_BUG,"Circuit initialization failed");
  2343. tor_free(tmp_cpath);
  2344. return -1;
  2345. }
  2346. circ->n_digest = tmp_cpath->f_digest;
  2347. circ->n_crypto = tmp_cpath->f_crypto;
  2348. circ->p_digest = tmp_cpath->b_digest;
  2349. circ->p_crypto = tmp_cpath->b_crypto;
  2350. tmp_cpath->magic = 0;
  2351. tor_free(tmp_cpath);
  2352. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  2353. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  2354. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  2355. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  2356. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  2357. circ->is_first_hop ? "created_fast" : "created");
  2358. if (!channel_is_local(circ->p_chan) &&
  2359. !channel_is_outgoing(circ->p_chan)) {
  2360. /* record that we could process create cells from a non-local conn
  2361. * that we didn't initiate; presumably this means that create cells
  2362. * can reach us too. */
  2363. router_orport_found_reachable();
  2364. }
  2365. return 0;
  2366. }
  2367. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  2368. * number of endpoints that would give something away about our destination.
  2369. *
  2370. * If the routerlist <b>nodes</b> doesn't have enough routers
  2371. * to handle the desired path length, return as large a path length as
  2372. * is feasible, except if it's less than 2, in which case return -1.
  2373. * XXX ^^ I think this behavior is a hold-over from back when we had only a
  2374. * few relays in the network, and certainly back before guards existed.
  2375. * We should very likely get rid of it. -RD
  2376. */
  2377. static int
  2378. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  2379. {
  2380. int num_acceptable_routers;
  2381. int routelen;
  2382. tor_assert(nodes);
  2383. routelen = DEFAULT_ROUTE_LEN;
  2384. if (exit &&
  2385. purpose != CIRCUIT_PURPOSE_TESTING &&
  2386. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2387. routelen++;
  2388. num_acceptable_routers = count_acceptable_nodes(nodes);
  2389. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2390. routelen, num_acceptable_routers, smartlist_len(nodes));
  2391. if (num_acceptable_routers < 2) {
  2392. log_info(LD_CIRC,
  2393. "Not enough acceptable routers (%d). Discarding this circuit.",
  2394. num_acceptable_routers);
  2395. return -1;
  2396. }
  2397. if (num_acceptable_routers < routelen) {
  2398. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2399. routelen, num_acceptable_routers);
  2400. routelen = num_acceptable_routers;
  2401. }
  2402. return routelen;
  2403. }
  2404. /** Return a newly allocated list of uint16_t * for each predicted port not
  2405. * handled by a current circuit. */
  2406. static smartlist_t *
  2407. circuit_get_unhandled_ports(time_t now)
  2408. {
  2409. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  2410. circuit_remove_handled_ports(dest);
  2411. return dest;
  2412. }
  2413. /** Return 1 if we already have circuits present or on the way for
  2414. * all anticipated ports. Return 0 if we should make more.
  2415. *
  2416. * If we're returning 0, set need_uptime and need_capacity to
  2417. * indicate any requirements that the unhandled ports have.
  2418. */
  2419. int
  2420. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2421. int *need_capacity)
  2422. {
  2423. int i, enough;
  2424. uint16_t *port;
  2425. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2426. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2427. tor_assert(need_uptime);
  2428. tor_assert(need_capacity);
  2429. // Always predict need_capacity
  2430. *need_capacity = 1;
  2431. enough = (smartlist_len(sl) == 0);
  2432. for (i = 0; i < smartlist_len(sl); ++i) {
  2433. port = smartlist_get(sl, i);
  2434. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  2435. *need_uptime = 1;
  2436. tor_free(port);
  2437. }
  2438. smartlist_free(sl);
  2439. return enough;
  2440. }
  2441. /** Return 1 if <b>node</b> can handle one or more of the ports in
  2442. * <b>needed_ports</b>, else return 0.
  2443. */
  2444. static int
  2445. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  2446. { /* XXXX MOVE */
  2447. int i;
  2448. uint16_t port;
  2449. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2450. addr_policy_result_t r;
  2451. /* alignment issues aren't a worry for this dereference, since
  2452. needed_ports is explicitly a smartlist of uint16_t's */
  2453. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2454. tor_assert(port);
  2455. if (node)
  2456. r = compare_tor_addr_to_node_policy(NULL, port, node);
  2457. else
  2458. continue;
  2459. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2460. return 1;
  2461. }
  2462. return 0;
  2463. }
  2464. /** Return true iff <b>conn</b> needs another general circuit to be
  2465. * built. */
  2466. static int
  2467. ap_stream_wants_exit_attention(connection_t *conn)
  2468. {
  2469. entry_connection_t *entry;
  2470. if (conn->type != CONN_TYPE_AP)
  2471. return 0;
  2472. entry = TO_ENTRY_CONN(conn);
  2473. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2474. !conn->marked_for_close &&
  2475. !(entry->want_onehop) && /* ignore one-hop streams */
  2476. !(entry->use_begindir) && /* ignore targeted dir fetches */
  2477. !(entry->chosen_exit_name) && /* ignore defined streams */
  2478. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2479. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  2480. MIN_CIRCUITS_HANDLING_STREAM))
  2481. return 1;
  2482. return 0;
  2483. }
  2484. /** Return a pointer to a suitable router to be the exit node for the
  2485. * general-purpose circuit we're about to build.
  2486. *
  2487. * Look through the connection array, and choose a router that maximizes
  2488. * the number of pending streams that can exit from this router.
  2489. *
  2490. * Return NULL if we can't find any suitable routers.
  2491. */
  2492. static const node_t *
  2493. choose_good_exit_server_general(int need_uptime, int need_capacity)
  2494. {
  2495. int *n_supported;
  2496. int n_pending_connections = 0;
  2497. smartlist_t *connections;
  2498. int best_support = -1;
  2499. int n_best_support=0;
  2500. const or_options_t *options = get_options();
  2501. const smartlist_t *the_nodes;
  2502. const node_t *node=NULL;
  2503. connections = get_connection_array();
  2504. /* Count how many connections are waiting for a circuit to be built.
  2505. * We use this for log messages now, but in the future we may depend on it.
  2506. */
  2507. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2508. {
  2509. if (ap_stream_wants_exit_attention(conn))
  2510. ++n_pending_connections;
  2511. });
  2512. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2513. // n_pending_connections);
  2514. /* Now we count, for each of the routers in the directory, how many
  2515. * of the pending connections could possibly exit from that
  2516. * router (n_supported[i]). (We can't be sure about cases where we
  2517. * don't know the IP address of the pending connection.)
  2518. *
  2519. * -1 means "Don't use this router at all."
  2520. */
  2521. the_nodes = nodelist_get_list();
  2522. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  2523. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2524. const int i = node_sl_idx;
  2525. if (router_digest_is_me(node->identity)) {
  2526. n_supported[i] = -1;
  2527. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2528. /* XXX there's probably a reverse predecessor attack here, but
  2529. * it's slow. should we take this out? -RD
  2530. */
  2531. continue;
  2532. }
  2533. if (!node_has_descriptor(node)) {
  2534. n_supported[i] = -1;
  2535. continue;
  2536. }
  2537. if (!node->is_running || node->is_bad_exit) {
  2538. n_supported[i] = -1;
  2539. continue; /* skip routers that are known to be down or bad exits */
  2540. }
  2541. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2542. /* never pick a non-general node as a random exit. */
  2543. n_supported[i] = -1;
  2544. continue;
  2545. }
  2546. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  2547. n_supported[i] = -1;
  2548. continue; /* user asked us not to use it, no matter what */
  2549. }
  2550. if (options->ExitNodes &&
  2551. !routerset_contains_node(options->ExitNodes, node)) {
  2552. n_supported[i] = -1;
  2553. continue; /* not one of our chosen exit nodes */
  2554. }
  2555. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2556. n_supported[i] = -1;
  2557. continue; /* skip routers that are not suitable. Don't worry if
  2558. * this makes us reject all the possible routers: if so,
  2559. * we'll retry later in this function with need_update and
  2560. * need_capacity set to 0. */
  2561. }
  2562. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  2563. /* if it's invalid and we don't want it */
  2564. n_supported[i] = -1;
  2565. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2566. // router->nickname, i);
  2567. continue; /* skip invalid routers */
  2568. }
  2569. if (options->ExcludeSingleHopRelays &&
  2570. node_allows_single_hop_exits(node)) {
  2571. n_supported[i] = -1;
  2572. continue;
  2573. }
  2574. if (node_exit_policy_rejects_all(node)) {
  2575. n_supported[i] = -1;
  2576. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2577. // router->nickname, i);
  2578. continue; /* skip routers that reject all */
  2579. }
  2580. n_supported[i] = 0;
  2581. /* iterate over connections */
  2582. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  2583. if (!ap_stream_wants_exit_attention(conn))
  2584. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2585. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  2586. ++n_supported[i];
  2587. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2588. // router->nickname, i, n_supported[i]);
  2589. } else {
  2590. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2591. // router->nickname, i);
  2592. }
  2593. } SMARTLIST_FOREACH_END(conn);
  2594. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2595. /* Leave best_support at -1 if that's where it is, so we can
  2596. * distinguish it later. */
  2597. continue;
  2598. }
  2599. if (n_supported[i] > best_support) {
  2600. /* If this router is better than previous ones, remember its index
  2601. * and goodness, and start counting how many routers are this good. */
  2602. best_support = n_supported[i]; n_best_support=1;
  2603. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2604. // router->nickname);
  2605. } else if (n_supported[i] == best_support) {
  2606. /* If this router is _as good_ as the best one, just increment the
  2607. * count of equally good routers.*/
  2608. ++n_best_support;
  2609. }
  2610. } SMARTLIST_FOREACH_END(node);
  2611. log_info(LD_CIRC,
  2612. "Found %d servers that might support %d/%d pending connections.",
  2613. n_best_support, best_support >= 0 ? best_support : 0,
  2614. n_pending_connections);
  2615. /* If any routers definitely support any pending connections, choose one
  2616. * at random. */
  2617. if (best_support > 0) {
  2618. smartlist_t *supporting = smartlist_new();
  2619. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2620. if (n_supported[node_sl_idx] == best_support)
  2621. smartlist_add(supporting, (void*)node);
  2622. });
  2623. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2624. smartlist_free(supporting);
  2625. } else {
  2626. /* Either there are no pending connections, or no routers even seem to
  2627. * possibly support any of them. Choose a router at random that satisfies
  2628. * at least one predicted exit port. */
  2629. int attempt;
  2630. smartlist_t *needed_ports, *supporting;
  2631. if (best_support == -1) {
  2632. if (need_uptime || need_capacity) {
  2633. log_info(LD_CIRC,
  2634. "We couldn't find any live%s%s routers; falling back "
  2635. "to list of all routers.",
  2636. need_capacity?", fast":"",
  2637. need_uptime?", stable":"");
  2638. tor_free(n_supported);
  2639. return choose_good_exit_server_general(0, 0);
  2640. }
  2641. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2642. "choosing a doomed exit at random.",
  2643. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  2644. }
  2645. supporting = smartlist_new();
  2646. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2647. for (attempt = 0; attempt < 2; attempt++) {
  2648. /* try once to pick only from routers that satisfy a needed port,
  2649. * then if there are none, pick from any that support exiting. */
  2650. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2651. if (n_supported[node_sl_idx] != -1 &&
  2652. (attempt || node_handles_some_port(node, needed_ports))) {
  2653. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2654. // try, router->nickname);
  2655. smartlist_add(supporting, (void*)node);
  2656. }
  2657. } SMARTLIST_FOREACH_END(node);
  2658. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2659. if (node)
  2660. break;
  2661. smartlist_clear(supporting);
  2662. /* If we reach this point, we can't actually support any unhandled
  2663. * predicted ports, so clear all the remaining ones. */
  2664. if (smartlist_len(needed_ports))
  2665. rep_hist_remove_predicted_ports(needed_ports);
  2666. }
  2667. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2668. smartlist_free(needed_ports);
  2669. smartlist_free(supporting);
  2670. }
  2671. tor_free(n_supported);
  2672. if (node) {
  2673. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2674. return node;
  2675. }
  2676. if (options->ExitNodes) {
  2677. log_warn(LD_CIRC,
  2678. "No specified %sexit routers seem to be running: "
  2679. "can't choose an exit.",
  2680. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  2681. }
  2682. return NULL;
  2683. }
  2684. /** Return a pointer to a suitable router to be the exit node for the
  2685. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2686. * if no router is suitable).
  2687. *
  2688. * For general-purpose circuits, pass it off to
  2689. * choose_good_exit_server_general()
  2690. *
  2691. * For client-side rendezvous circuits, choose a random node, weighted
  2692. * toward the preferences in 'options'.
  2693. */
  2694. static const node_t *
  2695. choose_good_exit_server(uint8_t purpose,
  2696. int need_uptime, int need_capacity, int is_internal)
  2697. {
  2698. const or_options_t *options = get_options();
  2699. router_crn_flags_t flags = CRN_NEED_DESC;
  2700. if (need_uptime)
  2701. flags |= CRN_NEED_UPTIME;
  2702. if (need_capacity)
  2703. flags |= CRN_NEED_CAPACITY;
  2704. switch (purpose) {
  2705. case CIRCUIT_PURPOSE_C_GENERAL:
  2706. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2707. flags |= CRN_ALLOW_INVALID;
  2708. if (is_internal) /* pick it like a middle hop */
  2709. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2710. else
  2711. return choose_good_exit_server_general(need_uptime,need_capacity);
  2712. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2713. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  2714. flags |= CRN_ALLOW_INVALID;
  2715. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2716. }
  2717. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2718. tor_fragile_assert();
  2719. return NULL;
  2720. }
  2721. /** Log a warning if the user specified an exit for the circuit that
  2722. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2723. static void
  2724. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2725. {
  2726. const or_options_t *options = get_options();
  2727. routerset_t *rs = options->ExcludeNodes;
  2728. const char *description;
  2729. uint8_t purpose = circ->base_.purpose;
  2730. if (circ->build_state->onehop_tunnel)
  2731. return;
  2732. switch (purpose)
  2733. {
  2734. default:
  2735. case CIRCUIT_PURPOSE_OR:
  2736. case CIRCUIT_PURPOSE_INTRO_POINT:
  2737. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2738. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2739. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2740. (int)purpose,
  2741. circuit_purpose_to_string(purpose));
  2742. return;
  2743. case CIRCUIT_PURPOSE_C_GENERAL:
  2744. if (circ->build_state->is_internal)
  2745. return;
  2746. description = "requested exit node";
  2747. rs = options->ExcludeExitNodesUnion_;
  2748. break;
  2749. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2750. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2751. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2752. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2753. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2754. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2755. case CIRCUIT_PURPOSE_TESTING:
  2756. return;
  2757. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2758. case CIRCUIT_PURPOSE_C_REND_READY:
  2759. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2760. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2761. description = "chosen rendezvous point";
  2762. break;
  2763. case CIRCUIT_PURPOSE_CONTROLLER:
  2764. rs = options->ExcludeExitNodesUnion_;
  2765. description = "controller-selected circuit target";
  2766. break;
  2767. }
  2768. if (routerset_contains_extendinfo(rs, exit)) {
  2769. /* We should never get here if StrictNodes is set to 1. */
  2770. if (options->StrictNodes) {
  2771. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2772. "even though StrictNodes is set. Please report. "
  2773. "(Circuit purpose: %s)",
  2774. description, extend_info_describe(exit),
  2775. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2776. circuit_purpose_to_string(purpose));
  2777. } else {
  2778. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2779. "ExcludeNodes%s, because no better options were available. To "
  2780. "prevent this (and possibly break your Tor functionality), "
  2781. "set the StrictNodes configuration option. "
  2782. "(Circuit purpose: %s)",
  2783. description, extend_info_describe(exit),
  2784. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2785. circuit_purpose_to_string(purpose));
  2786. }
  2787. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2788. }
  2789. return;
  2790. }
  2791. /** Decide a suitable length for circ's cpath, and pick an exit
  2792. * router (or use <b>exit</b> if provided). Store these in the
  2793. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2794. static int
  2795. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2796. {
  2797. cpath_build_state_t *state = circ->build_state;
  2798. if (state->onehop_tunnel) {
  2799. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2800. state->desired_path_len = 1;
  2801. } else {
  2802. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  2803. if (r < 1) /* must be at least 1 */
  2804. return -1;
  2805. state->desired_path_len = r;
  2806. }
  2807. if (exit) { /* the circuit-builder pre-requested one */
  2808. warn_if_last_router_excluded(circ, exit);
  2809. log_info(LD_CIRC,"Using requested exit node '%s'",
  2810. extend_info_describe(exit));
  2811. exit = extend_info_dup(exit);
  2812. } else { /* we have to decide one */
  2813. const node_t *node =
  2814. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  2815. state->need_capacity, state->is_internal);
  2816. if (!node) {
  2817. log_warn(LD_CIRC,"failed to choose an exit server");
  2818. return -1;
  2819. }
  2820. exit = extend_info_from_node(node, 0);
  2821. tor_assert(exit);
  2822. }
  2823. state->chosen_exit = exit;
  2824. return 0;
  2825. }
  2826. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2827. * hop to the cpath reflecting this. Don't send the next extend cell --
  2828. * the caller will do this if it wants to.
  2829. */
  2830. int
  2831. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2832. {
  2833. cpath_build_state_t *state;
  2834. tor_assert(exit);
  2835. tor_assert(circ);
  2836. state = circ->build_state;
  2837. tor_assert(state);
  2838. extend_info_free(state->chosen_exit);
  2839. state->chosen_exit = extend_info_dup(exit);
  2840. ++circ->build_state->desired_path_len;
  2841. onion_append_hop(&circ->cpath, exit);
  2842. return 0;
  2843. }
  2844. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2845. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2846. * send the next extend cell to begin connecting to that hop.
  2847. */
  2848. int
  2849. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2850. {
  2851. int err_reason = 0;
  2852. warn_if_last_router_excluded(circ, exit);
  2853. tor_gettimeofday(&circ->base_.timestamp_began);
  2854. circuit_append_new_exit(circ, exit);
  2855. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2856. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2857. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2858. extend_info_describe(exit));
  2859. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2860. return -1;
  2861. }
  2862. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  2863. return 0;
  2864. }
  2865. /** Return the number of routers in <b>routers</b> that are currently up
  2866. * and available for building circuits through.
  2867. */
  2868. static int
  2869. count_acceptable_nodes(smartlist_t *nodes)
  2870. {
  2871. int num=0;
  2872. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2873. // log_debug(LD_CIRC,
  2874. // "Contemplating whether router %d (%s) is a new option.",
  2875. // i, r->nickname);
  2876. if (! node->is_running)
  2877. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2878. continue;
  2879. if (! node->is_valid)
  2880. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2881. continue;
  2882. if (! node_has_descriptor(node))
  2883. continue;
  2884. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2885. * allows this node in some places, then we're getting an inaccurate
  2886. * count. For now, be conservative and don't count it. But later we
  2887. * should try to be smarter. */
  2888. ++num;
  2889. } SMARTLIST_FOREACH_END(node);
  2890. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2891. return num;
  2892. }
  2893. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2894. * This function is used to extend cpath by another hop.
  2895. */
  2896. void
  2897. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2898. {
  2899. if (*head_ptr) {
  2900. new_hop->next = (*head_ptr);
  2901. new_hop->prev = (*head_ptr)->prev;
  2902. (*head_ptr)->prev->next = new_hop;
  2903. (*head_ptr)->prev = new_hop;
  2904. } else {
  2905. *head_ptr = new_hop;
  2906. new_hop->prev = new_hop->next = new_hop;
  2907. }
  2908. }
  2909. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2910. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2911. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2912. * circuit. In particular, make sure we don't pick the exit node or its
  2913. * family, and make sure we don't duplicate any previous nodes or their
  2914. * families. */
  2915. static const node_t *
  2916. choose_good_middle_server(uint8_t purpose,
  2917. cpath_build_state_t *state,
  2918. crypt_path_t *head,
  2919. int cur_len)
  2920. {
  2921. int i;
  2922. const node_t *r, *choice;
  2923. crypt_path_t *cpath;
  2924. smartlist_t *excluded;
  2925. const or_options_t *options = get_options();
  2926. router_crn_flags_t flags = CRN_NEED_DESC;
  2927. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2928. purpose <= CIRCUIT_PURPOSE_MAX_);
  2929. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2930. excluded = smartlist_new();
  2931. if ((r = build_state_get_exit_node(state))) {
  2932. nodelist_add_node_and_family(excluded, r);
  2933. }
  2934. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2935. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2936. nodelist_add_node_and_family(excluded, r);
  2937. }
  2938. }
  2939. if (state->need_uptime)
  2940. flags |= CRN_NEED_UPTIME;
  2941. if (state->need_capacity)
  2942. flags |= CRN_NEED_CAPACITY;
  2943. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2944. flags |= CRN_ALLOW_INVALID;
  2945. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2946. smartlist_free(excluded);
  2947. return choice;
  2948. }
  2949. /** Pick a good entry server for the circuit to be built according to
  2950. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2951. * router (if we're an OR), and respect firewall settings; if we're
  2952. * configured to use entry guards, return one.
  2953. *
  2954. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2955. * guard, not for any particular circuit.
  2956. */
  2957. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2958. const node_t *
  2959. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2960. {
  2961. const node_t *choice;
  2962. smartlist_t *excluded;
  2963. const or_options_t *options = get_options();
  2964. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2965. const node_t *node;
  2966. if (state && options->UseEntryGuards &&
  2967. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2968. /* This request is for an entry server to use for a regular circuit,
  2969. * and we use entry guard nodes. Just return one of the guard nodes. */
  2970. return choose_random_entry(state);
  2971. }
  2972. excluded = smartlist_new();
  2973. if (state && (node = build_state_get_exit_node(state))) {
  2974. /* Exclude the exit node from the state, if we have one. Also exclude its
  2975. * family. */
  2976. nodelist_add_node_and_family(excluded, node);
  2977. }
  2978. if (firewall_is_fascist_or()) {
  2979. /* Exclude all ORs that we can't reach through our firewall */
  2980. smartlist_t *nodes = nodelist_get_list();
  2981. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2982. if (!fascist_firewall_allows_node(node))
  2983. smartlist_add(excluded, (void*)node);
  2984. });
  2985. }
  2986. /* and exclude current entry guards and their families, if applicable */
  2987. if (options->UseEntryGuards) {
  2988. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2989. {
  2990. if ((node = node_get_by_id(entry->identity))) {
  2991. nodelist_add_node_and_family(excluded, node);
  2992. }
  2993. });
  2994. }
  2995. if (state) {
  2996. if (state->need_uptime)
  2997. flags |= CRN_NEED_UPTIME;
  2998. if (state->need_capacity)
  2999. flags |= CRN_NEED_CAPACITY;
  3000. }
  3001. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  3002. flags |= CRN_ALLOW_INVALID;
  3003. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  3004. smartlist_free(excluded);
  3005. return choice;
  3006. }
  3007. /** Return the first non-open hop in cpath, or return NULL if all
  3008. * hops are open. */
  3009. static crypt_path_t *
  3010. onion_next_hop_in_cpath(crypt_path_t *cpath)
  3011. {
  3012. crypt_path_t *hop = cpath;
  3013. do {
  3014. if (hop->state != CPATH_STATE_OPEN)
  3015. return hop;
  3016. hop = hop->next;
  3017. } while (hop != cpath);
  3018. return NULL;
  3019. }
  3020. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  3021. * based on <b>state</b>. Append the hop info to head_ptr.
  3022. */
  3023. static int
  3024. onion_extend_cpath(origin_circuit_t *circ)
  3025. {
  3026. uint8_t purpose = circ->base_.purpose;
  3027. cpath_build_state_t *state = circ->build_state;
  3028. int cur_len = circuit_get_cpath_len(circ);
  3029. extend_info_t *info = NULL;
  3030. if (cur_len >= state->desired_path_len) {
  3031. log_debug(LD_CIRC, "Path is complete: %d steps long",
  3032. state->desired_path_len);
  3033. return 1;
  3034. }
  3035. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  3036. state->desired_path_len);
  3037. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  3038. info = extend_info_dup(state->chosen_exit);
  3039. } else if (cur_len == 0) { /* picking first node */
  3040. const node_t *r = choose_good_entry_server(purpose, state);
  3041. if (r) {
  3042. /* If we're a client, use the preferred address rather than the
  3043. primary address, for potentially connecting to an IPv6 OR
  3044. port. */
  3045. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  3046. tor_assert(info);
  3047. }
  3048. } else {
  3049. const node_t *r =
  3050. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  3051. if (r) {
  3052. info = extend_info_from_node(r, 0);
  3053. tor_assert(info);
  3054. }
  3055. }
  3056. if (!info) {
  3057. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  3058. "this circuit.", cur_len);
  3059. return -1;
  3060. }
  3061. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  3062. extend_info_describe(info),
  3063. cur_len+1, build_state_get_exit_nickname(state));
  3064. onion_append_hop(&circ->cpath, info);
  3065. extend_info_free(info);
  3066. return 0;
  3067. }
  3068. /** Create a new hop, annotate it with information about its
  3069. * corresponding router <b>choice</b>, and append it to the
  3070. * end of the cpath <b>head_ptr</b>. */
  3071. static int
  3072. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  3073. {
  3074. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  3075. /* link hop into the cpath, at the end. */
  3076. onion_append_to_cpath(head_ptr, hop);
  3077. hop->magic = CRYPT_PATH_MAGIC;
  3078. hop->state = CPATH_STATE_CLOSED;
  3079. hop->extend_info = extend_info_dup(choice);
  3080. hop->package_window = circuit_initial_package_window();
  3081. hop->deliver_window = CIRCWINDOW_START;
  3082. return 0;
  3083. }
  3084. /** Allocate a new extend_info object based on the various arguments. */
  3085. extend_info_t *
  3086. extend_info_new(const char *nickname, const char *digest,
  3087. crypto_pk_t *onion_key,
  3088. const curve25519_public_key_t *curve25519_key,
  3089. const tor_addr_t *addr, uint16_t port)
  3090. {
  3091. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  3092. memcpy(info->identity_digest, digest, DIGEST_LEN);
  3093. if (nickname)
  3094. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  3095. if (onion_key)
  3096. info->onion_key = crypto_pk_dup_key(onion_key);
  3097. #ifdef CURVE25519_ENABLED
  3098. if (curve25519_key)
  3099. memcpy(&info->curve25519_onion_key, curve25519_key,
  3100. sizeof(curve25519_public_key_t));
  3101. #else
  3102. (void)curve25519_key;
  3103. #endif
  3104. tor_addr_copy(&info->addr, addr);
  3105. info->port = port;
  3106. return info;
  3107. }
  3108. /** Allocate and return a new extend_info that can be used to build a
  3109. * circuit to or through the node <b>node</b>. Use the primary address
  3110. * of the node (i.e. its IPv4 address) unless
  3111. * <b>for_direct_connect</b> is true, in which case the preferred
  3112. * address is used instead. May return NULL if there is not enough
  3113. * info about <b>node</b> to extend to it--for example, if there is no
  3114. * routerinfo_t or microdesc_t.
  3115. **/
  3116. extend_info_t *
  3117. extend_info_from_node(const node_t *node, int for_direct_connect)
  3118. {
  3119. tor_addr_port_t ap;
  3120. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  3121. return NULL;
  3122. if (for_direct_connect)
  3123. node_get_pref_orport(node, &ap);
  3124. else
  3125. node_get_prim_orport(node, &ap);
  3126. log_debug(LD_CIRC, "using %s for %s",
  3127. fmt_addrport(&ap.addr, ap.port),
  3128. node->ri ? node->ri->nickname : node->rs->nickname);
  3129. if (node->ri)
  3130. return extend_info_new(node->ri->nickname,
  3131. node->identity,
  3132. node->ri->onion_pkey,
  3133. node->ri->onion_curve25519_pkey,
  3134. &ap.addr,
  3135. ap.port);
  3136. else if (node->rs && node->md)
  3137. return extend_info_new(node->rs->nickname,
  3138. node->identity,
  3139. node->md->onion_pkey,
  3140. node->md->onion_curve25519_pkey,
  3141. &ap.addr,
  3142. ap.port);
  3143. else
  3144. return NULL;
  3145. }
  3146. /** Release storage held by an extend_info_t struct. */
  3147. void
  3148. extend_info_free(extend_info_t *info)
  3149. {
  3150. if (!info)
  3151. return;
  3152. crypto_pk_free(info->onion_key);
  3153. tor_free(info);
  3154. }
  3155. /** Allocate and return a new extend_info_t with the same contents as
  3156. * <b>info</b>. */
  3157. extend_info_t *
  3158. extend_info_dup(extend_info_t *info)
  3159. {
  3160. extend_info_t *newinfo;
  3161. tor_assert(info);
  3162. newinfo = tor_malloc(sizeof(extend_info_t));
  3163. memcpy(newinfo, info, sizeof(extend_info_t));
  3164. if (info->onion_key)
  3165. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  3166. else
  3167. newinfo->onion_key = NULL;
  3168. return newinfo;
  3169. }
  3170. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  3171. * If there is no chosen exit, or if we don't know the routerinfo_t for
  3172. * the chosen exit, return NULL.
  3173. */
  3174. const node_t *
  3175. build_state_get_exit_node(cpath_build_state_t *state)
  3176. {
  3177. if (!state || !state->chosen_exit)
  3178. return NULL;
  3179. return node_get_by_id(state->chosen_exit->identity_digest);
  3180. }
  3181. /** Return the nickname for the chosen exit router in <b>state</b>. If
  3182. * there is no chosen exit, or if we don't know the routerinfo_t for the
  3183. * chosen exit, return NULL.
  3184. */
  3185. const char *
  3186. build_state_get_exit_nickname(cpath_build_state_t *state)
  3187. {
  3188. if (!state || !state->chosen_exit)
  3189. return NULL;
  3190. return state->chosen_exit->nickname;
  3191. }