circuitbuild.c 86 KB

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