circuitbuild.c 129 KB

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