circuitbuild.c 126 KB

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