circuitbuild.c 126 KB

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