circuitbuild.c 128 KB

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