circuitbuild.c 128 KB

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