circuitbuild.c 100 KB

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