circuitbuild.c 128 KB

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