circuitbuild.c 128 KB

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