circuitbuild.c 126 KB

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