circuitbuild.c 90 KB

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