circuitbuild.c 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514
  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. /* If a measurement circ ever gets back to us, consider it
  751. * succeeded for path bias */
  752. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  753. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  754. }
  755. return 0;
  756. }
  757. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  758. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  759. return - END_CIRC_REASON_INTERNAL;
  760. }
  761. {
  762. const node_t *prev_node;
  763. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  764. circuit_pick_extend_handshake(&ec.cell_type,
  765. &ec.create_cell.cell_type,
  766. &ec.create_cell.handshake_type,
  767. prev_node,
  768. hop->extend_info);
  769. }
  770. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  771. ec.orport_ipv4.port = hop->extend_info->port;
  772. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  773. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  774. len = onion_skin_create(ec.create_cell.handshake_type,
  775. hop->extend_info,
  776. &hop->handshake_state,
  777. ec.create_cell.onionskin);
  778. if (len < 0) {
  779. log_warn(LD_CIRC,"onion_skin_create failed.");
  780. return - END_CIRC_REASON_INTERNAL;
  781. }
  782. ec.create_cell.handshake_len = len;
  783. log_info(LD_CIRC,"Sending extend relay cell.");
  784. note_request("cell: extend", 1);
  785. {
  786. uint8_t command = 0;
  787. uint16_t payload_len=0;
  788. uint8_t payload[RELAY_PAYLOAD_SIZE];
  789. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  790. log_warn(LD_CIRC,"Couldn't format extend cell");
  791. return -END_CIRC_REASON_INTERNAL;
  792. }
  793. /* send it to hop->prev, because it will transfer
  794. * it to a create cell and then send to hop */
  795. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  796. command,
  797. (char*)payload, payload_len,
  798. hop->prev) < 0)
  799. return 0; /* circuit is closed */
  800. }
  801. hop->state = CPATH_STATE_AWAITING_KEYS;
  802. }
  803. return 0;
  804. }
  805. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  806. * something has also gone wrong with our network: notify the user,
  807. * and abandon all not-yet-used circuits. */
  808. void
  809. circuit_note_clock_jumped(int seconds_elapsed)
  810. {
  811. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  812. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  813. "assuming established circuits no longer work.",
  814. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  815. seconds_elapsed >=0 ? "forward" : "backward");
  816. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  817. seconds_elapsed);
  818. can_complete_circuit=0; /* so it'll log when it works again */
  819. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  820. "CLOCK_JUMPED");
  821. circuit_mark_all_unused_circs();
  822. circuit_expire_all_dirty_circs();
  823. }
  824. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  825. * skin and identity digest for the next hop. If we're already connected,
  826. * pass the onion skin to the next hop using a create cell; otherwise
  827. * launch a new OR connection, and <b>circ</b> will notice when the
  828. * connection succeeds or fails.
  829. *
  830. * Return -1 if we want to warn and tear down the circuit, else return 0.
  831. */
  832. int
  833. circuit_extend(cell_t *cell, circuit_t *circ)
  834. {
  835. channel_t *n_chan;
  836. relay_header_t rh;
  837. extend_cell_t ec;
  838. const char *msg = NULL;
  839. int should_launch = 0;
  840. if (circ->n_chan) {
  841. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  842. "n_chan already set. Bug/attack. Closing.");
  843. return -1;
  844. }
  845. if (circ->n_hop) {
  846. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  847. "conn to next hop already launched. Bug/attack. Closing.");
  848. return -1;
  849. }
  850. if (!server_mode(get_options())) {
  851. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  852. "Got an extend cell, but running as a client. Closing.");
  853. return -1;
  854. }
  855. relay_header_unpack(&rh, cell->payload);
  856. if (extend_cell_parse(&ec, rh.command,
  857. cell->payload+RELAY_HEADER_SIZE,
  858. rh.length) < 0) {
  859. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  860. "Can't parse extend cell. Closing circuit.");
  861. return -1;
  862. }
  863. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  864. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  865. "Client asked me to extend to zero destination port or addr.");
  866. return -1;
  867. }
  868. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  869. !get_options()->ExtendAllowPrivateAddresses) {
  870. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  871. "Client asked me to extend to a private address");
  872. return -1;
  873. }
  874. /* Check if they asked us for 0000..0000. We support using
  875. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  876. * but we don't want to let people send us extend cells for empty
  877. * fingerprints -- a) because it opens the user up to a mitm attack,
  878. * and b) because it lets an attacker force the relay to hold open a
  879. * new TLS connection for each extend request. */
  880. if (tor_digest_is_zero((const char*)ec.node_id)) {
  881. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  882. "Client asked me to extend without specifying an id_digest.");
  883. return -1;
  884. }
  885. /* Next, check if we're being asked to connect to the hop that the
  886. * extend cell came from. There isn't any reason for that, and it can
  887. * assist circular-path attacks. */
  888. if (tor_memeq(ec.node_id,
  889. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  890. DIGEST_LEN)) {
  891. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  892. "Client asked me to extend back to the previous hop.");
  893. return -1;
  894. }
  895. n_chan = channel_get_for_extend((const char*)ec.node_id,
  896. &ec.orport_ipv4.addr,
  897. &msg,
  898. &should_launch);
  899. if (!n_chan) {
  900. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  901. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  902. msg?msg:"????");
  903. circ->n_hop = extend_info_new(NULL /*nickname*/,
  904. (const char*)ec.node_id,
  905. NULL /*onion_key*/,
  906. NULL /*curve25519_key*/,
  907. &ec.orport_ipv4.addr,
  908. ec.orport_ipv4.port);
  909. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  910. sizeof(ec.create_cell));
  911. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  912. if (should_launch) {
  913. /* we should try to open a connection */
  914. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  915. ec.orport_ipv4.port,
  916. (const char*)ec.node_id);
  917. if (!n_chan) {
  918. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  919. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  920. return 0;
  921. }
  922. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  923. }
  924. /* return success. The onion/circuit/etc will be taken care of
  925. * automatically (may already have been) whenever n_chan reaches
  926. * OR_CONN_STATE_OPEN.
  927. */
  928. return 0;
  929. }
  930. tor_assert(!circ->n_hop); /* Connection is already established. */
  931. circ->n_chan = n_chan;
  932. log_debug(LD_CIRC,
  933. "n_chan is %s",
  934. channel_get_canonical_remote_descr(n_chan));
  935. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  936. return -1;
  937. return 0;
  938. }
  939. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  940. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  941. * used as follows:
  942. * - 20 to initialize f_digest
  943. * - 20 to initialize b_digest
  944. * - 16 to key f_crypto
  945. * - 16 to key b_crypto
  946. *
  947. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  948. */
  949. int
  950. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  951. int reverse)
  952. {
  953. crypto_digest_t *tmp_digest;
  954. crypto_cipher_t *tmp_crypto;
  955. tor_assert(cpath);
  956. tor_assert(key_data);
  957. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  958. cpath->f_digest || cpath->b_digest));
  959. cpath->f_digest = crypto_digest_new();
  960. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  961. cpath->b_digest = crypto_digest_new();
  962. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  963. if (!(cpath->f_crypto =
  964. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  965. log_warn(LD_BUG,"Forward cipher initialization failed.");
  966. return -1;
  967. }
  968. if (!(cpath->b_crypto =
  969. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  970. log_warn(LD_BUG,"Backward cipher initialization failed.");
  971. return -1;
  972. }
  973. if (reverse) {
  974. tmp_digest = cpath->f_digest;
  975. cpath->f_digest = cpath->b_digest;
  976. cpath->b_digest = tmp_digest;
  977. tmp_crypto = cpath->f_crypto;
  978. cpath->f_crypto = cpath->b_crypto;
  979. cpath->b_crypto = tmp_crypto;
  980. }
  981. return 0;
  982. }
  983. /** The minimum number of circuit attempts before we start
  984. * thinking about warning about path bias and dropping guards */
  985. static int
  986. pathbias_get_min_circs(const or_options_t *options)
  987. {
  988. #define DFLT_PATH_BIAS_MIN_CIRC 150
  989. if (options->PathBiasCircThreshold >= 5)
  990. return options->PathBiasCircThreshold;
  991. else
  992. return networkstatus_get_param(NULL, "pb_mincircs",
  993. DFLT_PATH_BIAS_MIN_CIRC,
  994. 5, INT32_MAX);
  995. }
  996. /** The circuit success rate below which we issue a notice */
  997. static double
  998. pathbias_get_notice_rate(const or_options_t *options)
  999. {
  1000. #define DFLT_PATH_BIAS_NOTICE_PCT 70
  1001. if (options->PathBiasNoticeRate >= 0.0)
  1002. return options->PathBiasNoticeRate;
  1003. else
  1004. return networkstatus_get_param(NULL, "pb_noticepct",
  1005. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  1006. }
  1007. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1008. /** The circuit success rate below which we issue a warn */
  1009. static double
  1010. pathbias_get_warn_rate(const or_options_t *options)
  1011. {
  1012. #define DFLT_PATH_BIAS_WARN_PCT 50
  1013. if (options->PathBiasWarnRate >= 0.0)
  1014. return options->PathBiasWarnRate;
  1015. else
  1016. return networkstatus_get_param(NULL, "pb_warnpct",
  1017. DFLT_PATH_BIAS_WARN_PCT, 0, 100)/100.0;
  1018. }
  1019. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1020. /**
  1021. * The extreme rate is the rate at which we would drop the guard,
  1022. * if pb_dropguard is also set. Otherwise we just warn.
  1023. */
  1024. double
  1025. pathbias_get_extreme_rate(const or_options_t *options)
  1026. {
  1027. #define DFLT_PATH_BIAS_EXTREME_PCT 30
  1028. if (options->PathBiasExtremeRate >= 0.0)
  1029. return options->PathBiasExtremeRate;
  1030. else
  1031. return networkstatus_get_param(NULL, "pb_extremepct",
  1032. DFLT_PATH_BIAS_EXTREME_PCT, 0, 100)/100.0;
  1033. }
  1034. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1035. /**
  1036. * If 1, we actually disable use of guards that fall below
  1037. * the extreme_pct.
  1038. */
  1039. int
  1040. pathbias_get_dropguards(const or_options_t *options)
  1041. {
  1042. #define DFLT_PATH_BIAS_DROP_GUARDS 0
  1043. if (options->PathBiasDropGuards >= 0)
  1044. return options->PathBiasDropGuards;
  1045. else
  1046. return networkstatus_get_param(NULL, "pb_dropguards",
  1047. DFLT_PATH_BIAS_DROP_GUARDS, 0, 1);
  1048. }
  1049. /**
  1050. * This is the number of circuits at which we scale our
  1051. * counts by mult_factor/scale_factor. Note, this count is
  1052. * not exact, as we only perform the scaling in the event
  1053. * of no integer truncation.
  1054. */
  1055. static int
  1056. pathbias_get_scale_threshold(const or_options_t *options)
  1057. {
  1058. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
  1059. if (options->PathBiasScaleThreshold >= 10)
  1060. return options->PathBiasScaleThreshold;
  1061. else
  1062. return networkstatus_get_param(NULL, "pb_scalecircs",
  1063. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  1064. INT32_MAX);
  1065. }
  1066. /**
  1067. * The scale factor is the denominator for our scaling
  1068. * of circuit counts for our path bias window.
  1069. *
  1070. * Note that our use of doubles for the path bias state
  1071. * file means that powers of 2 work best here.
  1072. */
  1073. static int
  1074. pathbias_get_scale_factor(const or_options_t *options)
  1075. {
  1076. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  1077. if (options->PathBiasScaleFactor >= 1)
  1078. return options->PathBiasScaleFactor;
  1079. else
  1080. return networkstatus_get_param(NULL, "pb_scalefactor",
  1081. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  1082. }
  1083. /**
  1084. * The mult factor is the numerator for our scaling
  1085. * of circuit counts for our path bias window. It
  1086. * allows us to scale by fractions.
  1087. */
  1088. static int
  1089. pathbias_get_mult_factor(const or_options_t *options)
  1090. {
  1091. #define DFLT_PATH_BIAS_MULT_FACTOR 1
  1092. if (options->PathBiasMultFactor >= 1)
  1093. return options->PathBiasMultFactor;
  1094. else
  1095. return networkstatus_get_param(NULL, "pb_multfactor",
  1096. DFLT_PATH_BIAS_MULT_FACTOR, 1,
  1097. pathbias_get_scale_factor(options));
  1098. }
  1099. /** The minimum number of circuit usage attempts before we start
  1100. * thinking about warning about path use bias and dropping guards */
  1101. static int
  1102. pathbias_get_min_use(const or_options_t *options)
  1103. {
  1104. #define DFLT_PATH_BIAS_MIN_USE 20
  1105. if (options->PathBiasUseThreshold >= 3)
  1106. return options->PathBiasUseThreshold;
  1107. else
  1108. return networkstatus_get_param(NULL, "pb_minuse",
  1109. DFLT_PATH_BIAS_MIN_USE,
  1110. 3, INT32_MAX);
  1111. }
  1112. /** The circuit use success rate below which we issue a notice */
  1113. static double
  1114. pathbias_get_notice_use_rate(const or_options_t *options)
  1115. {
  1116. #define DFLT_PATH_BIAS_NOTICE_USE_PCT 90
  1117. if (options->PathBiasNoticeUseRate >= 0.0)
  1118. return options->PathBiasNoticeUseRate;
  1119. else
  1120. return networkstatus_get_param(NULL, "pb_noticeusepct",
  1121. DFLT_PATH_BIAS_NOTICE_USE_PCT,
  1122. 0, 100)/100.0;
  1123. }
  1124. /**
  1125. * The extreme use rate is the rate at which we would drop the guard,
  1126. * if pb_dropguard is also set. Otherwise we just warn.
  1127. */
  1128. double
  1129. pathbias_get_extreme_use_rate(const or_options_t *options)
  1130. {
  1131. #define DFLT_PATH_BIAS_EXTREME_USE_PCT 70
  1132. if (options->PathBiasExtremeUseRate >= 0.0)
  1133. return options->PathBiasExtremeUseRate;
  1134. else
  1135. return networkstatus_get_param(NULL, "pb_extremeusepct",
  1136. DFLT_PATH_BIAS_EXTREME_USE_PCT,
  1137. 0, 100)/100.0;
  1138. }
  1139. /**
  1140. * This is the number of circuits at which we scale our
  1141. * use counts by mult_factor/scale_factor. Note, this count is
  1142. * not exact, as we only perform the scaling in the event
  1143. * of no integer truncation.
  1144. */
  1145. static int
  1146. pathbias_get_scale_use_threshold(const or_options_t *options)
  1147. {
  1148. #define DFLT_PATH_BIAS_SCALE_USE_THRESHOLD 100
  1149. if (options->PathBiasScaleUseThreshold >= 10)
  1150. return options->PathBiasScaleUseThreshold;
  1151. else
  1152. return networkstatus_get_param(NULL, "pb_scaleuse",
  1153. DFLT_PATH_BIAS_SCALE_USE_THRESHOLD,
  1154. 10, INT32_MAX);
  1155. }
  1156. /**
  1157. * Convert a Guard's path state to string.
  1158. */
  1159. static const char *
  1160. pathbias_state_to_string(path_state_t state)
  1161. {
  1162. switch (state) {
  1163. case PATH_STATE_NEW_CIRC:
  1164. return "new";
  1165. case PATH_STATE_BUILD_ATTEMPTED:
  1166. return "build attempted";
  1167. case PATH_STATE_BUILD_SUCCEEDED:
  1168. return "build succeeded";
  1169. case PATH_STATE_USE_ATTEMPTED:
  1170. return "use attempted";
  1171. case PATH_STATE_USE_SUCCEEDED:
  1172. return "use succeeded";
  1173. case PATH_STATE_USE_FAILED:
  1174. return "use failed";
  1175. case PATH_STATE_ALREADY_COUNTED:
  1176. return "already counted";
  1177. }
  1178. return "unknown";
  1179. }
  1180. /**
  1181. * This function decides if a circuit has progressed far enough to count
  1182. * as a circuit "attempt". As long as end-to-end tagging is possible,
  1183. * we assume the adversary will use it over hop-to-hop failure. Therefore,
  1184. * we only need to account bias for the last hop. This should make us
  1185. * much more resilient to ambient circuit failure, and also make that
  1186. * failure easier to measure (we only need to measure Exit failure rates).
  1187. */
  1188. static int
  1189. pathbias_is_new_circ_attempt(origin_circuit_t *circ)
  1190. {
  1191. #define N2N_TAGGING_IS_POSSIBLE
  1192. #ifdef N2N_TAGGING_IS_POSSIBLE
  1193. /* cpath is a circular list. We want circs with more than one hop,
  1194. * and the second hop must be waiting for keys still (it's just
  1195. * about to get them). */
  1196. return circ->cpath->next != circ->cpath &&
  1197. circ->cpath->next->state == CPATH_STATE_AWAITING_KEYS;
  1198. #else
  1199. /* If tagging attacks are no longer possible, we probably want to
  1200. * count bias from the first hop. However, one could argue that
  1201. * timing-based tagging is still more useful than per-hop failure.
  1202. * In which case, we'd never want to use this.
  1203. */
  1204. return circ->cpath->state == CPATH_STATE_AWAITING_KEYS;
  1205. #endif
  1206. }
  1207. /**
  1208. * Decide if the path bias code should count a circuit.
  1209. *
  1210. * @returns 1 if we should count it, 0 otherwise.
  1211. */
  1212. static int
  1213. pathbias_should_count(origin_circuit_t *circ)
  1214. {
  1215. #define PATHBIAS_COUNT_INTERVAL (600)
  1216. static ratelim_t count_limit =
  1217. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  1218. char *rate_msg = NULL;
  1219. /* We can't do path bias accounting without entry guards.
  1220. * Testing and controller circuits also have no guards.
  1221. *
  1222. * We also don't count server-side rends, because their
  1223. * endpoint could be chosen maliciously.
  1224. * Similarly, we can't count client-side intro attempts,
  1225. * because clients can be manipulated into connecting to
  1226. * malicious intro points. */
  1227. if (get_options()->UseEntryGuards == 0 ||
  1228. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1229. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  1230. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1231. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  1232. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1233. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  1234. return 0;
  1235. }
  1236. /* Completely ignore one hop circuits */
  1237. if (circ->build_state->onehop_tunnel ||
  1238. circ->build_state->desired_path_len == 1) {
  1239. /* Check for inconsistency */
  1240. if (circ->build_state->desired_path_len != 1 ||
  1241. !circ->build_state->onehop_tunnel) {
  1242. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  1243. log_notice(LD_BUG,
  1244. "One-hop circuit has length %d. Path state is %s. "
  1245. "Circuit is a %s currently %s.%s",
  1246. circ->build_state->desired_path_len,
  1247. pathbias_state_to_string(circ->path_state),
  1248. circuit_purpose_to_string(circ->base_.purpose),
  1249. circuit_state_to_string(circ->base_.state),
  1250. rate_msg);
  1251. tor_free(rate_msg);
  1252. }
  1253. tor_fragile_assert();
  1254. }
  1255. return 0;
  1256. }
  1257. return 1;
  1258. }
  1259. /**
  1260. * Check our circuit state to see if this is a successful circuit attempt.
  1261. * If so, record it in the current guard's path bias circ_attempt count.
  1262. *
  1263. * Also check for several potential error cases for bug #6475.
  1264. */
  1265. static int
  1266. pathbias_count_build_attempt(origin_circuit_t *circ)
  1267. {
  1268. #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
  1269. static ratelim_t circ_attempt_notice_limit =
  1270. RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL);
  1271. char *rate_msg = NULL;
  1272. if (!pathbias_should_count(circ)) {
  1273. return 0;
  1274. }
  1275. if (pathbias_is_new_circ_attempt(circ)) {
  1276. /* Help track down the real cause of bug #6475: */
  1277. if (circ->has_opened && circ->path_state != PATH_STATE_BUILD_ATTEMPTED) {
  1278. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1279. approx_time()))) {
  1280. log_info(LD_BUG,
  1281. "Opened circuit is in strange path state %s. "
  1282. "Circuit is a %s currently %s.%s",
  1283. pathbias_state_to_string(circ->path_state),
  1284. circuit_purpose_to_string(circ->base_.purpose),
  1285. circuit_state_to_string(circ->base_.state),
  1286. rate_msg);
  1287. tor_free(rate_msg);
  1288. }
  1289. }
  1290. /* Don't re-count cannibalized circs.. */
  1291. if (!circ->has_opened) {
  1292. entry_guard_t *guard = NULL;
  1293. if (circ->cpath && circ->cpath->extend_info) {
  1294. guard = entry_guard_get_by_id_digest(
  1295. circ->cpath->extend_info->identity_digest);
  1296. } else if (circ->base_.n_chan) {
  1297. guard =
  1298. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1299. }
  1300. if (guard) {
  1301. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1302. circ->path_state = PATH_STATE_BUILD_ATTEMPTED;
  1303. if (entry_guard_inc_circ_attempt_count(guard) < 0) {
  1304. /* Bogus guard; we already warned. */
  1305. return -END_CIRC_REASON_TORPROTOCOL;
  1306. }
  1307. } else {
  1308. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1309. approx_time()))) {
  1310. log_info(LD_BUG,
  1311. "Unopened circuit has 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. } else {
  1321. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1322. approx_time()))) {
  1323. log_info(LD_CIRC,
  1324. "Unopened circuit has no known guard. "
  1325. "Circuit is a %s currently %s.%s",
  1326. circuit_purpose_to_string(circ->base_.purpose),
  1327. circuit_state_to_string(circ->base_.state),
  1328. rate_msg);
  1329. tor_free(rate_msg);
  1330. }
  1331. }
  1332. }
  1333. }
  1334. return 0;
  1335. }
  1336. /**
  1337. * Check our circuit state to see if this is a successful circuit
  1338. * completion. If so, record it in the current guard's path bias
  1339. * success count.
  1340. *
  1341. * Also check for several potential error cases for bug #6475.
  1342. */
  1343. static void
  1344. pathbias_count_build_success(origin_circuit_t *circ)
  1345. {
  1346. #define SUCCESS_NOTICE_INTERVAL (600)
  1347. static ratelim_t success_notice_limit =
  1348. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1349. char *rate_msg = NULL;
  1350. entry_guard_t *guard = NULL;
  1351. if (!pathbias_should_count(circ)) {
  1352. return;
  1353. }
  1354. /* Don't count cannibalized/reused circs for path bias
  1355. * "build" success, since they get counted under "use" success. */
  1356. if (!circ->has_opened) {
  1357. if (circ->cpath && circ->cpath->extend_info) {
  1358. guard = entry_guard_get_by_id_digest(
  1359. circ->cpath->extend_info->identity_digest);
  1360. }
  1361. if (guard) {
  1362. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  1363. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  1364. guard->circ_successes++;
  1365. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  1366. guard->circ_successes, guard->circ_attempts,
  1367. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1368. } else {
  1369. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1370. approx_time()))) {
  1371. log_info(LD_BUG,
  1372. "Succeeded circuit is in strange path state %s. "
  1373. "Circuit is a %s currently %s.%s",
  1374. pathbias_state_to_string(circ->path_state),
  1375. circuit_purpose_to_string(circ->base_.purpose),
  1376. circuit_state_to_string(circ->base_.state),
  1377. rate_msg);
  1378. tor_free(rate_msg);
  1379. }
  1380. }
  1381. if (guard->circ_attempts < guard->circ_successes) {
  1382. log_notice(LD_BUG, "Unexpectedly high successes counts (%f/%f) "
  1383. "for guard %s=%s",
  1384. guard->circ_successes, guard->circ_attempts,
  1385. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1386. }
  1387. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1388. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1389. * No need to log that case. */
  1390. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1391. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1392. approx_time()))) {
  1393. log_info(LD_CIRC,
  1394. "Completed circuit has no known guard. "
  1395. "Circuit is a %s currently %s.%s",
  1396. circuit_purpose_to_string(circ->base_.purpose),
  1397. circuit_state_to_string(circ->base_.state),
  1398. rate_msg);
  1399. tor_free(rate_msg);
  1400. }
  1401. }
  1402. } else {
  1403. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1404. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1405. approx_time()))) {
  1406. log_info(LD_BUG,
  1407. "Opened circuit is in strange path state %s. "
  1408. "Circuit is a %s currently %s.%s",
  1409. pathbias_state_to_string(circ->path_state),
  1410. circuit_purpose_to_string(circ->base_.purpose),
  1411. circuit_state_to_string(circ->base_.state),
  1412. rate_msg);
  1413. tor_free(rate_msg);
  1414. }
  1415. }
  1416. }
  1417. }
  1418. /**
  1419. * Record an attempt to use a circuit. Changes the circuit's
  1420. * path state and update its guard's usage counter.
  1421. *
  1422. * Used for path bias usage accounting.
  1423. */
  1424. void
  1425. pathbias_count_use_attempt(origin_circuit_t *circ)
  1426. {
  1427. entry_guard_t *guard;
  1428. if (!pathbias_should_count(circ)) {
  1429. return;
  1430. }
  1431. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1432. log_notice(LD_BUG,
  1433. "Used circuit is in strange path state %s. "
  1434. "Circuit is a %s currently %s.",
  1435. pathbias_state_to_string(circ->path_state),
  1436. circuit_purpose_to_string(circ->base_.purpose),
  1437. circuit_state_to_string(circ->base_.state));
  1438. } else if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  1439. guard = entry_guard_get_by_id_digest(
  1440. circ->cpath->extend_info->identity_digest);
  1441. if (guard) {
  1442. pathbias_check_use_rate(guard);
  1443. guard->use_attempts++;
  1444. log_debug(LD_CIRC, "Marked circuit %d as used for guard %s=%s.",
  1445. circ->global_identifier, guard->nickname,
  1446. hex_str(guard->identity, DIGEST_LEN));
  1447. }
  1448. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  1449. } else {
  1450. /* Harmless but educational log message */
  1451. log_info(LD_CIRC,
  1452. "Used circuit %d is already in path state %s. "
  1453. "Circuit is a %s currently %s.",
  1454. circ->global_identifier,
  1455. pathbias_state_to_string(circ->path_state),
  1456. circuit_purpose_to_string(circ->base_.purpose),
  1457. circuit_state_to_string(circ->base_.state));
  1458. }
  1459. return;
  1460. }
  1461. /**
  1462. * Check the circuit's path stat is appropriate and it as successfully
  1463. * used.
  1464. *
  1465. * We don't actually increment the guard's counters until
  1466. * pathbias_check_close().
  1467. *
  1468. * Used for path bias usage accounting.
  1469. */
  1470. void
  1471. pathbias_mark_use_success(origin_circuit_t *circ)
  1472. {
  1473. if (!pathbias_should_count(circ)) {
  1474. return;
  1475. }
  1476. if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  1477. log_notice(LD_BUG,
  1478. "Used circuit %d is in strange path state %s. "
  1479. "Circuit is a %s currently %s.",
  1480. circ->global_identifier,
  1481. pathbias_state_to_string(circ->path_state),
  1482. circuit_purpose_to_string(circ->base_.purpose),
  1483. circuit_state_to_string(circ->base_.state));
  1484. pathbias_count_use_attempt(circ);
  1485. }
  1486. /* We don't do any accounting at the guard until actual circuit close */
  1487. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  1488. return;
  1489. }
  1490. /**
  1491. * Actually count a circuit success towards a guard's usage counters
  1492. * if the path state is appropriate.
  1493. */
  1494. static void
  1495. pathbias_count_use_success(origin_circuit_t *circ)
  1496. {
  1497. entry_guard_t *guard;
  1498. if (!pathbias_should_count(circ)) {
  1499. return;
  1500. }
  1501. if (circ->path_state != PATH_STATE_USE_SUCCEEDED) {
  1502. log_notice(LD_BUG,
  1503. "Successfully used circuit %d is in strange path state %s. "
  1504. "Circuit is a %s currently %s.",
  1505. circ->global_identifier,
  1506. pathbias_state_to_string(circ->path_state),
  1507. circuit_purpose_to_string(circ->base_.purpose),
  1508. circuit_state_to_string(circ->base_.state));
  1509. } else {
  1510. guard = entry_guard_get_by_id_digest(
  1511. circ->cpath->extend_info->identity_digest);
  1512. if (guard) {
  1513. guard->use_successes++;
  1514. log_debug(LD_CIRC,
  1515. "Marked circuit %d as used successfully for guard %s=%s.",
  1516. circ->global_identifier, guard->nickname,
  1517. hex_str(guard->identity, DIGEST_LEN));
  1518. }
  1519. }
  1520. return;
  1521. }
  1522. /**
  1523. * Send a probe down a circuit that the client attempted to use,
  1524. * but for which the stream timed out/failed. The probe is a
  1525. * RELAY_BEGIN cell with a 0.a.b.c destination address, which
  1526. * the exit will reject and reply back, echoing that address.
  1527. *
  1528. * The reason for such probes is because it is possible to bias
  1529. * a user's paths simply by causing timeouts, and these timeouts
  1530. * are not possible to differentiate from unresponsive servers.
  1531. *
  1532. * The probe is sent at the end of the circuit lifetime for two
  1533. * reasons: to prevent cryptographic taggers from being able to
  1534. * drop cells to cause timeouts, and to prevent easy recognition
  1535. * of probes before any real client traffic happens.
  1536. *
  1537. * Returns -1 if we couldn't probe, 0 otherwise.
  1538. */
  1539. static int
  1540. pathbias_send_usable_probe(circuit_t *circ)
  1541. {
  1542. /* Based on connection_ap_handshake_send_begin() */
  1543. char payload[CELL_PAYLOAD_SIZE];
  1544. int payload_len;
  1545. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1546. crypt_path_t *cpath_layer = NULL;
  1547. char *probe_nonce = NULL;
  1548. tor_assert(ocirc);
  1549. cpath_layer = ocirc->cpath->prev;
  1550. if (cpath_layer->state != CPATH_STATE_OPEN) {
  1551. /* This can happen for cannibalized circuits. Their
  1552. * last hop isn't yet open */
  1553. log_info(LD_CIRC,
  1554. "Got pathbias probe request for unopened circuit %d. "
  1555. "Opened %d, len %d", ocirc->global_identifier,
  1556. ocirc->has_opened, ocirc->build_state->desired_path_len);
  1557. return -1;
  1558. }
  1559. /* We already went down this road. */
  1560. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING &&
  1561. ocirc->pathbias_probe_id) {
  1562. log_info(LD_CIRC,
  1563. "Got pathbias probe request for circuit %d with "
  1564. "outstanding probe", ocirc->global_identifier);
  1565. return -1;
  1566. }
  1567. circuit_change_purpose(circ, CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1568. /* Update timestamp for when circuit_expire_building() should kill us */
  1569. tor_gettimeofday(&circ->timestamp_began);
  1570. /* Generate a random address for the nonce */
  1571. crypto_rand((char*)&ocirc->pathbias_probe_nonce,
  1572. sizeof(ocirc->pathbias_probe_nonce));
  1573. ocirc->pathbias_probe_nonce &= 0x00ffffff;
  1574. probe_nonce = tor_dup_ip(ocirc->pathbias_probe_nonce);
  1575. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:25", probe_nonce);
  1576. payload_len = (int)strlen(payload)+1;
  1577. // XXX: need this? Can we assume ipv4 will always be supported?
  1578. // If not, how do we tell?
  1579. //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  1580. // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  1581. // payload_len += 4;
  1582. //}
  1583. /* Generate+Store stream id, make sure it's non-zero */
  1584. ocirc->pathbias_probe_id = get_unique_stream_id_by_circ(ocirc);
  1585. if (ocirc->pathbias_probe_id==0) {
  1586. log_warn(LD_CIRC,
  1587. "Ran out of stream IDs on circuit %u during "
  1588. "pathbias probe attempt.", ocirc->global_identifier);
  1589. tor_free(probe_nonce);
  1590. return -1;
  1591. }
  1592. log_info(LD_CIRC,
  1593. "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
  1594. probe_nonce, ocirc->pathbias_probe_id, ocirc->global_identifier);
  1595. tor_free(probe_nonce);
  1596. /* Send a test relay cell */
  1597. if (relay_send_command_from_edge(ocirc->pathbias_probe_id, circ,
  1598. RELAY_COMMAND_BEGIN, payload,
  1599. payload_len, cpath_layer) < 0) {
  1600. log_notice(LD_CIRC,
  1601. "Failed to send pathbias probe cell on circuit %d.",
  1602. ocirc->global_identifier);
  1603. return -1;
  1604. }
  1605. /* Mark it freshly dirty so it doesn't get expired in the meantime */
  1606. circ->timestamp_dirty = time(NULL);
  1607. return 0;
  1608. }
  1609. /**
  1610. * Check the response to a pathbias probe, to ensure the
  1611. * cell is recognized and the nonce and other probe
  1612. * characteristics are as expected.
  1613. *
  1614. * If the response is valid, return 0. Otherwise return < 0.
  1615. */
  1616. int
  1617. pathbias_check_probe_response(circuit_t *circ, const cell_t *cell)
  1618. {
  1619. /* Based on connection_edge_process_relay_cell() */
  1620. relay_header_t rh;
  1621. int reason;
  1622. uint32_t ipv4_host;
  1623. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1624. tor_assert(cell);
  1625. tor_assert(ocirc);
  1626. tor_assert(circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1627. relay_header_unpack(&rh, cell->payload);
  1628. reason = rh.length > 0 ?
  1629. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1630. if (rh.command == RELAY_COMMAND_END &&
  1631. reason == END_STREAM_REASON_EXITPOLICY &&
  1632. ocirc->pathbias_probe_id == rh.stream_id) {
  1633. /* Check length+extract host: It is in network order after the reason code.
  1634. * See connection_edge_end(). */
  1635. if (rh.length < 9) { /* reason+ipv4+dns_ttl */
  1636. log_notice(LD_PROTOCOL,
  1637. "Short path bias probe response length field (%d).", rh.length);
  1638. return - END_CIRC_REASON_TORPROTOCOL;
  1639. }
  1640. ipv4_host = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  1641. /* Check nonce */
  1642. if (ipv4_host == ocirc->pathbias_probe_nonce) {
  1643. pathbias_mark_use_success(ocirc);
  1644. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1645. log_info(LD_CIRC,
  1646. "Got valid path bias probe back for circ %d, stream %d.",
  1647. ocirc->global_identifier, ocirc->pathbias_probe_id);
  1648. return 0;
  1649. } else {
  1650. log_notice(LD_CIRC,
  1651. "Got strange probe value 0x%x vs 0x%x back for circ %d, "
  1652. "stream %d.", ipv4_host, ocirc->pathbias_probe_nonce,
  1653. ocirc->global_identifier, ocirc->pathbias_probe_id);
  1654. return -1;
  1655. }
  1656. }
  1657. log_info(LD_CIRC,
  1658. "Got another cell back back on pathbias probe circuit %d: "
  1659. "Command: %d, Reason: %d, Stream-id: %d",
  1660. ocirc->global_identifier, rh.command, reason, rh.stream_id);
  1661. return -1;
  1662. }
  1663. /**
  1664. * Check if a circuit was used and/or closed successfully.
  1665. *
  1666. * If we attempted to use the circuit to carry a stream but failed
  1667. * for whatever reason, or if the circuit mysteriously died before
  1668. * we could attach any streams, record these two cases.
  1669. *
  1670. * If we *have* successfully used the circuit, or it appears to
  1671. * have been closed by us locally, count it as a success.
  1672. *
  1673. * Returns 0 if we're done making decisions with the circ,
  1674. * or -1 if we want to probe it first.
  1675. */
  1676. int
  1677. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  1678. {
  1679. circuit_t *circ = &ocirc->base_;
  1680. if (!pathbias_should_count(ocirc)) {
  1681. return 0;
  1682. }
  1683. switch (ocirc->path_state) {
  1684. /* If the circuit was closed after building, but before use, we need
  1685. * to ensure we were the ones who tried to close it (and not a remote
  1686. * actor). */
  1687. case PATH_STATE_BUILD_SUCCEEDED:
  1688. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  1689. /* Remote circ close reasons on an unused circuit all could be bias */
  1690. log_info(LD_CIRC,
  1691. "Circuit %d remote-closed without successful use for reason %d. "
  1692. "Circuit purpose %d currently %d,%s. Len %d.",
  1693. ocirc->global_identifier,
  1694. reason, circ->purpose, ocirc->has_opened,
  1695. circuit_state_to_string(circ->state),
  1696. ocirc->build_state->desired_path_len);
  1697. pathbias_count_collapse(ocirc);
  1698. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  1699. == END_CIRC_REASON_CHANNEL_CLOSED &&
  1700. circ->n_chan &&
  1701. circ->n_chan->reason_for_closing
  1702. != CHANNEL_CLOSE_REQUESTED) {
  1703. /* If we didn't close the channel ourselves, it could be bias */
  1704. /* XXX: Only count bias if the network is live?
  1705. * What about clock jumps/suspends? */
  1706. log_info(LD_CIRC,
  1707. "Circuit %d's channel closed without successful use for reason "
  1708. "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
  1709. "%d.", ocirc->global_identifier,
  1710. reason, circ->n_chan->reason_for_closing,
  1711. circ->purpose, ocirc->has_opened,
  1712. circuit_state_to_string(circ->state),
  1713. ocirc->build_state->desired_path_len);
  1714. pathbias_count_collapse(ocirc);
  1715. } else {
  1716. pathbias_count_successful_close(ocirc);
  1717. }
  1718. break;
  1719. /* If we tried to use a circuit but failed, we should probe it to ensure
  1720. * it has not been tampered with. */
  1721. case PATH_STATE_USE_ATTEMPTED:
  1722. /* XXX: Only probe and/or count failure if the network is live?
  1723. * What about clock jumps/suspends? */
  1724. if (pathbias_send_usable_probe(circ) == 0)
  1725. return -1;
  1726. else
  1727. pathbias_count_use_failed(ocirc);
  1728. /* Any circuit where there were attempted streams but no successful
  1729. * streams could be bias */
  1730. log_info(LD_CIRC,
  1731. "Circuit %d closed without successful use for reason %d. "
  1732. "Circuit purpose %d currently %d,%s. Len %d.",
  1733. ocirc->global_identifier,
  1734. reason, circ->purpose, ocirc->has_opened,
  1735. circuit_state_to_string(circ->state),
  1736. ocirc->build_state->desired_path_len);
  1737. break;
  1738. case PATH_STATE_USE_SUCCEEDED:
  1739. pathbias_count_successful_close(ocirc);
  1740. pathbias_count_use_success(ocirc);
  1741. break;
  1742. default:
  1743. // Other states are uninteresting. No stats to count.
  1744. break;
  1745. }
  1746. ocirc->path_state = PATH_STATE_ALREADY_COUNTED;
  1747. return 0;
  1748. }
  1749. /**
  1750. * Count a successfully closed circuit.
  1751. */
  1752. static void
  1753. pathbias_count_successful_close(origin_circuit_t *circ)
  1754. {
  1755. entry_guard_t *guard = NULL;
  1756. if (!pathbias_should_count(circ)) {
  1757. return;
  1758. }
  1759. if (circ->cpath && circ->cpath->extend_info) {
  1760. guard = entry_guard_get_by_id_digest(
  1761. circ->cpath->extend_info->identity_digest);
  1762. }
  1763. if (guard) {
  1764. /* In the long run: circuit_success ~= successful_circuit_close +
  1765. * circ_failure + stream_failure */
  1766. guard->successful_circuits_closed++;
  1767. entry_guards_changed();
  1768. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1769. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1770. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1771. * No need to log that case. */
  1772. log_info(LD_CIRC,
  1773. "Successfully closed circuit has no known guard. "
  1774. "Circuit is a %s currently %s",
  1775. circuit_purpose_to_string(circ->base_.purpose),
  1776. circuit_state_to_string(circ->base_.state));
  1777. }
  1778. }
  1779. /**
  1780. * Count a circuit that fails after it is built, but before it can
  1781. * carry any traffic.
  1782. *
  1783. * This is needed because there are ways to destroy a
  1784. * circuit after it has successfully completed. Right now, this is
  1785. * used for purely informational/debugging purposes.
  1786. */
  1787. static void
  1788. pathbias_count_collapse(origin_circuit_t *circ)
  1789. {
  1790. entry_guard_t *guard = NULL;
  1791. if (!pathbias_should_count(circ)) {
  1792. return;
  1793. }
  1794. if (circ->cpath && circ->cpath->extend_info) {
  1795. guard = entry_guard_get_by_id_digest(
  1796. circ->cpath->extend_info->identity_digest);
  1797. }
  1798. if (guard) {
  1799. guard->collapsed_circuits++;
  1800. entry_guards_changed();
  1801. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1802. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1803. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1804. * No need to log that case. */
  1805. log_info(LD_CIRC,
  1806. "Destroyed circuit has no known guard. "
  1807. "Circuit is a %s currently %s",
  1808. circuit_purpose_to_string(circ->base_.purpose),
  1809. circuit_state_to_string(circ->base_.state));
  1810. }
  1811. }
  1812. /**
  1813. * Count a known failed circuit (because we could not probe it).
  1814. *
  1815. * This counter is informational.
  1816. */
  1817. static void
  1818. pathbias_count_use_failed(origin_circuit_t *circ)
  1819. {
  1820. entry_guard_t *guard = NULL;
  1821. if (!pathbias_should_count(circ)) {
  1822. return;
  1823. }
  1824. if (circ->cpath && circ->cpath->extend_info) {
  1825. guard = entry_guard_get_by_id_digest(
  1826. circ->cpath->extend_info->identity_digest);
  1827. }
  1828. if (guard) {
  1829. guard->unusable_circuits++;
  1830. entry_guards_changed();
  1831. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1832. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1833. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1834. * No need to log that case. */
  1835. /* XXX note cut-and-paste code in this function compared to nearby
  1836. * functions. Would be nice to refactor. -RD */
  1837. log_info(LD_CIRC,
  1838. "Stream-failing circuit has no known guard. "
  1839. "Circuit is a %s currently %s",
  1840. circuit_purpose_to_string(circ->base_.purpose),
  1841. circuit_state_to_string(circ->base_.state));
  1842. }
  1843. }
  1844. /**
  1845. * Count timeouts for path bias log messages.
  1846. *
  1847. * These counts are purely informational.
  1848. */
  1849. void
  1850. pathbias_count_timeout(origin_circuit_t *circ)
  1851. {
  1852. entry_guard_t *guard = NULL;
  1853. if (!pathbias_should_count(circ)) {
  1854. return;
  1855. }
  1856. /* For hidden service circs, they can actually be used
  1857. * successfully and then time out later (because
  1858. * the other side declines to use them). */
  1859. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1860. return;
  1861. }
  1862. if (circ->cpath && circ->cpath->extend_info) {
  1863. guard = entry_guard_get_by_id_digest(
  1864. circ->cpath->extend_info->identity_digest);
  1865. }
  1866. if (guard) {
  1867. guard->timeouts++;
  1868. entry_guards_changed();
  1869. }
  1870. }
  1871. /**
  1872. * Return the number of circuits counted as successfully closed for
  1873. * this guard.
  1874. *
  1875. * Also add in the currently open circuits to give them the benefit
  1876. * of the doubt.
  1877. */
  1878. double
  1879. pathbias_get_close_success_count(entry_guard_t *guard)
  1880. {
  1881. circuit_t *circ;
  1882. int open_circuits = 0;
  1883. /* Count currently open circuits. Give them the benefit of the doubt. */
  1884. for (circ = global_circuitlist; circ; circ = circ->next) {
  1885. origin_circuit_t *ocirc = NULL;
  1886. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1887. circ->marked_for_close) /* already counted */
  1888. continue;
  1889. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1890. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1891. continue;
  1892. /* Don't count known failed or already counted circuits */
  1893. if (ocirc->path_state >= PATH_STATE_USE_FAILED)
  1894. continue;
  1895. if (ocirc->path_state >= PATH_STATE_BUILD_SUCCEEDED &&
  1896. pathbias_should_count(ocirc) &&
  1897. fast_memeq(guard->identity,
  1898. ocirc->cpath->extend_info->identity_digest,
  1899. DIGEST_LEN)) {
  1900. open_circuits++;
  1901. }
  1902. }
  1903. return guard->successful_circuits_closed + open_circuits;
  1904. }
  1905. /**
  1906. * Return the number of circuits counted as successfully used
  1907. * this guard.
  1908. *
  1909. * Also add in the currently open circuits that we are attempting
  1910. * to use to give them the benefit of the doubt.
  1911. */
  1912. double
  1913. pathbias_get_use_success_count(entry_guard_t *guard)
  1914. {
  1915. circuit_t *circ = global_circuitlist;
  1916. int open_circuits = 0;
  1917. /* Count currently open circuits. Give them the benefit of the doubt */
  1918. for ( ; circ; circ = circ->next) {
  1919. origin_circuit_t *ocirc = NULL;
  1920. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1921. circ->marked_for_close) /* already counted */
  1922. continue;
  1923. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1924. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1925. continue;
  1926. /* Don't count known failed or already counted circuits */
  1927. if (ocirc->path_state >= PATH_STATE_USE_FAILED)
  1928. continue;
  1929. if (ocirc->path_state >= PATH_STATE_USE_ATTEMPTED &&
  1930. pathbias_should_count(ocirc) &&
  1931. fast_memeq(guard->identity,
  1932. ocirc->cpath->extend_info->identity_digest,
  1933. DIGEST_LEN)) {
  1934. open_circuits++;
  1935. }
  1936. }
  1937. return guard->use_successes + open_circuits;
  1938. }
  1939. /**
  1940. * Check the path bias use rate against our consensus parameter limits.
  1941. *
  1942. * Emits a log message if the use success rates are too low.
  1943. *
  1944. * If pathbias_get_dropguards() is set, we also disable the use of
  1945. * very failure prone guards.
  1946. *
  1947. * Returns -1 if we decided to disable the guard, 0 otherwise.
  1948. */
  1949. static int
  1950. pathbias_check_use_rate(entry_guard_t *guard)
  1951. {
  1952. const or_options_t *options = get_options();
  1953. if (guard->use_attempts > pathbias_get_min_use(options)) {
  1954. /* Note: We rely on the < comparison here to allow us to set a 0
  1955. * rate and disable the feature entirely. If refactoring, don't
  1956. * change to <= */
  1957. if (pathbias_get_use_success_count(guard)/guard->use_attempts
  1958. < pathbias_get_extreme_use_rate(options)) {
  1959. /* Dropping is currently disabled by default. */
  1960. if (pathbias_get_dropguards(options)) {
  1961. if (!guard->path_bias_disabled) {
  1962. log_warn(LD_CIRC,
  1963. "Your Guard %s=%s is failing to carry an extremely large "
  1964. "amount of stream on its circuits. "
  1965. "To avoid potential route manipluation attacks, Tor has "
  1966. "disabled use of this guard. "
  1967. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1968. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1969. "and %ld timed out. "
  1970. "For reference, your timeout cutoff is %ld seconds.",
  1971. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1972. tor_lround(pathbias_get_use_success_count(guard)),
  1973. tor_lround(guard->use_attempts),
  1974. tor_lround(pathbias_get_close_success_count(guard)),
  1975. tor_lround(guard->circ_attempts),
  1976. tor_lround(guard->circ_successes),
  1977. tor_lround(guard->unusable_circuits),
  1978. tor_lround(guard->collapsed_circuits),
  1979. tor_lround(guard->timeouts),
  1980. tor_lround(circ_times.close_ms/1000));
  1981. guard->path_bias_disabled = 1;
  1982. guard->bad_since = approx_time();
  1983. return -1;
  1984. }
  1985. } else if (!guard->path_bias_extreme) {
  1986. guard->path_bias_extreme = 1;
  1987. log_warn(LD_CIRC,
  1988. "Your Guard %s=%s is failing to carry an extremely large "
  1989. "amount of streams on its circuits. "
  1990. "This could indicate a route manipulation attack, network "
  1991. "overload, bad local network connectivity, or a bug. "
  1992. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1993. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1994. "and %ld timed out. "
  1995. "For reference, your timeout cutoff is %ld seconds.",
  1996. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1997. tor_lround(pathbias_get_use_success_count(guard)),
  1998. tor_lround(guard->use_attempts),
  1999. tor_lround(pathbias_get_close_success_count(guard)),
  2000. tor_lround(guard->circ_attempts),
  2001. tor_lround(guard->circ_successes),
  2002. tor_lround(guard->unusable_circuits),
  2003. tor_lround(guard->collapsed_circuits),
  2004. tor_lround(guard->timeouts),
  2005. tor_lround(circ_times.close_ms/1000));
  2006. }
  2007. } else if (pathbias_get_use_success_count(guard)/guard->use_attempts
  2008. < pathbias_get_notice_use_rate(options)) {
  2009. if (!guard->path_bias_noticed) {
  2010. guard->path_bias_noticed = 1;
  2011. log_notice(LD_CIRC,
  2012. "Your Guard %s=%s is failing to carry more streams on its "
  2013. "circuits than usual. "
  2014. "Most likely this means the Tor network is overloaded "
  2015. "or your network connection is poor. "
  2016. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  2017. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2018. "and %ld timed out. "
  2019. "For reference, your timeout cutoff is %ld seconds.",
  2020. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2021. tor_lround(pathbias_get_use_success_count(guard)),
  2022. tor_lround(guard->use_attempts),
  2023. tor_lround(pathbias_get_close_success_count(guard)),
  2024. tor_lround(guard->circ_attempts),
  2025. tor_lround(guard->circ_successes),
  2026. tor_lround(guard->unusable_circuits),
  2027. tor_lround(guard->collapsed_circuits),
  2028. tor_lround(guard->timeouts),
  2029. tor_lround(circ_times.close_ms/1000));
  2030. }
  2031. }
  2032. }
  2033. /* If we get a ton of circuits, just scale everything down */
  2034. if (guard->use_attempts > pathbias_get_scale_use_threshold(options)) {
  2035. const int scale_factor = pathbias_get_scale_factor(options);
  2036. const int mult_factor = pathbias_get_mult_factor(options);
  2037. log_info(LD_CIRC,
  2038. "Scaling pathbias use counts to (%f/%f)*(%d/%d) for guard %s=%s",
  2039. guard->use_successes, guard->use_attempts,
  2040. mult_factor, scale_factor, guard->nickname,
  2041. hex_str(guard->identity, DIGEST_LEN));
  2042. guard->use_attempts *= mult_factor;
  2043. guard->use_successes *= mult_factor;
  2044. guard->use_attempts /= scale_factor;
  2045. guard->use_successes /= scale_factor;
  2046. }
  2047. return 0;
  2048. }
  2049. /**
  2050. * Check the path bias circuit close status rates against our consensus
  2051. * parameter limits.
  2052. *
  2053. * Emits a log message if the use success rates are too low.
  2054. *
  2055. * If pathbias_get_dropguards() is set, we also disable the use of
  2056. * very failure prone guards.
  2057. *
  2058. * Returns -1 if we decided to disable the guard, 0 otherwise.
  2059. */
  2060. static int
  2061. pathbias_check_close_rate(entry_guard_t *guard)
  2062. {
  2063. const or_options_t *options = get_options();
  2064. if (guard->circ_attempts > pathbias_get_min_circs(options)) {
  2065. /* Note: We rely on the < comparison here to allow us to set a 0
  2066. * rate and disable the feature entirely. If refactoring, don't
  2067. * change to <= */
  2068. if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2069. < pathbias_get_extreme_rate(options)) {
  2070. /* Dropping is currently disabled by default. */
  2071. if (pathbias_get_dropguards(options)) {
  2072. if (!guard->path_bias_disabled) {
  2073. log_warn(LD_CIRC,
  2074. "Your Guard %s=%s is failing an extremely large "
  2075. "amount of circuits. "
  2076. "To avoid potential route manipluation attacks, Tor has "
  2077. "disabled use of this guard. "
  2078. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2079. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2080. "and %ld timed out. "
  2081. "For reference, your timeout cutoff is %ld seconds.",
  2082. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2083. tor_lround(pathbias_get_close_success_count(guard)),
  2084. tor_lround(guard->circ_attempts),
  2085. tor_lround(pathbias_get_use_success_count(guard)),
  2086. tor_lround(guard->use_attempts),
  2087. tor_lround(guard->circ_successes),
  2088. tor_lround(guard->unusable_circuits),
  2089. tor_lround(guard->collapsed_circuits),
  2090. tor_lround(guard->timeouts),
  2091. tor_lround(circ_times.close_ms/1000));
  2092. guard->path_bias_disabled = 1;
  2093. guard->bad_since = approx_time();
  2094. return -1;
  2095. }
  2096. } else if (!guard->path_bias_extreme) {
  2097. guard->path_bias_extreme = 1;
  2098. log_warn(LD_CIRC,
  2099. "Your Guard %s=%s is failing an extremely large "
  2100. "amount of circuits. "
  2101. "This could indicate a route manipulation attack, "
  2102. "extreme network overload, or a bug. "
  2103. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2104. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2105. "and %ld timed out. "
  2106. "For reference, your timeout cutoff is %ld seconds.",
  2107. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2108. tor_lround(pathbias_get_close_success_count(guard)),
  2109. tor_lround(guard->circ_attempts),
  2110. tor_lround(pathbias_get_use_success_count(guard)),
  2111. tor_lround(guard->use_attempts),
  2112. tor_lround(guard->circ_successes),
  2113. tor_lround(guard->unusable_circuits),
  2114. tor_lround(guard->collapsed_circuits),
  2115. tor_lround(guard->timeouts),
  2116. tor_lround(circ_times.close_ms/1000));
  2117. }
  2118. } else if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2119. < pathbias_get_warn_rate(options)) {
  2120. if (!guard->path_bias_warned) {
  2121. guard->path_bias_warned = 1;
  2122. log_warn(LD_CIRC,
  2123. "Your Guard %s=%s is failing a very large "
  2124. "amount of circuits. "
  2125. "Most likely this means the Tor network is "
  2126. "overloaded, but it could also mean an attack against "
  2127. "you or the potentially the guard itself. "
  2128. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2129. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2130. "and %ld timed out. "
  2131. "For reference, your timeout cutoff is %ld seconds.",
  2132. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2133. tor_lround(pathbias_get_close_success_count(guard)),
  2134. tor_lround(guard->circ_attempts),
  2135. tor_lround(pathbias_get_use_success_count(guard)),
  2136. tor_lround(guard->use_attempts),
  2137. tor_lround(guard->circ_successes),
  2138. tor_lround(guard->unusable_circuits),
  2139. tor_lround(guard->collapsed_circuits),
  2140. tor_lround(guard->timeouts),
  2141. tor_lround(circ_times.close_ms/1000));
  2142. }
  2143. } else if (pathbias_get_close_success_count(guard)/guard->circ_attempts
  2144. < pathbias_get_notice_rate(options)) {
  2145. if (!guard->path_bias_noticed) {
  2146. guard->path_bias_noticed = 1;
  2147. log_notice(LD_CIRC,
  2148. "Your Guard %s=%s is failing more circuits than "
  2149. "usual. "
  2150. "Most likely this means the Tor network is overloaded. "
  2151. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  2152. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  2153. "and %ld timed out. "
  2154. "For reference, your timeout cutoff is %ld seconds.",
  2155. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  2156. tor_lround(pathbias_get_close_success_count(guard)),
  2157. tor_lround(guard->circ_attempts),
  2158. tor_lround(pathbias_get_use_success_count(guard)),
  2159. tor_lround(guard->use_attempts),
  2160. tor_lround(guard->circ_successes),
  2161. tor_lround(guard->unusable_circuits),
  2162. tor_lround(guard->collapsed_circuits),
  2163. tor_lround(guard->timeouts),
  2164. tor_lround(circ_times.close_ms/1000));
  2165. }
  2166. }
  2167. }
  2168. /* If we get a ton of circuits, just scale everything down */
  2169. if (guard->circ_attempts > pathbias_get_scale_threshold(options)) {
  2170. const int scale_factor = pathbias_get_scale_factor(options);
  2171. const int mult_factor = pathbias_get_mult_factor(options);
  2172. log_info(LD_CIRC,
  2173. "Scaling pathbias counts to (%f/%f)*(%d/%d) for guard %s=%s",
  2174. guard->circ_successes, guard->circ_attempts,
  2175. mult_factor, scale_factor, guard->nickname,
  2176. hex_str(guard->identity, DIGEST_LEN));
  2177. guard->circ_attempts *= mult_factor;
  2178. guard->circ_successes *= mult_factor;
  2179. guard->timeouts *= mult_factor;
  2180. guard->successful_circuits_closed *= mult_factor;
  2181. guard->collapsed_circuits *= mult_factor;
  2182. guard->unusable_circuits *= mult_factor;
  2183. guard->circ_attempts /= scale_factor;
  2184. guard->circ_successes /= scale_factor;
  2185. guard->timeouts /= scale_factor;
  2186. guard->successful_circuits_closed /= scale_factor;
  2187. guard->collapsed_circuits /= scale_factor;
  2188. guard->unusable_circuits /= scale_factor;
  2189. }
  2190. return 0;
  2191. }
  2192. /** Increment the number of times we successfully extended a circuit to
  2193. * 'guard', first checking if the failure rate is high enough that we should
  2194. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  2195. * guard looks fine. */
  2196. static int
  2197. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  2198. {
  2199. entry_guards_changed();
  2200. if (pathbias_check_close_rate(guard) < 0)
  2201. return -1;
  2202. guard->circ_attempts++;
  2203. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  2204. guard->circ_successes, guard->circ_attempts, guard->nickname,
  2205. hex_str(guard->identity, DIGEST_LEN));
  2206. return 0;
  2207. }
  2208. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  2209. * (The body of <b>reply</b> varies depending on what sort of handshake
  2210. * this is.)
  2211. *
  2212. * Calculate the appropriate keys and digests, make sure KH is
  2213. * correct, and initialize this hop of the cpath.
  2214. *
  2215. * Return - reason if we want to mark circ for close, else return 0.
  2216. */
  2217. int
  2218. circuit_finish_handshake(origin_circuit_t *circ,
  2219. const created_cell_t *reply)
  2220. {
  2221. char keys[CPATH_KEY_MATERIAL_LEN];
  2222. crypt_path_t *hop;
  2223. int rv;
  2224. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  2225. return rv;
  2226. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  2227. hop = circ->cpath;
  2228. } else {
  2229. hop = onion_next_hop_in_cpath(circ->cpath);
  2230. if (!hop) { /* got an extended when we're all done? */
  2231. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  2232. return - END_CIRC_REASON_TORPROTOCOL;
  2233. }
  2234. }
  2235. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  2236. {
  2237. if (onion_skin_client_handshake(hop->handshake_state.tag,
  2238. &hop->handshake_state,
  2239. reply->reply, reply->handshake_len,
  2240. (uint8_t*)keys, sizeof(keys),
  2241. (uint8_t*)hop->rend_circ_nonce) < 0) {
  2242. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  2243. return -END_CIRC_REASON_TORPROTOCOL;
  2244. }
  2245. }
  2246. onion_handshake_state_release(&hop->handshake_state);
  2247. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  2248. return -END_CIRC_REASON_TORPROTOCOL;
  2249. }
  2250. hop->state = CPATH_STATE_OPEN;
  2251. log_info(LD_CIRC,"Finished building circuit hop:");
  2252. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  2253. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  2254. return 0;
  2255. }
  2256. /** We received a relay truncated cell on circ.
  2257. *
  2258. * Since we don't send truncates currently, getting a truncated
  2259. * means that a connection broke or an extend failed. For now,
  2260. * just give up: force circ to close, and return 0.
  2261. */
  2262. int
  2263. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  2264. {
  2265. // crypt_path_t *victim;
  2266. // connection_t *stream;
  2267. tor_assert(circ);
  2268. tor_assert(layer);
  2269. /* XXX Since we don't send truncates currently, getting a truncated
  2270. * means that a connection broke or an extend failed. For now,
  2271. * just give up.
  2272. */
  2273. circuit_mark_for_close(TO_CIRCUIT(circ),
  2274. END_CIRC_REASON_FLAG_REMOTE|reason);
  2275. return 0;
  2276. #if 0
  2277. while (layer->next != circ->cpath) {
  2278. /* we need to clear out layer->next */
  2279. victim = layer->next;
  2280. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  2281. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  2282. if (stream->cpath_layer == victim) {
  2283. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  2284. stream->stream_id);
  2285. /* no need to send 'end' relay cells,
  2286. * because the other side's already dead
  2287. */
  2288. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  2289. }
  2290. }
  2291. layer->next = victim->next;
  2292. circuit_free_cpath_node(victim);
  2293. }
  2294. log_info(LD_CIRC, "finished");
  2295. return 0;
  2296. #endif
  2297. }
  2298. /** Given a response payload and keys, initialize, then send a created
  2299. * cell back.
  2300. */
  2301. int
  2302. onionskin_answer(or_circuit_t *circ,
  2303. const created_cell_t *created_cell,
  2304. const char *keys,
  2305. const uint8_t *rend_circ_nonce)
  2306. {
  2307. cell_t cell;
  2308. crypt_path_t *tmp_cpath;
  2309. if (created_cell_format(&cell, created_cell) < 0) {
  2310. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  2311. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  2312. return -1;
  2313. }
  2314. cell.circ_id = circ->p_circ_id;
  2315. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  2316. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  2317. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2318. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  2319. (unsigned int)get_uint32(keys),
  2320. (unsigned int)get_uint32(keys+20));
  2321. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  2322. log_warn(LD_BUG,"Circuit initialization failed");
  2323. tor_free(tmp_cpath);
  2324. return -1;
  2325. }
  2326. circ->n_digest = tmp_cpath->f_digest;
  2327. circ->n_crypto = tmp_cpath->f_crypto;
  2328. circ->p_digest = tmp_cpath->b_digest;
  2329. circ->p_crypto = tmp_cpath->b_crypto;
  2330. tmp_cpath->magic = 0;
  2331. tor_free(tmp_cpath);
  2332. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  2333. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  2334. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  2335. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  2336. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  2337. circ->is_first_hop ? "created_fast" : "created");
  2338. if (!channel_is_local(circ->p_chan) &&
  2339. !channel_is_outgoing(circ->p_chan)) {
  2340. /* record that we could process create cells from a non-local conn
  2341. * that we didn't initiate; presumably this means that create cells
  2342. * can reach us too. */
  2343. router_orport_found_reachable();
  2344. }
  2345. return 0;
  2346. }
  2347. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  2348. * number of endpoints that would give something away about our destination.
  2349. *
  2350. * If the routerlist <b>nodes</b> doesn't have enough routers
  2351. * to handle the desired path length, return as large a path length as
  2352. * is feasible, except if it's less than 2, in which case return -1.
  2353. * XXX ^^ I think this behavior is a hold-over from back when we had only a
  2354. * few relays in the network, and certainly back before guards existed.
  2355. * We should very likely get rid of it. -RD
  2356. */
  2357. static int
  2358. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  2359. {
  2360. int num_acceptable_routers;
  2361. int routelen;
  2362. tor_assert(nodes);
  2363. routelen = DEFAULT_ROUTE_LEN;
  2364. if (exit &&
  2365. purpose != CIRCUIT_PURPOSE_TESTING &&
  2366. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2367. routelen++;
  2368. num_acceptable_routers = count_acceptable_nodes(nodes);
  2369. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2370. routelen, num_acceptable_routers, smartlist_len(nodes));
  2371. if (num_acceptable_routers < 2) {
  2372. log_info(LD_CIRC,
  2373. "Not enough acceptable routers (%d). Discarding this circuit.",
  2374. num_acceptable_routers);
  2375. return -1;
  2376. }
  2377. if (num_acceptable_routers < routelen) {
  2378. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2379. routelen, num_acceptable_routers);
  2380. routelen = num_acceptable_routers;
  2381. }
  2382. return routelen;
  2383. }
  2384. /** Return a newly allocated list of uint16_t * for each predicted port not
  2385. * handled by a current circuit. */
  2386. static smartlist_t *
  2387. circuit_get_unhandled_ports(time_t now)
  2388. {
  2389. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  2390. circuit_remove_handled_ports(dest);
  2391. return dest;
  2392. }
  2393. /** Return 1 if we already have circuits present or on the way for
  2394. * all anticipated ports. Return 0 if we should make more.
  2395. *
  2396. * If we're returning 0, set need_uptime and need_capacity to
  2397. * indicate any requirements that the unhandled ports have.
  2398. */
  2399. int
  2400. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2401. int *need_capacity)
  2402. {
  2403. int i, enough;
  2404. uint16_t *port;
  2405. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2406. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2407. tor_assert(need_uptime);
  2408. tor_assert(need_capacity);
  2409. // Always predict need_capacity
  2410. *need_capacity = 1;
  2411. enough = (smartlist_len(sl) == 0);
  2412. for (i = 0; i < smartlist_len(sl); ++i) {
  2413. port = smartlist_get(sl, i);
  2414. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  2415. *need_uptime = 1;
  2416. tor_free(port);
  2417. }
  2418. smartlist_free(sl);
  2419. return enough;
  2420. }
  2421. /** Return 1 if <b>node</b> can handle one or more of the ports in
  2422. * <b>needed_ports</b>, else return 0.
  2423. */
  2424. static int
  2425. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  2426. { /* XXXX MOVE */
  2427. int i;
  2428. uint16_t port;
  2429. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2430. addr_policy_result_t r;
  2431. /* alignment issues aren't a worry for this dereference, since
  2432. needed_ports is explicitly a smartlist of uint16_t's */
  2433. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2434. tor_assert(port);
  2435. if (node)
  2436. r = compare_tor_addr_to_node_policy(NULL, port, node);
  2437. else
  2438. continue;
  2439. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2440. return 1;
  2441. }
  2442. return 0;
  2443. }
  2444. /** Return true iff <b>conn</b> needs another general circuit to be
  2445. * built. */
  2446. static int
  2447. ap_stream_wants_exit_attention(connection_t *conn)
  2448. {
  2449. entry_connection_t *entry;
  2450. if (conn->type != CONN_TYPE_AP)
  2451. return 0;
  2452. entry = TO_ENTRY_CONN(conn);
  2453. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2454. !conn->marked_for_close &&
  2455. !(entry->want_onehop) && /* ignore one-hop streams */
  2456. !(entry->use_begindir) && /* ignore targeted dir fetches */
  2457. !(entry->chosen_exit_name) && /* ignore defined streams */
  2458. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2459. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  2460. MIN_CIRCUITS_HANDLING_STREAM))
  2461. return 1;
  2462. return 0;
  2463. }
  2464. /** Return a pointer to a suitable router to be the exit node for the
  2465. * general-purpose circuit we're about to build.
  2466. *
  2467. * Look through the connection array, and choose a router that maximizes
  2468. * the number of pending streams that can exit from this router.
  2469. *
  2470. * Return NULL if we can't find any suitable routers.
  2471. */
  2472. static const node_t *
  2473. choose_good_exit_server_general(int need_uptime, int need_capacity)
  2474. {
  2475. int *n_supported;
  2476. int n_pending_connections = 0;
  2477. smartlist_t *connections;
  2478. int best_support = -1;
  2479. int n_best_support=0;
  2480. const or_options_t *options = get_options();
  2481. const smartlist_t *the_nodes;
  2482. const node_t *node=NULL;
  2483. connections = get_connection_array();
  2484. /* Count how many connections are waiting for a circuit to be built.
  2485. * We use this for log messages now, but in the future we may depend on it.
  2486. */
  2487. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2488. {
  2489. if (ap_stream_wants_exit_attention(conn))
  2490. ++n_pending_connections;
  2491. });
  2492. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2493. // n_pending_connections);
  2494. /* Now we count, for each of the routers in the directory, how many
  2495. * of the pending connections could possibly exit from that
  2496. * router (n_supported[i]). (We can't be sure about cases where we
  2497. * don't know the IP address of the pending connection.)
  2498. *
  2499. * -1 means "Don't use this router at all."
  2500. */
  2501. the_nodes = nodelist_get_list();
  2502. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  2503. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2504. const int i = node_sl_idx;
  2505. if (router_digest_is_me(node->identity)) {
  2506. n_supported[i] = -1;
  2507. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2508. /* XXX there's probably a reverse predecessor attack here, but
  2509. * it's slow. should we take this out? -RD
  2510. */
  2511. continue;
  2512. }
  2513. if (!node_has_descriptor(node)) {
  2514. n_supported[i] = -1;
  2515. continue;
  2516. }
  2517. if (!node->is_running || node->is_bad_exit) {
  2518. n_supported[i] = -1;
  2519. continue; /* skip routers that are known to be down or bad exits */
  2520. }
  2521. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2522. /* never pick a non-general node as a random exit. */
  2523. n_supported[i] = -1;
  2524. continue;
  2525. }
  2526. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  2527. n_supported[i] = -1;
  2528. continue; /* user asked us not to use it, no matter what */
  2529. }
  2530. if (options->ExitNodes &&
  2531. !routerset_contains_node(options->ExitNodes, node)) {
  2532. n_supported[i] = -1;
  2533. continue; /* not one of our chosen exit nodes */
  2534. }
  2535. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2536. n_supported[i] = -1;
  2537. continue; /* skip routers that are not suitable. Don't worry if
  2538. * this makes us reject all the possible routers: if so,
  2539. * we'll retry later in this function with need_update and
  2540. * need_capacity set to 0. */
  2541. }
  2542. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  2543. /* if it's invalid and we don't want it */
  2544. n_supported[i] = -1;
  2545. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2546. // router->nickname, i);
  2547. continue; /* skip invalid routers */
  2548. }
  2549. if (options->ExcludeSingleHopRelays &&
  2550. node_allows_single_hop_exits(node)) {
  2551. n_supported[i] = -1;
  2552. continue;
  2553. }
  2554. if (node_exit_policy_rejects_all(node)) {
  2555. n_supported[i] = -1;
  2556. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2557. // router->nickname, i);
  2558. continue; /* skip routers that reject all */
  2559. }
  2560. n_supported[i] = 0;
  2561. /* iterate over connections */
  2562. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  2563. if (!ap_stream_wants_exit_attention(conn))
  2564. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2565. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  2566. ++n_supported[i];
  2567. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2568. // router->nickname, i, n_supported[i]);
  2569. } else {
  2570. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2571. // router->nickname, i);
  2572. }
  2573. } SMARTLIST_FOREACH_END(conn);
  2574. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2575. /* Leave best_support at -1 if that's where it is, so we can
  2576. * distinguish it later. */
  2577. continue;
  2578. }
  2579. if (n_supported[i] > best_support) {
  2580. /* If this router is better than previous ones, remember its index
  2581. * and goodness, and start counting how many routers are this good. */
  2582. best_support = n_supported[i]; n_best_support=1;
  2583. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2584. // router->nickname);
  2585. } else if (n_supported[i] == best_support) {
  2586. /* If this router is _as good_ as the best one, just increment the
  2587. * count of equally good routers.*/
  2588. ++n_best_support;
  2589. }
  2590. } SMARTLIST_FOREACH_END(node);
  2591. log_info(LD_CIRC,
  2592. "Found %d servers that might support %d/%d pending connections.",
  2593. n_best_support, best_support >= 0 ? best_support : 0,
  2594. n_pending_connections);
  2595. /* If any routers definitely support any pending connections, choose one
  2596. * at random. */
  2597. if (best_support > 0) {
  2598. smartlist_t *supporting = smartlist_new();
  2599. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2600. if (n_supported[node_sl_idx] == best_support)
  2601. smartlist_add(supporting, (void*)node);
  2602. });
  2603. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2604. smartlist_free(supporting);
  2605. } else {
  2606. /* Either there are no pending connections, or no routers even seem to
  2607. * possibly support any of them. Choose a router at random that satisfies
  2608. * at least one predicted exit port. */
  2609. int attempt;
  2610. smartlist_t *needed_ports, *supporting;
  2611. if (best_support == -1) {
  2612. if (need_uptime || need_capacity) {
  2613. log_info(LD_CIRC,
  2614. "We couldn't find any live%s%s routers; falling back "
  2615. "to list of all routers.",
  2616. need_capacity?", fast":"",
  2617. need_uptime?", stable":"");
  2618. tor_free(n_supported);
  2619. return choose_good_exit_server_general(0, 0);
  2620. }
  2621. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2622. "choosing a doomed exit at random.",
  2623. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  2624. }
  2625. supporting = smartlist_new();
  2626. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2627. for (attempt = 0; attempt < 2; attempt++) {
  2628. /* try once to pick only from routers that satisfy a needed port,
  2629. * then if there are none, pick from any that support exiting. */
  2630. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2631. if (n_supported[node_sl_idx] != -1 &&
  2632. (attempt || node_handles_some_port(node, needed_ports))) {
  2633. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2634. // try, router->nickname);
  2635. smartlist_add(supporting, (void*)node);
  2636. }
  2637. } SMARTLIST_FOREACH_END(node);
  2638. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2639. if (node)
  2640. break;
  2641. smartlist_clear(supporting);
  2642. /* If we reach this point, we can't actually support any unhandled
  2643. * predicted ports, so clear all the remaining ones. */
  2644. if (smartlist_len(needed_ports))
  2645. rep_hist_remove_predicted_ports(needed_ports);
  2646. }
  2647. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2648. smartlist_free(needed_ports);
  2649. smartlist_free(supporting);
  2650. }
  2651. tor_free(n_supported);
  2652. if (node) {
  2653. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2654. return node;
  2655. }
  2656. if (options->ExitNodes) {
  2657. log_warn(LD_CIRC,
  2658. "No specified %sexit routers seem to be running: "
  2659. "can't choose an exit.",
  2660. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  2661. }
  2662. return NULL;
  2663. }
  2664. /** Return a pointer to a suitable router to be the exit node for the
  2665. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2666. * if no router is suitable).
  2667. *
  2668. * For general-purpose circuits, pass it off to
  2669. * choose_good_exit_server_general()
  2670. *
  2671. * For client-side rendezvous circuits, choose a random node, weighted
  2672. * toward the preferences in 'options'.
  2673. */
  2674. static const node_t *
  2675. choose_good_exit_server(uint8_t purpose,
  2676. int need_uptime, int need_capacity, int is_internal)
  2677. {
  2678. const or_options_t *options = get_options();
  2679. router_crn_flags_t flags = CRN_NEED_DESC;
  2680. if (need_uptime)
  2681. flags |= CRN_NEED_UPTIME;
  2682. if (need_capacity)
  2683. flags |= CRN_NEED_CAPACITY;
  2684. switch (purpose) {
  2685. case CIRCUIT_PURPOSE_C_GENERAL:
  2686. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2687. flags |= CRN_ALLOW_INVALID;
  2688. if (is_internal) /* pick it like a middle hop */
  2689. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2690. else
  2691. return choose_good_exit_server_general(need_uptime,need_capacity);
  2692. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2693. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  2694. flags |= CRN_ALLOW_INVALID;
  2695. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2696. }
  2697. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2698. tor_fragile_assert();
  2699. return NULL;
  2700. }
  2701. /** Log a warning if the user specified an exit for the circuit that
  2702. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2703. static void
  2704. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2705. {
  2706. const or_options_t *options = get_options();
  2707. routerset_t *rs = options->ExcludeNodes;
  2708. const char *description;
  2709. uint8_t purpose = circ->base_.purpose;
  2710. if (circ->build_state->onehop_tunnel)
  2711. return;
  2712. switch (purpose)
  2713. {
  2714. default:
  2715. case CIRCUIT_PURPOSE_OR:
  2716. case CIRCUIT_PURPOSE_INTRO_POINT:
  2717. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2718. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2719. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2720. (int)purpose,
  2721. circuit_purpose_to_string(purpose));
  2722. return;
  2723. case CIRCUIT_PURPOSE_C_GENERAL:
  2724. if (circ->build_state->is_internal)
  2725. return;
  2726. description = "requested exit node";
  2727. rs = options->ExcludeExitNodesUnion_;
  2728. break;
  2729. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2730. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2731. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2732. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2733. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2734. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2735. case CIRCUIT_PURPOSE_TESTING:
  2736. return;
  2737. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2738. case CIRCUIT_PURPOSE_C_REND_READY:
  2739. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2740. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2741. description = "chosen rendezvous point";
  2742. break;
  2743. case CIRCUIT_PURPOSE_CONTROLLER:
  2744. rs = options->ExcludeExitNodesUnion_;
  2745. description = "controller-selected circuit target";
  2746. break;
  2747. }
  2748. if (routerset_contains_extendinfo(rs, exit)) {
  2749. /* We should never get here if StrictNodes is set to 1. */
  2750. if (options->StrictNodes) {
  2751. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2752. "even though StrictNodes is set. Please report. "
  2753. "(Circuit purpose: %s)",
  2754. description, extend_info_describe(exit),
  2755. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2756. circuit_purpose_to_string(purpose));
  2757. } else {
  2758. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2759. "ExcludeNodes%s, because no better options were available. To "
  2760. "prevent this (and possibly break your Tor functionality), "
  2761. "set the StrictNodes configuration option. "
  2762. "(Circuit purpose: %s)",
  2763. description, extend_info_describe(exit),
  2764. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2765. circuit_purpose_to_string(purpose));
  2766. }
  2767. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2768. }
  2769. return;
  2770. }
  2771. /** Decide a suitable length for circ's cpath, and pick an exit
  2772. * router (or use <b>exit</b> if provided). Store these in the
  2773. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2774. static int
  2775. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2776. {
  2777. cpath_build_state_t *state = circ->build_state;
  2778. if (state->onehop_tunnel) {
  2779. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2780. state->desired_path_len = 1;
  2781. } else {
  2782. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  2783. if (r < 1) /* must be at least 1 */
  2784. return -1;
  2785. state->desired_path_len = r;
  2786. }
  2787. if (exit) { /* the circuit-builder pre-requested one */
  2788. warn_if_last_router_excluded(circ, exit);
  2789. log_info(LD_CIRC,"Using requested exit node '%s'",
  2790. extend_info_describe(exit));
  2791. exit = extend_info_dup(exit);
  2792. } else { /* we have to decide one */
  2793. const node_t *node =
  2794. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  2795. state->need_capacity, state->is_internal);
  2796. if (!node) {
  2797. log_warn(LD_CIRC,"failed to choose an exit server");
  2798. return -1;
  2799. }
  2800. exit = extend_info_from_node(node, 0);
  2801. tor_assert(exit);
  2802. }
  2803. state->chosen_exit = exit;
  2804. return 0;
  2805. }
  2806. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2807. * hop to the cpath reflecting this. Don't send the next extend cell --
  2808. * the caller will do this if it wants to.
  2809. */
  2810. int
  2811. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2812. {
  2813. cpath_build_state_t *state;
  2814. tor_assert(exit);
  2815. tor_assert(circ);
  2816. state = circ->build_state;
  2817. tor_assert(state);
  2818. extend_info_free(state->chosen_exit);
  2819. state->chosen_exit = extend_info_dup(exit);
  2820. ++circ->build_state->desired_path_len;
  2821. onion_append_hop(&circ->cpath, exit);
  2822. return 0;
  2823. }
  2824. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2825. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2826. * send the next extend cell to begin connecting to that hop.
  2827. */
  2828. int
  2829. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2830. {
  2831. int err_reason = 0;
  2832. warn_if_last_router_excluded(circ, exit);
  2833. tor_gettimeofday(&circ->base_.timestamp_began);
  2834. circuit_append_new_exit(circ, exit);
  2835. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2836. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2837. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2838. extend_info_describe(exit));
  2839. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2840. return -1;
  2841. }
  2842. /* Set timestamp_dirty, so we can check it for path use bias */
  2843. if (!circ->base_.timestamp_dirty)
  2844. circ->base_.timestamp_dirty = time(NULL);
  2845. return 0;
  2846. }
  2847. /** Return the number of routers in <b>routers</b> that are currently up
  2848. * and available for building circuits through.
  2849. */
  2850. static int
  2851. count_acceptable_nodes(smartlist_t *nodes)
  2852. {
  2853. int num=0;
  2854. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2855. // log_debug(LD_CIRC,
  2856. // "Contemplating whether router %d (%s) is a new option.",
  2857. // i, r->nickname);
  2858. if (! node->is_running)
  2859. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2860. continue;
  2861. if (! node->is_valid)
  2862. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2863. continue;
  2864. if (! node_has_descriptor(node))
  2865. continue;
  2866. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2867. * allows this node in some places, then we're getting an inaccurate
  2868. * count. For now, be conservative and don't count it. But later we
  2869. * should try to be smarter. */
  2870. ++num;
  2871. } SMARTLIST_FOREACH_END(node);
  2872. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2873. return num;
  2874. }
  2875. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2876. * This function is used to extend cpath by another hop.
  2877. */
  2878. void
  2879. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2880. {
  2881. if (*head_ptr) {
  2882. new_hop->next = (*head_ptr);
  2883. new_hop->prev = (*head_ptr)->prev;
  2884. (*head_ptr)->prev->next = new_hop;
  2885. (*head_ptr)->prev = new_hop;
  2886. } else {
  2887. *head_ptr = new_hop;
  2888. new_hop->prev = new_hop->next = new_hop;
  2889. }
  2890. }
  2891. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2892. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2893. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2894. * circuit. In particular, make sure we don't pick the exit node or its
  2895. * family, and make sure we don't duplicate any previous nodes or their
  2896. * families. */
  2897. static const node_t *
  2898. choose_good_middle_server(uint8_t purpose,
  2899. cpath_build_state_t *state,
  2900. crypt_path_t *head,
  2901. int cur_len)
  2902. {
  2903. int i;
  2904. const node_t *r, *choice;
  2905. crypt_path_t *cpath;
  2906. smartlist_t *excluded;
  2907. const or_options_t *options = get_options();
  2908. router_crn_flags_t flags = CRN_NEED_DESC;
  2909. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2910. purpose <= CIRCUIT_PURPOSE_MAX_);
  2911. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2912. excluded = smartlist_new();
  2913. if ((r = build_state_get_exit_node(state))) {
  2914. nodelist_add_node_and_family(excluded, r);
  2915. }
  2916. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2917. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2918. nodelist_add_node_and_family(excluded, r);
  2919. }
  2920. }
  2921. if (state->need_uptime)
  2922. flags |= CRN_NEED_UPTIME;
  2923. if (state->need_capacity)
  2924. flags |= CRN_NEED_CAPACITY;
  2925. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2926. flags |= CRN_ALLOW_INVALID;
  2927. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2928. smartlist_free(excluded);
  2929. return choice;
  2930. }
  2931. /** Pick a good entry server for the circuit to be built according to
  2932. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2933. * router (if we're an OR), and respect firewall settings; if we're
  2934. * configured to use entry guards, return one.
  2935. *
  2936. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2937. * guard, not for any particular circuit.
  2938. */
  2939. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2940. const node_t *
  2941. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2942. {
  2943. const node_t *choice;
  2944. smartlist_t *excluded;
  2945. const or_options_t *options = get_options();
  2946. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2947. const node_t *node;
  2948. if (state && options->UseEntryGuards &&
  2949. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2950. /* This request is for an entry server to use for a regular circuit,
  2951. * and we use entry guard nodes. Just return one of the guard nodes. */
  2952. return choose_random_entry(state);
  2953. }
  2954. excluded = smartlist_new();
  2955. if (state && (node = build_state_get_exit_node(state))) {
  2956. /* Exclude the exit node from the state, if we have one. Also exclude its
  2957. * family. */
  2958. nodelist_add_node_and_family(excluded, node);
  2959. }
  2960. if (firewall_is_fascist_or()) {
  2961. /* Exclude all ORs that we can't reach through our firewall */
  2962. smartlist_t *nodes = nodelist_get_list();
  2963. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2964. if (!fascist_firewall_allows_node(node))
  2965. smartlist_add(excluded, (void*)node);
  2966. });
  2967. }
  2968. /* and exclude current entry guards and their families, if applicable */
  2969. if (options->UseEntryGuards) {
  2970. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2971. {
  2972. if ((node = node_get_by_id(entry->identity))) {
  2973. nodelist_add_node_and_family(excluded, node);
  2974. }
  2975. });
  2976. }
  2977. if (state) {
  2978. if (state->need_uptime)
  2979. flags |= CRN_NEED_UPTIME;
  2980. if (state->need_capacity)
  2981. flags |= CRN_NEED_CAPACITY;
  2982. }
  2983. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  2984. flags |= CRN_ALLOW_INVALID;
  2985. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2986. smartlist_free(excluded);
  2987. return choice;
  2988. }
  2989. /** Return the first non-open hop in cpath, or return NULL if all
  2990. * hops are open. */
  2991. static crypt_path_t *
  2992. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2993. {
  2994. crypt_path_t *hop = cpath;
  2995. do {
  2996. if (hop->state != CPATH_STATE_OPEN)
  2997. return hop;
  2998. hop = hop->next;
  2999. } while (hop != cpath);
  3000. return NULL;
  3001. }
  3002. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  3003. * based on <b>state</b>. Append the hop info to head_ptr.
  3004. */
  3005. static int
  3006. onion_extend_cpath(origin_circuit_t *circ)
  3007. {
  3008. uint8_t purpose = circ->base_.purpose;
  3009. cpath_build_state_t *state = circ->build_state;
  3010. int cur_len = circuit_get_cpath_len(circ);
  3011. extend_info_t *info = NULL;
  3012. if (cur_len >= state->desired_path_len) {
  3013. log_debug(LD_CIRC, "Path is complete: %d steps long",
  3014. state->desired_path_len);
  3015. return 1;
  3016. }
  3017. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  3018. state->desired_path_len);
  3019. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  3020. info = extend_info_dup(state->chosen_exit);
  3021. } else if (cur_len == 0) { /* picking first node */
  3022. const node_t *r = choose_good_entry_server(purpose, state);
  3023. if (r) {
  3024. /* If we're a client, use the preferred address rather than the
  3025. primary address, for potentially connecting to an IPv6 OR
  3026. port. */
  3027. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  3028. tor_assert(info);
  3029. }
  3030. } else {
  3031. const node_t *r =
  3032. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  3033. if (r) {
  3034. info = extend_info_from_node(r, 0);
  3035. tor_assert(info);
  3036. }
  3037. }
  3038. if (!info) {
  3039. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  3040. "this circuit.", cur_len);
  3041. return -1;
  3042. }
  3043. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  3044. extend_info_describe(info),
  3045. cur_len+1, build_state_get_exit_nickname(state));
  3046. onion_append_hop(&circ->cpath, info);
  3047. extend_info_free(info);
  3048. return 0;
  3049. }
  3050. /** Create a new hop, annotate it with information about its
  3051. * corresponding router <b>choice</b>, and append it to the
  3052. * end of the cpath <b>head_ptr</b>. */
  3053. static int
  3054. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  3055. {
  3056. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  3057. /* link hop into the cpath, at the end. */
  3058. onion_append_to_cpath(head_ptr, hop);
  3059. hop->magic = CRYPT_PATH_MAGIC;
  3060. hop->state = CPATH_STATE_CLOSED;
  3061. hop->extend_info = extend_info_dup(choice);
  3062. hop->package_window = circuit_initial_package_window();
  3063. hop->deliver_window = CIRCWINDOW_START;
  3064. return 0;
  3065. }
  3066. /** Allocate a new extend_info object based on the various arguments. */
  3067. extend_info_t *
  3068. extend_info_new(const char *nickname, const char *digest,
  3069. crypto_pk_t *onion_key,
  3070. const curve25519_public_key_t *curve25519_key,
  3071. const tor_addr_t *addr, uint16_t port)
  3072. {
  3073. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  3074. memcpy(info->identity_digest, digest, DIGEST_LEN);
  3075. if (nickname)
  3076. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  3077. if (onion_key)
  3078. info->onion_key = crypto_pk_dup_key(onion_key);
  3079. #ifdef CURVE25519_ENABLED
  3080. if (curve25519_key)
  3081. memcpy(&info->curve25519_onion_key, curve25519_key,
  3082. sizeof(curve25519_public_key_t));
  3083. #else
  3084. (void)curve25519_key;
  3085. #endif
  3086. tor_addr_copy(&info->addr, addr);
  3087. info->port = port;
  3088. return info;
  3089. }
  3090. /** Allocate and return a new extend_info that can be used to build a
  3091. * circuit to or through the node <b>node</b>. Use the primary address
  3092. * of the node (i.e. its IPv4 address) unless
  3093. * <b>for_direct_connect</b> is true, in which case the preferred
  3094. * address is used instead. May return NULL if there is not enough
  3095. * info about <b>node</b> to extend to it--for example, if there is no
  3096. * routerinfo_t or microdesc_t.
  3097. **/
  3098. extend_info_t *
  3099. extend_info_from_node(const node_t *node, int for_direct_connect)
  3100. {
  3101. tor_addr_port_t ap;
  3102. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  3103. return NULL;
  3104. if (for_direct_connect)
  3105. node_get_pref_orport(node, &ap);
  3106. else
  3107. node_get_prim_orport(node, &ap);
  3108. log_debug(LD_CIRC, "using %s for %s",
  3109. fmt_addrport(&ap.addr, ap.port),
  3110. node->ri ? node->ri->nickname : node->rs->nickname);
  3111. if (node->ri)
  3112. return extend_info_new(node->ri->nickname,
  3113. node->identity,
  3114. node->ri->onion_pkey,
  3115. node->ri->onion_curve25519_pkey,
  3116. &ap.addr,
  3117. ap.port);
  3118. else if (node->rs && node->md)
  3119. return extend_info_new(node->rs->nickname,
  3120. node->identity,
  3121. node->md->onion_pkey,
  3122. node->md->onion_curve25519_pkey,
  3123. &ap.addr,
  3124. ap.port);
  3125. else
  3126. return NULL;
  3127. }
  3128. /** Release storage held by an extend_info_t struct. */
  3129. void
  3130. extend_info_free(extend_info_t *info)
  3131. {
  3132. if (!info)
  3133. return;
  3134. crypto_pk_free(info->onion_key);
  3135. tor_free(info);
  3136. }
  3137. /** Allocate and return a new extend_info_t with the same contents as
  3138. * <b>info</b>. */
  3139. extend_info_t *
  3140. extend_info_dup(extend_info_t *info)
  3141. {
  3142. extend_info_t *newinfo;
  3143. tor_assert(info);
  3144. newinfo = tor_malloc(sizeof(extend_info_t));
  3145. memcpy(newinfo, info, sizeof(extend_info_t));
  3146. if (info->onion_key)
  3147. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  3148. else
  3149. newinfo->onion_key = NULL;
  3150. return newinfo;
  3151. }
  3152. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  3153. * If there is no chosen exit, or if we don't know the routerinfo_t for
  3154. * the chosen exit, return NULL.
  3155. */
  3156. const node_t *
  3157. build_state_get_exit_node(cpath_build_state_t *state)
  3158. {
  3159. if (!state || !state->chosen_exit)
  3160. return NULL;
  3161. return node_get_by_id(state->chosen_exit->identity_digest);
  3162. }
  3163. /** Return the nickname for the chosen exit router in <b>state</b>. If
  3164. * there is no chosen exit, or if we don't know the routerinfo_t for the
  3165. * chosen exit, return NULL.
  3166. */
  3167. const char *
  3168. build_state_get_exit_nickname(cpath_build_state_t *state)
  3169. {
  3170. if (!state || !state->chosen_exit)
  3171. return NULL;
  3172. return state->chosen_exit->nickname;
  3173. }