circuitbuild.c 122 KB

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