circuitbuild.c 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770
  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-2017, 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 "bridges.h"
  29. #include "channel.h"
  30. #include "circpathbias.h"
  31. #define CIRCUITBUILD_PRIVATE
  32. #include "circuitbuild.h"
  33. #include "circuitlist.h"
  34. #include "circuitstats.h"
  35. #include "circuituse.h"
  36. #include "command.h"
  37. #include "config.h"
  38. #include "confparse.h"
  39. #include "connection.h"
  40. #include "connection_edge.h"
  41. #include "connection_or.h"
  42. #include "control.h"
  43. #include "crypto.h"
  44. #include "directory.h"
  45. #include "entrynodes.h"
  46. #include "main.h"
  47. #include "microdesc.h"
  48. #include "networkstatus.h"
  49. #include "nodelist.h"
  50. #include "onion.h"
  51. #include "onion_tap.h"
  52. #include "onion_fast.h"
  53. #include "policies.h"
  54. #include "relay.h"
  55. #include "rendcommon.h"
  56. #include "rephist.h"
  57. #include "router.h"
  58. #include "routerlist.h"
  59. #include "routerparse.h"
  60. #include "routerset.h"
  61. #include "transports.h"
  62. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  63. uint16_t port,
  64. const char *id_digest,
  65. const ed25519_public_key_t *ed_id);
  66. static int circuit_deliver_create_cell(circuit_t *circ,
  67. const create_cell_t *create_cell,
  68. int relayed);
  69. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  70. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  71. static int onion_extend_cpath(origin_circuit_t *circ);
  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. /** Return the guard state associated with <b>circ</b>, which may be NULL. */
  474. circuit_guard_state_t *
  475. origin_circuit_get_guard_state(origin_circuit_t *circ)
  476. {
  477. return circ->guard_state;
  478. }
  479. /** Start establishing the first hop of our circuit. Figure out what
  480. * OR we should connect to, and if necessary start the connection to
  481. * it. If we're already connected, then send the 'create' cell.
  482. * Return 0 for ok, -reason if circ should be marked-for-close. */
  483. int
  484. circuit_handle_first_hop(origin_circuit_t *circ)
  485. {
  486. crypt_path_t *firsthop;
  487. channel_t *n_chan;
  488. int err_reason = 0;
  489. const char *msg = NULL;
  490. int should_launch = 0;
  491. const or_options_t *options = get_options();
  492. firsthop = onion_next_hop_in_cpath(circ->cpath);
  493. tor_assert(firsthop);
  494. tor_assert(firsthop->extend_info);
  495. /* Some bridges are on private addresses. Others pass a dummy private
  496. * address to the pluggable transport, which ignores it.
  497. * Deny the connection if:
  498. * - the address is internal, and
  499. * - we're not connecting to a configured bridge, and
  500. * - we're not configured to allow extends to private addresses. */
  501. if (tor_addr_is_internal(&firsthop->extend_info->addr, 0) &&
  502. !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
  503. !options->ExtendAllowPrivateAddresses) {
  504. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  505. "Client asked me to connect directly to a private address");
  506. return -END_CIRC_REASON_TORPROTOCOL;
  507. }
  508. /* now see if we're already connected to the first OR in 'route' */
  509. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  510. fmt_addrport(&firsthop->extend_info->addr,
  511. firsthop->extend_info->port));
  512. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  513. &firsthop->extend_info->ed_identity,
  514. &firsthop->extend_info->addr,
  515. &msg,
  516. &should_launch);
  517. if (!n_chan) {
  518. /* not currently connected in a useful way. */
  519. log_info(LD_CIRC, "Next router is %s: %s",
  520. safe_str_client(extend_info_describe(firsthop->extend_info)),
  521. msg?msg:"???");
  522. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  523. if (should_launch) {
  524. if (circ->build_state->onehop_tunnel)
  525. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  526. n_chan = channel_connect_for_circuit(
  527. &firsthop->extend_info->addr,
  528. firsthop->extend_info->port,
  529. firsthop->extend_info->identity_digest,
  530. &firsthop->extend_info->ed_identity);
  531. if (!n_chan) { /* connect failed, forget the whole thing */
  532. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  533. return -END_CIRC_REASON_CONNECTFAILED;
  534. }
  535. }
  536. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  537. /* return success. The onion/circuit/etc will be taken care of
  538. * automatically (may already have been) whenever n_chan reaches
  539. * OR_CONN_STATE_OPEN.
  540. */
  541. return 0;
  542. } else { /* it's already open. use it. */
  543. tor_assert(!circ->base_.n_hop);
  544. circ->base_.n_chan = n_chan;
  545. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  546. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  547. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  548. circ->base_.n_chan = NULL;
  549. return err_reason;
  550. }
  551. }
  552. return 0;
  553. }
  554. /** Find any circuits that are waiting on <b>or_conn</b> to become
  555. * open and get them to send their create cells forward.
  556. *
  557. * Status is 1 if connect succeeded, or 0 if connect failed.
  558. *
  559. * Close_origin_circuits is 1 if we should close all the origin circuits
  560. * through this channel, or 0 otherwise. (This happens when we want to retry
  561. * an older guard.)
  562. */
  563. void
  564. circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
  565. {
  566. smartlist_t *pending_circs;
  567. int err_reason = 0;
  568. tor_assert(chan);
  569. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  570. chan->nickname ? chan->nickname : "NULL",
  571. channel_get_canonical_remote_descr(chan), status);
  572. pending_circs = smartlist_new();
  573. circuit_get_all_pending_on_channel(pending_circs, chan);
  574. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  575. {
  576. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  577. * leaving them in in case it's possible for the status of a circuit to
  578. * change as we're going down the list. */
  579. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  580. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  581. continue;
  582. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  583. /* Look at addr/port. This is an unkeyed connection. */
  584. if (!channel_matches_extend_info(chan, circ->n_hop))
  585. continue;
  586. } else {
  587. /* We expected a key. See if it's the right one. */
  588. if (tor_memneq(chan->identity_digest,
  589. circ->n_hop->identity_digest, DIGEST_LEN))
  590. continue;
  591. }
  592. if (!status) { /* chan failed; close circ */
  593. log_info(LD_CIRC,"Channel failed; closing circ.");
  594. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  595. continue;
  596. }
  597. if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
  598. log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
  599. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  600. continue;
  601. }
  602. log_debug(LD_CIRC, "Found circ, sending create cell.");
  603. /* circuit_deliver_create_cell will set n_circ_id and add us to
  604. * chan_circuid_circuit_map, so we don't need to call
  605. * set_circid_chan here. */
  606. circ->n_chan = chan;
  607. extend_info_free(circ->n_hop);
  608. circ->n_hop = NULL;
  609. if (CIRCUIT_IS_ORIGIN(circ)) {
  610. if ((err_reason =
  611. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  612. log_info(LD_CIRC,
  613. "send_next_onion_skin failed; circuit marked for closing.");
  614. circuit_mark_for_close(circ, -err_reason);
  615. continue;
  616. /* XXX could this be bad, eg if next_onion_skin failed because conn
  617. * died? */
  618. }
  619. } else {
  620. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  621. tor_assert(circ->n_chan_create_cell);
  622. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  623. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  624. continue;
  625. }
  626. tor_free(circ->n_chan_create_cell);
  627. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  628. }
  629. }
  630. SMARTLIST_FOREACH_END(circ);
  631. smartlist_free(pending_circs);
  632. }
  633. /** Find a new circid that isn't currently in use on the circ->n_chan
  634. * for the outgoing
  635. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  636. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  637. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  638. * it. Return -1 if we failed to find a suitable circid, else return 0.
  639. */
  640. static int
  641. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  642. int relayed)
  643. {
  644. cell_t cell;
  645. circid_t id;
  646. int r;
  647. tor_assert(circ);
  648. tor_assert(circ->n_chan);
  649. tor_assert(create_cell);
  650. tor_assert(create_cell->cell_type == CELL_CREATE ||
  651. create_cell->cell_type == CELL_CREATE_FAST ||
  652. create_cell->cell_type == CELL_CREATE2);
  653. id = get_unique_circ_id_by_chan(circ->n_chan);
  654. if (!id) {
  655. static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
  656. log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
  657. "failed to get unique circID.");
  658. goto error;
  659. }
  660. memset(&cell, 0, sizeof(cell_t));
  661. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  662. : create_cell_format(&cell, create_cell);
  663. if (r < 0) {
  664. log_warn(LD_CIRC,"Couldn't format create cell");
  665. goto error;
  666. }
  667. log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
  668. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  669. cell.circ_id = circ->n_circ_id;
  670. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  671. CELL_DIRECTION_OUT, 0);
  672. if (CIRCUIT_IS_ORIGIN(circ)) {
  673. /* Update began timestamp for circuits starting their first hop */
  674. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  675. if (!CHANNEL_IS_OPEN(circ->n_chan)) {
  676. log_warn(LD_CIRC,
  677. "Got first hop for a circuit without an opened channel. "
  678. "State: %s.", channel_state_to_string(circ->n_chan->state));
  679. tor_fragile_assert();
  680. }
  681. tor_gettimeofday(&circ->timestamp_began);
  682. }
  683. /* mark it so it gets better rate limiting treatment. */
  684. channel_timestamp_client(circ->n_chan);
  685. }
  686. return 0;
  687. error:
  688. circ->n_chan = NULL;
  689. return -1;
  690. }
  691. /** We've decided to start our reachability testing. If all
  692. * is set, log this to the user. Return 1 if we did, or 0 if
  693. * we chose not to log anything. */
  694. int
  695. inform_testing_reachability(void)
  696. {
  697. char dirbuf[128];
  698. char *address;
  699. const routerinfo_t *me = router_get_my_routerinfo();
  700. if (!me)
  701. return 0;
  702. address = tor_dup_ip(me->addr);
  703. control_event_server_status(LOG_NOTICE,
  704. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  705. address, me->or_port);
  706. if (me->dir_port) {
  707. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  708. address, me->dir_port);
  709. control_event_server_status(LOG_NOTICE,
  710. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  711. address, me->dir_port);
  712. }
  713. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  714. "(this may take up to %d minutes -- look for log "
  715. "messages indicating success)",
  716. address, me->or_port,
  717. me->dir_port ? dirbuf : "",
  718. me->dir_port ? "are" : "is",
  719. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  720. tor_free(address);
  721. return 1;
  722. }
  723. /** Return true iff we should send a create_fast cell to start building a given
  724. * circuit */
  725. static inline int
  726. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  727. {
  728. const or_options_t *options = get_options();
  729. tor_assert(circ->cpath);
  730. tor_assert(circ->cpath->extend_info);
  731. if (!circuit_has_usable_onion_key(circ)) {
  732. /* We don't have ntor, and we don't have or can't use TAP,
  733. * so our hand is forced: only a create_fast will work. */
  734. return 1;
  735. }
  736. if (public_server_mode(options)) {
  737. /* We're a server, and we have a usable onion key. We can choose.
  738. * Prefer to blend our circuit into the other circuits we are
  739. * creating on behalf of others. */
  740. return 0;
  741. }
  742. return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
  743. }
  744. /** Return true if <b>circ</b> is the type of circuit we want to count
  745. * timeouts from. In particular, we want it to have not completed yet
  746. * (already completing indicates we cannibalized it), and we want it to
  747. * have exactly three hops.
  748. */
  749. int
  750. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  751. {
  752. return !circ->has_opened
  753. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  754. }
  755. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  756. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  757. * accordingly.
  758. * Note that TAP handshakes in CREATE cells are only used for direct
  759. * connections:
  760. * - from Tor2web to intro points not in the client's consensus, and
  761. * - from Single Onions to rend points not in the service's consensus.
  762. * This is checked in onion_populate_cpath. */
  763. static void
  764. circuit_pick_create_handshake(uint8_t *cell_type_out,
  765. uint16_t *handshake_type_out,
  766. const extend_info_t *ei)
  767. {
  768. /* torspec says: In general, clients SHOULD use CREATE whenever they are
  769. * using the TAP handshake, and CREATE2 otherwise. */
  770. if (extend_info_supports_ntor(ei)) {
  771. *cell_type_out = CELL_CREATE2;
  772. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  773. } else {
  774. /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
  775. *cell_type_out = CELL_CREATE;
  776. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  777. }
  778. }
  779. /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
  780. * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
  781. * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
  782. * and *<b>create_cell_type_out</b> accordingly.
  783. * Note that TAP handshakes in EXTEND cells are only used:
  784. * - from clients to intro points, and
  785. * - from hidden services to rend points.
  786. * This is checked in onion_populate_cpath.
  787. */
  788. static void
  789. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  790. uint8_t *create_cell_type_out,
  791. uint16_t *handshake_type_out,
  792. const extend_info_t *ei)
  793. {
  794. uint8_t t;
  795. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  796. /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
  797. * handshake... In other cases, clients SHOULD use EXTEND2. */
  798. if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
  799. *cell_type_out = RELAY_COMMAND_EXTEND2;
  800. *create_cell_type_out = CELL_CREATE2;
  801. } else {
  802. /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
  803. *cell_type_out = RELAY_COMMAND_EXTEND;
  804. *create_cell_type_out = CELL_CREATE;
  805. }
  806. }
  807. /**
  808. * Return true iff <b>purpose</b> is a purpose for a circuit which is
  809. * allowed to have no guard configured, even if the circuit is multihop
  810. * and guards are enabled.
  811. */
  812. static int
  813. circuit_purpose_may_omit_guard(int purpose)
  814. {
  815. switch (purpose) {
  816. case CIRCUIT_PURPOSE_TESTING:
  817. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  818. /* Testing circuits may omit guards because they're measuring
  819. * liveness or performance, and don't want guards to interfere. */
  820. return 1;
  821. default:
  822. /* All other multihop circuits should use guards if guards are
  823. * enabled. */
  824. return 0;
  825. }
  826. }
  827. /** This is the backbone function for building circuits.
  828. *
  829. * If circ's first hop is closed, then we need to build a create
  830. * cell and send it forward.
  831. *
  832. * Otherwise, we need to build a relay extend cell and send it
  833. * forward.
  834. *
  835. * Return -reason if we want to tear down circ, else return 0.
  836. */
  837. int
  838. circuit_send_next_onion_skin(origin_circuit_t *circ)
  839. {
  840. crypt_path_t *hop;
  841. const node_t *node;
  842. tor_assert(circ);
  843. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  844. /* This is the first hop. */
  845. create_cell_t cc;
  846. int fast;
  847. int len;
  848. log_debug(LD_CIRC,"First skin; sending create cell.");
  849. memset(&cc, 0, sizeof(cc));
  850. if (circ->build_state->onehop_tunnel)
  851. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  852. else {
  853. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  854. /* If this is not a one-hop tunnel, the channel is being used
  855. * for traffic that wants anonymity and protection from traffic
  856. * analysis (such as netflow record retention). That means we want
  857. * to pad it.
  858. */
  859. if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
  860. circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
  861. }
  862. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  863. fast = should_use_create_fast_for_circuit(circ);
  864. if (!fast) {
  865. /* We are an OR and we know the right onion key: we should
  866. * send a create cell.
  867. */
  868. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  869. circ->cpath->extend_info);
  870. } else {
  871. /* We are not an OR, and we're building the first hop of a circuit to a
  872. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  873. * and a DH operation. */
  874. cc.cell_type = CELL_CREATE_FAST;
  875. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  876. }
  877. len = onion_skin_create(cc.handshake_type,
  878. circ->cpath->extend_info,
  879. &circ->cpath->handshake_state,
  880. cc.onionskin);
  881. if (len < 0) {
  882. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  883. return - END_CIRC_REASON_INTERNAL;
  884. }
  885. cc.handshake_len = len;
  886. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  887. return - END_CIRC_REASON_RESOURCELIMIT;
  888. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  889. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  890. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  891. fast ? "CREATE_FAST" : "CREATE",
  892. node ? node_describe(node) : "<unnamed>");
  893. } else {
  894. extend_cell_t ec;
  895. int len;
  896. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  897. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  898. log_debug(LD_CIRC,"starting to send subsequent skin.");
  899. hop = onion_next_hop_in_cpath(circ->cpath);
  900. memset(&ec, 0, sizeof(ec));
  901. if (!hop) {
  902. /* done building the circuit. whew. */
  903. guard_usable_t r;
  904. if (! circ->guard_state) {
  905. if (circuit_get_cpath_len(circ) != 1 &&
  906. ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
  907. get_options()->UseEntryGuards) {
  908. log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
  909. "guard state",
  910. circuit_get_cpath_len(circ), circ, circ->base_.purpose);
  911. }
  912. r = GUARD_USABLE_NOW;
  913. } else {
  914. r = entry_guard_succeeded(&circ->guard_state);
  915. }
  916. const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
  917. if (r == GUARD_USABLE_NOW) {
  918. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  919. } else if (r == GUARD_MAYBE_USABLE_LATER) {
  920. // Wait till either a better guard succeeds, or till
  921. // all better guards fail.
  922. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
  923. } else {
  924. tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
  925. return - END_CIRC_REASON_INTERNAL;
  926. }
  927. /* XXXX #21422 -- the rest of this branch needs careful thought!
  928. * Some of the things here need to happen when a circuit becomes
  929. * mechanically open; some need to happen when it is actually usable.
  930. * I think I got them right, but more checking would be wise. -NM
  931. */
  932. if (circuit_timeout_want_to_count_circ(circ)) {
  933. struct timeval end;
  934. long timediff;
  935. tor_gettimeofday(&end);
  936. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  937. /*
  938. * If the circuit build time is much greater than we would have cut
  939. * it off at, we probably had a suspend event along this codepath,
  940. * and we should discard the value.
  941. */
  942. if (timediff < 0 ||
  943. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  944. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  945. "Assuming clock jump. Purpose %d (%s)", timediff,
  946. circ->base_.purpose,
  947. circuit_purpose_to_string(circ->base_.purpose));
  948. } else if (!circuit_build_times_disabled(get_options())) {
  949. /* Only count circuit times if the network is live */
  950. if (circuit_build_times_network_check_live(
  951. get_circuit_build_times())) {
  952. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  953. (build_time_t)timediff);
  954. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  955. }
  956. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  957. circuit_build_times_network_circ_success(
  958. get_circuit_build_times_mutable());
  959. }
  960. }
  961. }
  962. log_info(LD_CIRC,"circuit built!");
  963. circuit_reset_failure_count(0);
  964. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  965. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  966. }
  967. pathbias_count_build_success(circ);
  968. circuit_rep_hist_note_result(circ);
  969. if (is_usable_for_streams)
  970. circuit_has_opened(circ); /* do other actions as necessary */
  971. if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
  972. const or_options_t *options = get_options();
  973. note_that_we_completed_a_circuit();
  974. /* FFFF Log a count of known routers here */
  975. log_notice(LD_GENERAL,
  976. "Tor has successfully opened a circuit. "
  977. "Looks like client functionality is working.");
  978. if (control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0) == 0) {
  979. log_notice(LD_GENERAL,
  980. "Tor has successfully opened a circuit. "
  981. "Looks like client functionality is working.");
  982. }
  983. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  984. clear_broken_connection_map(1);
  985. if (server_mode(options) && !check_whether_orport_reachable(options)) {
  986. inform_testing_reachability();
  987. consider_testing_reachability(1, 1);
  988. }
  989. }
  990. /* We're done with measurement circuits here. Just close them */
  991. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  992. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  993. }
  994. return 0;
  995. }
  996. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  997. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  998. return - END_CIRC_REASON_INTERNAL;
  999. }
  1000. circuit_pick_extend_handshake(&ec.cell_type,
  1001. &ec.create_cell.cell_type,
  1002. &ec.create_cell.handshake_type,
  1003. hop->extend_info);
  1004. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  1005. ec.orport_ipv4.port = hop->extend_info->port;
  1006. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  1007. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  1008. /* Set the ED25519 identity too -- it will only get included
  1009. * in the extend2 cell if we're configured to use it, though. */
  1010. ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
  1011. len = onion_skin_create(ec.create_cell.handshake_type,
  1012. hop->extend_info,
  1013. &hop->handshake_state,
  1014. ec.create_cell.onionskin);
  1015. if (len < 0) {
  1016. log_warn(LD_CIRC,"onion_skin_create failed.");
  1017. return - END_CIRC_REASON_INTERNAL;
  1018. }
  1019. ec.create_cell.handshake_len = len;
  1020. log_info(LD_CIRC,"Sending extend relay cell.");
  1021. {
  1022. uint8_t command = 0;
  1023. uint16_t payload_len=0;
  1024. uint8_t payload[RELAY_PAYLOAD_SIZE];
  1025. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  1026. log_warn(LD_CIRC,"Couldn't format extend cell");
  1027. return -END_CIRC_REASON_INTERNAL;
  1028. }
  1029. /* send it to hop->prev, because it will transfer
  1030. * it to a create cell and then send to hop */
  1031. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  1032. command,
  1033. (char*)payload, payload_len,
  1034. hop->prev) < 0)
  1035. return 0; /* circuit is closed */
  1036. }
  1037. hop->state = CPATH_STATE_AWAITING_KEYS;
  1038. }
  1039. return 0;
  1040. }
  1041. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  1042. * something has also gone wrong with our network: notify the user,
  1043. * and abandon all not-yet-used circuits. */
  1044. void
  1045. circuit_note_clock_jumped(int seconds_elapsed)
  1046. {
  1047. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  1048. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  1049. "assuming established circuits no longer work.",
  1050. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  1051. seconds_elapsed >=0 ? "forward" : "backward");
  1052. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  1053. seconds_elapsed);
  1054. /* so we log when it works again */
  1055. note_that_we_maybe_cant_complete_circuits();
  1056. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  1057. "CLOCK_JUMPED");
  1058. circuit_mark_all_unused_circs();
  1059. circuit_mark_all_dirty_circs_as_unusable();
  1060. if (seconds_elapsed < 0) {
  1061. /* Restart all the timers in case we jumped a long way into the past. */
  1062. reset_all_main_loop_timers();
  1063. }
  1064. }
  1065. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  1066. * skin and identity digest for the next hop. If we're already connected,
  1067. * pass the onion skin to the next hop using a create cell; otherwise
  1068. * launch a new OR connection, and <b>circ</b> will notice when the
  1069. * connection succeeds or fails.
  1070. *
  1071. * Return -1 if we want to warn and tear down the circuit, else return 0.
  1072. */
  1073. int
  1074. circuit_extend(cell_t *cell, circuit_t *circ)
  1075. {
  1076. channel_t *n_chan;
  1077. relay_header_t rh;
  1078. extend_cell_t ec;
  1079. const char *msg = NULL;
  1080. int should_launch = 0;
  1081. if (circ->n_chan) {
  1082. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1083. "n_chan already set. Bug/attack. Closing.");
  1084. return -1;
  1085. }
  1086. if (circ->n_hop) {
  1087. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1088. "conn to next hop already launched. Bug/attack. Closing.");
  1089. return -1;
  1090. }
  1091. if (!server_mode(get_options())) {
  1092. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1093. "Got an extend cell, but running as a client. Closing.");
  1094. return -1;
  1095. }
  1096. relay_header_unpack(&rh, cell->payload);
  1097. if (extend_cell_parse(&ec, rh.command,
  1098. cell->payload+RELAY_HEADER_SIZE,
  1099. rh.length) < 0) {
  1100. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1101. "Can't parse extend cell. Closing circuit.");
  1102. return -1;
  1103. }
  1104. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  1105. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1106. "Client asked me to extend to zero destination port or addr.");
  1107. return -1;
  1108. }
  1109. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  1110. !get_options()->ExtendAllowPrivateAddresses) {
  1111. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1112. "Client asked me to extend to a private address");
  1113. return -1;
  1114. }
  1115. /* Check if they asked us for 0000..0000. We support using
  1116. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  1117. * but we don't want to let clients send us extend cells for empty
  1118. * fingerprints -- a) because it opens the user up to a mitm attack,
  1119. * and b) because it lets an attacker force the relay to hold open a
  1120. * new TLS connection for each extend request. */
  1121. if (tor_digest_is_zero((const char*)ec.node_id)) {
  1122. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1123. "Client asked me to extend without specifying an id_digest.");
  1124. return -1;
  1125. }
  1126. /* Fill in ed_pubkey if it was not provided and we can infer it from
  1127. * our networkstatus */
  1128. if (ed25519_public_key_is_zero(&ec.ed_pubkey)) {
  1129. const node_t *node = node_get_by_id((const char*)ec.node_id);
  1130. const ed25519_public_key_t *node_ed_id = NULL;
  1131. if (node &&
  1132. node_supports_ed25519_link_authentication(node) &&
  1133. (node_ed_id = node_get_ed25519_id(node))) {
  1134. ed25519_pubkey_copy(&ec.ed_pubkey, node_ed_id);
  1135. }
  1136. }
  1137. /* Next, check if we're being asked to connect to the hop that the
  1138. * extend cell came from. There isn't any reason for that, and it can
  1139. * assist circular-path attacks. */
  1140. if (tor_memeq(ec.node_id,
  1141. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  1142. DIGEST_LEN)) {
  1143. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1144. "Client asked me to extend back to the previous hop.");
  1145. return -1;
  1146. }
  1147. /* Check the previous hop Ed25519 ID too */
  1148. if (! ed25519_public_key_is_zero(&ec.ed_pubkey) &&
  1149. ed25519_pubkey_eq(&ec.ed_pubkey,
  1150. &TO_OR_CIRCUIT(circ)->p_chan->ed25519_identity)) {
  1151. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1152. "Client asked me to extend back to the previous hop "
  1153. "(by Ed25519 ID).");
  1154. }
  1155. n_chan = channel_get_for_extend((const char*)ec.node_id,
  1156. &ec.ed_pubkey,
  1157. &ec.orport_ipv4.addr,
  1158. &msg,
  1159. &should_launch);
  1160. if (!n_chan) {
  1161. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  1162. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  1163. msg?msg:"????");
  1164. circ->n_hop = extend_info_new(NULL /*nickname*/,
  1165. (const char*)ec.node_id,
  1166. &ec.ed_pubkey,
  1167. NULL, /*onion_key*/
  1168. NULL, /*curve25519_key*/
  1169. &ec.orport_ipv4.addr,
  1170. ec.orport_ipv4.port);
  1171. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  1172. sizeof(ec.create_cell));
  1173. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  1174. if (should_launch) {
  1175. /* we should try to open a connection */
  1176. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  1177. ec.orport_ipv4.port,
  1178. (const char*)ec.node_id,
  1179. &ec.ed_pubkey);
  1180. if (!n_chan) {
  1181. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  1182. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  1183. return 0;
  1184. }
  1185. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  1186. }
  1187. /* return success. The onion/circuit/etc will be taken care of
  1188. * automatically (may already have been) whenever n_chan reaches
  1189. * OR_CONN_STATE_OPEN.
  1190. */
  1191. return 0;
  1192. }
  1193. tor_assert(!circ->n_hop); /* Connection is already established. */
  1194. circ->n_chan = n_chan;
  1195. log_debug(LD_CIRC,
  1196. "n_chan is %s",
  1197. channel_get_canonical_remote_descr(n_chan));
  1198. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  1199. return -1;
  1200. return 0;
  1201. }
  1202. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  1203. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  1204. * used as follows:
  1205. * - 20 to initialize f_digest
  1206. * - 20 to initialize b_digest
  1207. * - 16 to key f_crypto
  1208. * - 16 to key b_crypto
  1209. *
  1210. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  1211. */
  1212. int
  1213. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  1214. int reverse)
  1215. {
  1216. crypto_digest_t *tmp_digest;
  1217. crypto_cipher_t *tmp_crypto;
  1218. tor_assert(cpath);
  1219. tor_assert(key_data);
  1220. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  1221. cpath->f_digest || cpath->b_digest));
  1222. cpath->f_digest = crypto_digest_new();
  1223. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  1224. cpath->b_digest = crypto_digest_new();
  1225. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  1226. if (!(cpath->f_crypto =
  1227. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  1228. log_warn(LD_BUG,"Forward cipher initialization failed.");
  1229. return -1;
  1230. }
  1231. if (!(cpath->b_crypto =
  1232. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  1233. log_warn(LD_BUG,"Backward cipher initialization failed.");
  1234. return -1;
  1235. }
  1236. if (reverse) {
  1237. tmp_digest = cpath->f_digest;
  1238. cpath->f_digest = cpath->b_digest;
  1239. cpath->b_digest = tmp_digest;
  1240. tmp_crypto = cpath->f_crypto;
  1241. cpath->f_crypto = cpath->b_crypto;
  1242. cpath->b_crypto = tmp_crypto;
  1243. }
  1244. return 0;
  1245. }
  1246. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  1247. * (The body of <b>reply</b> varies depending on what sort of handshake
  1248. * this is.)
  1249. *
  1250. * Calculate the appropriate keys and digests, make sure KH is
  1251. * correct, and initialize this hop of the cpath.
  1252. *
  1253. * Return - reason if we want to mark circ for close, else return 0.
  1254. */
  1255. int
  1256. circuit_finish_handshake(origin_circuit_t *circ,
  1257. const created_cell_t *reply)
  1258. {
  1259. char keys[CPATH_KEY_MATERIAL_LEN];
  1260. crypt_path_t *hop;
  1261. int rv;
  1262. if ((rv = pathbias_count_build_attempt(circ)) < 0) {
  1263. log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
  1264. return rv;
  1265. }
  1266. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1267. hop = circ->cpath;
  1268. } else {
  1269. hop = onion_next_hop_in_cpath(circ->cpath);
  1270. if (!hop) { /* got an extended when we're all done? */
  1271. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1272. return - END_CIRC_REASON_TORPROTOCOL;
  1273. }
  1274. }
  1275. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1276. {
  1277. const char *msg = NULL;
  1278. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1279. &hop->handshake_state,
  1280. reply->reply, reply->handshake_len,
  1281. (uint8_t*)keys, sizeof(keys),
  1282. (uint8_t*)hop->rend_circ_nonce,
  1283. &msg) < 0) {
  1284. if (msg)
  1285. log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
  1286. return -END_CIRC_REASON_TORPROTOCOL;
  1287. }
  1288. }
  1289. onion_handshake_state_release(&hop->handshake_state);
  1290. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1291. return -END_CIRC_REASON_TORPROTOCOL;
  1292. }
  1293. hop->state = CPATH_STATE_OPEN;
  1294. log_info(LD_CIRC,"Finished building circuit hop:");
  1295. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1296. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1297. return 0;
  1298. }
  1299. /** We received a relay truncated cell on circ.
  1300. *
  1301. * Since we don't send truncates currently, getting a truncated
  1302. * means that a connection broke or an extend failed. For now,
  1303. * just give up: force circ to close, and return 0.
  1304. */
  1305. int
  1306. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1307. {
  1308. // crypt_path_t *victim;
  1309. // connection_t *stream;
  1310. tor_assert(circ);
  1311. tor_assert(layer);
  1312. /* XXX Since we don't send truncates currently, getting a truncated
  1313. * means that a connection broke or an extend failed. For now,
  1314. * just give up.
  1315. */
  1316. circuit_mark_for_close(TO_CIRCUIT(circ),
  1317. END_CIRC_REASON_FLAG_REMOTE|reason);
  1318. return 0;
  1319. #if 0
  1320. while (layer->next != circ->cpath) {
  1321. /* we need to clear out layer->next */
  1322. victim = layer->next;
  1323. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1324. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1325. if (stream->cpath_layer == victim) {
  1326. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1327. stream->stream_id);
  1328. /* no need to send 'end' relay cells,
  1329. * because the other side's already dead
  1330. */
  1331. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1332. }
  1333. }
  1334. layer->next = victim->next;
  1335. circuit_free_cpath_node(victim);
  1336. }
  1337. log_info(LD_CIRC, "finished");
  1338. return 0;
  1339. #endif
  1340. }
  1341. /** Given a response payload and keys, initialize, then send a created
  1342. * cell back.
  1343. */
  1344. int
  1345. onionskin_answer(or_circuit_t *circ,
  1346. const created_cell_t *created_cell,
  1347. const char *keys,
  1348. const uint8_t *rend_circ_nonce)
  1349. {
  1350. cell_t cell;
  1351. crypt_path_t *tmp_cpath;
  1352. if (created_cell_format(&cell, created_cell) < 0) {
  1353. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1354. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1355. return -1;
  1356. }
  1357. cell.circ_id = circ->p_circ_id;
  1358. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1359. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1360. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1361. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1362. (unsigned int)get_uint32(keys),
  1363. (unsigned int)get_uint32(keys+20));
  1364. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1365. log_warn(LD_BUG,"Circuit initialization failed");
  1366. tor_free(tmp_cpath);
  1367. return -1;
  1368. }
  1369. circ->n_digest = tmp_cpath->f_digest;
  1370. circ->n_crypto = tmp_cpath->f_crypto;
  1371. circ->p_digest = tmp_cpath->b_digest;
  1372. circ->p_crypto = tmp_cpath->b_crypto;
  1373. tmp_cpath->magic = 0;
  1374. tor_free(tmp_cpath);
  1375. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1376. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1377. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1378. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1379. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1380. circ->is_first_hop ? "created_fast" : "created");
  1381. /* Ignore the local bit when ExtendAllowPrivateAddresses is set:
  1382. * it violates the assumption that private addresses are local.
  1383. * Also, many test networks run on local addresses, and
  1384. * TestingTorNetwork sets ExtendAllowPrivateAddresses. */
  1385. if ((!channel_is_local(circ->p_chan)
  1386. || get_options()->ExtendAllowPrivateAddresses)
  1387. && !channel_is_outgoing(circ->p_chan)) {
  1388. /* record that we could process create cells from a non-local conn
  1389. * that we didn't initiate; presumably this means that create cells
  1390. * can reach us too. */
  1391. router_orport_found_reachable();
  1392. }
  1393. return 0;
  1394. }
  1395. /** Helper for new_route_len(). Choose a circuit length for purpose
  1396. * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
  1397. * exit). If someone else chose the exit, they could be colluding
  1398. * with the exit, so add a randomly selected node to preserve
  1399. * anonymity.
  1400. *
  1401. * Here, "exit node" sometimes means an OR acting as an internal
  1402. * endpoint, rather than as a relay to an external endpoint. This
  1403. * means there need to be at least DEFAULT_ROUTE_LEN routers between
  1404. * us and the internal endpoint to preserve the same anonymity
  1405. * properties that we would get when connecting to an external
  1406. * endpoint. These internal endpoints can include:
  1407. *
  1408. * - Connections to a directory of hidden services
  1409. * (CIRCUIT_PURPOSE_C_GENERAL)
  1410. *
  1411. * - A client connecting to an introduction point, which the hidden
  1412. * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
  1413. * circuit_get_open_circ_or_launch() which rewrites it from
  1414. * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1415. *
  1416. * - A hidden service connecting to a rendezvous point, which the
  1417. * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND, via
  1418. * rend_service_receive_introduction() and
  1419. * rend_service_relaunch_rendezvous)
  1420. *
  1421. * There are currently two situations where we picked the exit node
  1422. * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
  1423. *
  1424. * - We are a hidden service connecting to an introduction point
  1425. * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, via
  1426. * rend_service_launch_establish_intro())
  1427. *
  1428. * - We are a router testing its own reachabiity
  1429. * (CIRCUIT_PURPOSE_TESTING, via consider_testing_reachability())
  1430. *
  1431. * onion_pick_cpath_exit() bypasses us (by not calling
  1432. * new_route_len()) in the one-hop tunnel case, so we don't need to
  1433. * handle that.
  1434. */
  1435. static int
  1436. route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
  1437. {
  1438. int routelen = DEFAULT_ROUTE_LEN;
  1439. int known_purpose = 0;
  1440. if (!exit_ei)
  1441. return routelen;
  1442. switch (purpose) {
  1443. /* These two purposes connect to a router that we chose, so
  1444. * DEFAULT_ROUTE_LEN is safe. */
  1445. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1446. /* hidden service connecting to introduction point */
  1447. case CIRCUIT_PURPOSE_TESTING:
  1448. /* router reachability testing */
  1449. known_purpose = 1;
  1450. break;
  1451. /* These three purposes connect to a router that someone else
  1452. * might have chosen, so add an extra hop to protect anonymity. */
  1453. case CIRCUIT_PURPOSE_C_GENERAL:
  1454. /* connecting to hidden service directory */
  1455. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1456. /* client connecting to introduction point */
  1457. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1458. /* hidden service connecting to rendezvous point */
  1459. known_purpose = 1;
  1460. routelen++;
  1461. break;
  1462. default:
  1463. /* Got a purpose not listed above along with a chosen exit.
  1464. * Increase the circuit length by one anyway for safety. */
  1465. routelen++;
  1466. break;
  1467. }
  1468. if (BUG(exit_ei && !known_purpose)) {
  1469. log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
  1470. "assuming routelen %d.", purpose, routelen);
  1471. }
  1472. return routelen;
  1473. }
  1474. /** Choose a length for a circuit of purpose <b>purpose</b> and check
  1475. * if enough routers are available.
  1476. *
  1477. * If the routerlist <b>nodes</b> doesn't have enough routers
  1478. * to handle the desired path length, return -1.
  1479. */
  1480. STATIC int
  1481. new_route_len(uint8_t purpose, extend_info_t *exit_ei, smartlist_t *nodes)
  1482. {
  1483. int num_acceptable_routers;
  1484. int routelen;
  1485. tor_assert(nodes);
  1486. routelen = route_len_for_purpose(purpose, exit_ei);
  1487. num_acceptable_routers = count_acceptable_nodes(nodes);
  1488. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1489. routelen, num_acceptable_routers, smartlist_len(nodes));
  1490. if (num_acceptable_routers < routelen) {
  1491. log_info(LD_CIRC,
  1492. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1493. num_acceptable_routers, routelen);
  1494. return -1;
  1495. }
  1496. return routelen;
  1497. }
  1498. /** Return a newly allocated list of uint16_t * for each predicted port not
  1499. * handled by a current circuit. */
  1500. static smartlist_t *
  1501. circuit_get_unhandled_ports(time_t now)
  1502. {
  1503. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1504. circuit_remove_handled_ports(dest);
  1505. return dest;
  1506. }
  1507. /** Return 1 if we already have circuits present or on the way for
  1508. * all anticipated ports. Return 0 if we should make more.
  1509. *
  1510. * If we're returning 0, set need_uptime and need_capacity to
  1511. * indicate any requirements that the unhandled ports have.
  1512. */
  1513. MOCK_IMPL(int,
  1514. circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
  1515. int *need_capacity))
  1516. {
  1517. int i, enough;
  1518. uint16_t *port;
  1519. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1520. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1521. tor_assert(need_uptime);
  1522. tor_assert(need_capacity);
  1523. // Always predict need_capacity
  1524. *need_capacity = 1;
  1525. enough = (smartlist_len(sl) == 0);
  1526. for (i = 0; i < smartlist_len(sl); ++i) {
  1527. port = smartlist_get(sl, i);
  1528. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1529. *need_uptime = 1;
  1530. tor_free(port);
  1531. }
  1532. smartlist_free(sl);
  1533. return enough;
  1534. }
  1535. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1536. * <b>needed_ports</b>, else return 0.
  1537. */
  1538. static int
  1539. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1540. { /* XXXX MOVE */
  1541. int i;
  1542. uint16_t port;
  1543. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1544. addr_policy_result_t r;
  1545. /* alignment issues aren't a worry for this dereference, since
  1546. needed_ports is explicitly a smartlist of uint16_t's */
  1547. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1548. tor_assert(port);
  1549. if (node)
  1550. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1551. else
  1552. continue;
  1553. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1554. return 1;
  1555. }
  1556. return 0;
  1557. }
  1558. /** Return true iff <b>conn</b> needs another general circuit to be
  1559. * built. */
  1560. static int
  1561. ap_stream_wants_exit_attention(connection_t *conn)
  1562. {
  1563. entry_connection_t *entry;
  1564. if (conn->type != CONN_TYPE_AP)
  1565. return 0;
  1566. entry = TO_ENTRY_CONN(conn);
  1567. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1568. !conn->marked_for_close &&
  1569. !(entry->want_onehop) && /* ignore one-hop streams */
  1570. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1571. !(entry->chosen_exit_name) && /* ignore defined streams */
  1572. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1573. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1574. MIN_CIRCUITS_HANDLING_STREAM))
  1575. return 1;
  1576. return 0;
  1577. }
  1578. /** Return a pointer to a suitable router to be the exit node for the
  1579. * general-purpose circuit we're about to build.
  1580. *
  1581. * Look through the connection array, and choose a router that maximizes
  1582. * the number of pending streams that can exit from this router.
  1583. *
  1584. * Return NULL if we can't find any suitable routers.
  1585. */
  1586. static const node_t *
  1587. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1588. {
  1589. int *n_supported;
  1590. int n_pending_connections = 0;
  1591. smartlist_t *connections;
  1592. int best_support = -1;
  1593. int n_best_support=0;
  1594. const or_options_t *options = get_options();
  1595. const smartlist_t *the_nodes;
  1596. const node_t *selected_node=NULL;
  1597. connections = get_connection_array();
  1598. /* Count how many connections are waiting for a circuit to be built.
  1599. * We use this for log messages now, but in the future we may depend on it.
  1600. */
  1601. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1602. {
  1603. if (ap_stream_wants_exit_attention(conn))
  1604. ++n_pending_connections;
  1605. });
  1606. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1607. // n_pending_connections);
  1608. /* Now we count, for each of the routers in the directory, how many
  1609. * of the pending connections could possibly exit from that
  1610. * router (n_supported[i]). (We can't be sure about cases where we
  1611. * don't know the IP address of the pending connection.)
  1612. *
  1613. * -1 means "Don't use this router at all."
  1614. */
  1615. the_nodes = nodelist_get_list();
  1616. n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
  1617. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1618. const int i = node_sl_idx;
  1619. if (router_digest_is_me(node->identity)) {
  1620. n_supported[i] = -1;
  1621. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1622. /* XXX there's probably a reverse predecessor attack here, but
  1623. * it's slow. should we take this out? -RD
  1624. */
  1625. continue;
  1626. }
  1627. if (!node_has_descriptor(node)) {
  1628. n_supported[i] = -1;
  1629. continue;
  1630. }
  1631. if (!node->is_running || node->is_bad_exit) {
  1632. n_supported[i] = -1;
  1633. continue; /* skip routers that are known to be down or bad exits */
  1634. }
  1635. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1636. /* never pick a non-general node as a random exit. */
  1637. n_supported[i] = -1;
  1638. continue;
  1639. }
  1640. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1641. n_supported[i] = -1;
  1642. continue; /* user asked us not to use it, no matter what */
  1643. }
  1644. if (options->ExitNodes &&
  1645. !routerset_contains_node(options->ExitNodes, node)) {
  1646. n_supported[i] = -1;
  1647. continue; /* not one of our chosen exit nodes */
  1648. }
  1649. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1650. n_supported[i] = -1;
  1651. continue; /* skip routers that are not suitable. Don't worry if
  1652. * this makes us reject all the possible routers: if so,
  1653. * we'll retry later in this function with need_update and
  1654. * need_capacity set to 0. */
  1655. }
  1656. if (!(node->is_valid)) {
  1657. /* if it's invalid and we don't want it */
  1658. n_supported[i] = -1;
  1659. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1660. // router->nickname, i);
  1661. continue; /* skip invalid routers */
  1662. }
  1663. /* We do not allow relays that allow single hop exits by default. Option
  1664. * was deprecated in 0.2.9.2-alpha and removed in 0.3.1.0-alpha. */
  1665. if (node_allows_single_hop_exits(node)) {
  1666. n_supported[i] = -1;
  1667. continue;
  1668. }
  1669. if (node_exit_policy_rejects_all(node)) {
  1670. n_supported[i] = -1;
  1671. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1672. // router->nickname, i);
  1673. continue; /* skip routers that reject all */
  1674. }
  1675. n_supported[i] = 0;
  1676. /* iterate over connections */
  1677. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1678. if (!ap_stream_wants_exit_attention(conn))
  1679. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1680. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1681. ++n_supported[i];
  1682. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1683. // router->nickname, i, n_supported[i]);
  1684. } else {
  1685. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1686. // router->nickname, i);
  1687. }
  1688. } SMARTLIST_FOREACH_END(conn);
  1689. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1690. /* Leave best_support at -1 if that's where it is, so we can
  1691. * distinguish it later. */
  1692. continue;
  1693. }
  1694. if (n_supported[i] > best_support) {
  1695. /* If this router is better than previous ones, remember its index
  1696. * and goodness, and start counting how many routers are this good. */
  1697. best_support = n_supported[i]; n_best_support=1;
  1698. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1699. // router->nickname);
  1700. } else if (n_supported[i] == best_support) {
  1701. /* If this router is _as good_ as the best one, just increment the
  1702. * count of equally good routers.*/
  1703. ++n_best_support;
  1704. }
  1705. } SMARTLIST_FOREACH_END(node);
  1706. log_info(LD_CIRC,
  1707. "Found %d servers that might support %d/%d pending connections.",
  1708. n_best_support, best_support >= 0 ? best_support : 0,
  1709. n_pending_connections);
  1710. /* If any routers definitely support any pending connections, choose one
  1711. * at random. */
  1712. if (best_support > 0) {
  1713. smartlist_t *supporting = smartlist_new();
  1714. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1715. if (n_supported[node_sl_idx] == best_support)
  1716. smartlist_add(supporting, (void*)node);
  1717. });
  1718. selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1719. smartlist_free(supporting);
  1720. } else {
  1721. /* Either there are no pending connections, or no routers even seem to
  1722. * possibly support any of them. Choose a router at random that satisfies
  1723. * at least one predicted exit port. */
  1724. int attempt;
  1725. smartlist_t *needed_ports, *supporting;
  1726. if (best_support == -1) {
  1727. if (need_uptime || need_capacity) {
  1728. log_info(LD_CIRC,
  1729. "We couldn't find any live%s%s routers; falling back "
  1730. "to list of all routers.",
  1731. need_capacity?", fast":"",
  1732. need_uptime?", stable":"");
  1733. tor_free(n_supported);
  1734. return choose_good_exit_server_general(0, 0);
  1735. }
  1736. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1737. "choosing a doomed exit at random.",
  1738. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1739. }
  1740. supporting = smartlist_new();
  1741. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1742. for (attempt = 0; attempt < 2; attempt++) {
  1743. /* try once to pick only from routers that satisfy a needed port,
  1744. * then if there are none, pick from any that support exiting. */
  1745. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1746. if (n_supported[node_sl_idx] != -1 &&
  1747. (attempt || node_handles_some_port(node, needed_ports))) {
  1748. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1749. // try, router->nickname);
  1750. smartlist_add(supporting, (void*)node);
  1751. }
  1752. } SMARTLIST_FOREACH_END(node);
  1753. selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1754. if (selected_node)
  1755. break;
  1756. smartlist_clear(supporting);
  1757. /* If we reach this point, we can't actually support any unhandled
  1758. * predicted ports, so clear all the remaining ones. */
  1759. if (smartlist_len(needed_ports))
  1760. rep_hist_remove_predicted_ports(needed_ports);
  1761. }
  1762. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1763. smartlist_free(needed_ports);
  1764. smartlist_free(supporting);
  1765. }
  1766. tor_free(n_supported);
  1767. if (selected_node) {
  1768. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
  1769. return selected_node;
  1770. }
  1771. if (options->ExitNodes) {
  1772. log_warn(LD_CIRC,
  1773. "No specified %sexit routers seem to be running: "
  1774. "can't choose an exit.",
  1775. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1776. }
  1777. return NULL;
  1778. }
  1779. #if defined(ENABLE_TOR2WEB_MODE) || defined(TOR_UNIT_TESTS)
  1780. /* The config option Tor2webRendezvousPoints has been set and we need
  1781. * to pick an RP out of that set. Make sure that the RP we choose is
  1782. * alive, and return it. Return NULL if no usable RP could be found in
  1783. * Tor2webRendezvousPoints. */
  1784. STATIC const node_t *
  1785. pick_tor2web_rendezvous_node(router_crn_flags_t flags,
  1786. const or_options_t *options)
  1787. {
  1788. const node_t *rp_node = NULL;
  1789. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  1790. const int pref_addr = (flags & CRN_PREF_ADDR) != 0;
  1791. const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
  1792. smartlist_t *whitelisted_live_rps = smartlist_new();
  1793. smartlist_t *all_live_nodes = smartlist_new();
  1794. tor_assert(options->Tor2webRendezvousPoints);
  1795. /* Add all running nodes to all_live_nodes */
  1796. router_add_running_nodes_to_smartlist(all_live_nodes,
  1797. 0, 0, 0,
  1798. need_desc,
  1799. pref_addr,
  1800. direct_conn);
  1801. /* Filter all_live_nodes to only add live *and* whitelisted RPs to
  1802. * the list whitelisted_live_rps. */
  1803. SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
  1804. if (routerset_contains_node(options->Tor2webRendezvousPoints, live_node)) {
  1805. smartlist_add(whitelisted_live_rps, live_node);
  1806. }
  1807. } SMARTLIST_FOREACH_END(live_node);
  1808. /* Honor ExcludeNodes */
  1809. if (options->ExcludeNodes) {
  1810. routerset_subtract_nodes(whitelisted_live_rps, options->ExcludeNodes);
  1811. }
  1812. /* Now pick randomly amongst the whitelisted RPs. No need to waste time
  1813. doing bandwidth load balancing, for most use cases
  1814. 'whitelisted_live_rps' contains a single OR anyway. */
  1815. rp_node = smartlist_choose(whitelisted_live_rps);
  1816. if (!rp_node) {
  1817. log_warn(LD_REND, "Could not find a Rendezvous Point that suits "
  1818. "the purposes of Tor2webRendezvousPoints. Choosing random one.");
  1819. }
  1820. smartlist_free(whitelisted_live_rps);
  1821. smartlist_free(all_live_nodes);
  1822. return rp_node;
  1823. }
  1824. #endif
  1825. /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
  1826. static const node_t *
  1827. pick_rendezvous_node(router_crn_flags_t flags)
  1828. {
  1829. const or_options_t *options = get_options();
  1830. #ifdef ENABLE_TOR2WEB_MODE
  1831. /* We want to connect directly to the node if we can */
  1832. router_crn_flags_t direct_flags = flags;
  1833. direct_flags |= CRN_PREF_ADDR;
  1834. direct_flags |= CRN_DIRECT_CONN;
  1835. /* The user wants us to pick specific RPs. */
  1836. if (options->Tor2webRendezvousPoints) {
  1837. const node_t *tor2web_rp = pick_tor2web_rendezvous_node(direct_flags,
  1838. options);
  1839. if (tor2web_rp) {
  1840. return tor2web_rp;
  1841. }
  1842. }
  1843. /* Else, if no direct, preferred tor2web RP was found, fall back to choosing
  1844. * a random direct node */
  1845. const node_t *node = router_choose_random_node(NULL, options->ExcludeNodes,
  1846. direct_flags);
  1847. /* Return the direct node (if found), or log a message and fall back to an
  1848. * indirect connection. */
  1849. if (node) {
  1850. return node;
  1851. } else {
  1852. log_info(LD_REND,
  1853. "Unable to find a random rendezvous point that is reachable via "
  1854. "a direct connection, falling back to a 3-hop path.");
  1855. }
  1856. #endif
  1857. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1858. }
  1859. /** Return a pointer to a suitable router to be the exit node for the
  1860. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1861. * if no router is suitable).
  1862. *
  1863. * For general-purpose circuits, pass it off to
  1864. * choose_good_exit_server_general()
  1865. *
  1866. * For client-side rendezvous circuits, choose a random node, weighted
  1867. * toward the preferences in 'options'.
  1868. */
  1869. static const node_t *
  1870. choose_good_exit_server(uint8_t purpose,
  1871. int need_uptime, int need_capacity, int is_internal)
  1872. {
  1873. const or_options_t *options = get_options();
  1874. router_crn_flags_t flags = CRN_NEED_DESC;
  1875. if (need_uptime)
  1876. flags |= CRN_NEED_UPTIME;
  1877. if (need_capacity)
  1878. flags |= CRN_NEED_CAPACITY;
  1879. switch (purpose) {
  1880. case CIRCUIT_PURPOSE_C_GENERAL:
  1881. if (is_internal) /* pick it like a middle hop */
  1882. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1883. else
  1884. return choose_good_exit_server_general(need_uptime,need_capacity);
  1885. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1886. {
  1887. /* Pick a new RP */
  1888. const node_t *rendezvous_node = pick_rendezvous_node(flags);
  1889. log_info(LD_REND, "Picked new RP: %s",
  1890. safe_str_client(node_describe(rendezvous_node)));
  1891. return rendezvous_node;
  1892. }
  1893. }
  1894. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1895. tor_fragile_assert();
  1896. return NULL;
  1897. }
  1898. /** Log a warning if the user specified an exit for the circuit that
  1899. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1900. static void
  1901. warn_if_last_router_excluded(origin_circuit_t *circ,
  1902. const extend_info_t *exit_ei)
  1903. {
  1904. const or_options_t *options = get_options();
  1905. routerset_t *rs = options->ExcludeNodes;
  1906. const char *description;
  1907. uint8_t purpose = circ->base_.purpose;
  1908. if (circ->build_state->onehop_tunnel)
  1909. return;
  1910. switch (purpose)
  1911. {
  1912. default:
  1913. case CIRCUIT_PURPOSE_OR:
  1914. case CIRCUIT_PURPOSE_INTRO_POINT:
  1915. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1916. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1917. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1918. (int)purpose,
  1919. circuit_purpose_to_string(purpose));
  1920. return;
  1921. case CIRCUIT_PURPOSE_C_GENERAL:
  1922. if (circ->build_state->is_internal)
  1923. return;
  1924. description = "requested exit node";
  1925. rs = options->ExcludeExitNodesUnion_;
  1926. break;
  1927. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1928. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1929. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1930. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1931. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1932. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1933. case CIRCUIT_PURPOSE_TESTING:
  1934. return;
  1935. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1936. case CIRCUIT_PURPOSE_C_REND_READY:
  1937. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1938. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1939. description = "chosen rendezvous point";
  1940. break;
  1941. case CIRCUIT_PURPOSE_CONTROLLER:
  1942. rs = options->ExcludeExitNodesUnion_;
  1943. description = "controller-selected circuit target";
  1944. break;
  1945. }
  1946. if (routerset_contains_extendinfo(rs, exit_ei)) {
  1947. /* We should never get here if StrictNodes is set to 1. */
  1948. if (options->StrictNodes) {
  1949. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1950. "even though StrictNodes is set. Please report. "
  1951. "(Circuit purpose: %s)",
  1952. description, extend_info_describe(exit_ei),
  1953. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1954. circuit_purpose_to_string(purpose));
  1955. } else {
  1956. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1957. "ExcludeNodes%s, because no better options were available. To "
  1958. "prevent this (and possibly break your Tor functionality), "
  1959. "set the StrictNodes configuration option. "
  1960. "(Circuit purpose: %s)",
  1961. description, extend_info_describe(exit_ei),
  1962. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1963. circuit_purpose_to_string(purpose));
  1964. }
  1965. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1966. }
  1967. return;
  1968. }
  1969. /** Decide a suitable length for circ's cpath, and pick an exit
  1970. * router (or use <b>exit</b> if provided). Store these in the
  1971. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1972. static int
  1973. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
  1974. {
  1975. cpath_build_state_t *state = circ->build_state;
  1976. if (state->onehop_tunnel) {
  1977. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
  1978. (rend_allow_non_anonymous_connection(get_options()) ?
  1979. ", or intro or rendezvous connection" : ""));
  1980. state->desired_path_len = 1;
  1981. } else {
  1982. int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
  1983. if (r < 1) /* must be at least 1 */
  1984. return -1;
  1985. state->desired_path_len = r;
  1986. }
  1987. if (exit_ei) { /* the circuit-builder pre-requested one */
  1988. warn_if_last_router_excluded(circ, exit_ei);
  1989. log_info(LD_CIRC,"Using requested exit node '%s'",
  1990. extend_info_describe(exit_ei));
  1991. exit_ei = extend_info_dup(exit_ei);
  1992. } else { /* we have to decide one */
  1993. const node_t *node =
  1994. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1995. state->need_capacity, state->is_internal);
  1996. if (!node) {
  1997. log_warn(LD_CIRC,"Failed to choose an exit server");
  1998. return -1;
  1999. }
  2000. exit_ei = extend_info_from_node(node, 0);
  2001. if (BUG(exit_ei == NULL))
  2002. return -1;
  2003. }
  2004. state->chosen_exit = exit_ei;
  2005. return 0;
  2006. }
  2007. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2008. * hop to the cpath reflecting this. Don't send the next extend cell --
  2009. * the caller will do this if it wants to.
  2010. */
  2011. int
  2012. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
  2013. {
  2014. cpath_build_state_t *state;
  2015. tor_assert(exit_ei);
  2016. tor_assert(circ);
  2017. state = circ->build_state;
  2018. tor_assert(state);
  2019. extend_info_free(state->chosen_exit);
  2020. state->chosen_exit = extend_info_dup(exit_ei);
  2021. ++circ->build_state->desired_path_len;
  2022. onion_append_hop(&circ->cpath, exit_ei);
  2023. return 0;
  2024. }
  2025. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2026. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2027. * send the next extend cell to begin connecting to that hop.
  2028. */
  2029. int
  2030. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
  2031. {
  2032. int err_reason = 0;
  2033. warn_if_last_router_excluded(circ, exit_ei);
  2034. tor_gettimeofday(&circ->base_.timestamp_began);
  2035. circuit_append_new_exit(circ, exit_ei);
  2036. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2037. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2038. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2039. extend_info_describe(exit_ei));
  2040. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2041. return -1;
  2042. }
  2043. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  2044. return 0;
  2045. }
  2046. /** Return the number of routers in <b>routers</b> that are currently up
  2047. * and available for building circuits through.
  2048. */
  2049. MOCK_IMPL(STATIC int,
  2050. count_acceptable_nodes, (smartlist_t *nodes))
  2051. {
  2052. int num=0;
  2053. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2054. // log_debug(LD_CIRC,
  2055. // "Contemplating whether router %d (%s) is a new option.",
  2056. // i, r->nickname);
  2057. if (! node->is_running)
  2058. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2059. continue;
  2060. if (! node->is_valid)
  2061. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2062. continue;
  2063. if (! node_has_descriptor(node))
  2064. continue;
  2065. /* The node has a descriptor, so we can just check the ntor key directly */
  2066. if (!node_has_curve25519_onion_key(node))
  2067. continue;
  2068. ++num;
  2069. } SMARTLIST_FOREACH_END(node);
  2070. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2071. return num;
  2072. }
  2073. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2074. * This function is used to extend cpath by another hop.
  2075. */
  2076. void
  2077. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2078. {
  2079. if (*head_ptr) {
  2080. new_hop->next = (*head_ptr);
  2081. new_hop->prev = (*head_ptr)->prev;
  2082. (*head_ptr)->prev->next = new_hop;
  2083. (*head_ptr)->prev = new_hop;
  2084. } else {
  2085. *head_ptr = new_hop;
  2086. new_hop->prev = new_hop->next = new_hop;
  2087. }
  2088. }
  2089. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2090. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2091. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2092. * circuit. In particular, make sure we don't pick the exit node or its
  2093. * family, and make sure we don't duplicate any previous nodes or their
  2094. * families. */
  2095. static const node_t *
  2096. choose_good_middle_server(uint8_t purpose,
  2097. cpath_build_state_t *state,
  2098. crypt_path_t *head,
  2099. int cur_len)
  2100. {
  2101. int i;
  2102. const node_t *r, *choice;
  2103. crypt_path_t *cpath;
  2104. smartlist_t *excluded;
  2105. const or_options_t *options = get_options();
  2106. router_crn_flags_t flags = CRN_NEED_DESC;
  2107. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2108. purpose <= CIRCUIT_PURPOSE_MAX_);
  2109. log_debug(LD_CIRC, "Contemplating intermediate hop %d: random choice.",
  2110. cur_len);
  2111. excluded = smartlist_new();
  2112. if ((r = build_state_get_exit_node(state))) {
  2113. nodelist_add_node_and_family(excluded, r);
  2114. }
  2115. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2116. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2117. nodelist_add_node_and_family(excluded, r);
  2118. }
  2119. }
  2120. if (state->need_uptime)
  2121. flags |= CRN_NEED_UPTIME;
  2122. if (state->need_capacity)
  2123. flags |= CRN_NEED_CAPACITY;
  2124. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2125. smartlist_free(excluded);
  2126. return choice;
  2127. }
  2128. /** Pick a good entry server for the circuit to be built according to
  2129. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2130. * router (if we're an OR), and respect firewall settings; if we're
  2131. * configured to use entry guards, return one.
  2132. *
  2133. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2134. * guard, not for any particular circuit.
  2135. *
  2136. * Set *<b>guard_state_out</b> to information about the guard that
  2137. * we're selecting, which we'll use later to remember whether the
  2138. * guard worked or not.
  2139. */
  2140. const node_t *
  2141. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state,
  2142. circuit_guard_state_t **guard_state_out)
  2143. {
  2144. const node_t *choice;
  2145. smartlist_t *excluded;
  2146. const or_options_t *options = get_options();
  2147. /* If possible, choose an entry server with a preferred address,
  2148. * otherwise, choose one with an allowed address */
  2149. router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
  2150. CRN_DIRECT_CONN);
  2151. const node_t *node;
  2152. if (state && options->UseEntryGuards &&
  2153. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2154. /* This request is for an entry server to use for a regular circuit,
  2155. * and we use entry guard nodes. Just return one of the guard nodes. */
  2156. tor_assert(guard_state_out);
  2157. return guards_choose_guard(state, guard_state_out);
  2158. }
  2159. excluded = smartlist_new();
  2160. if (state && (node = build_state_get_exit_node(state))) {
  2161. /* Exclude the exit node from the state, if we have one. Also exclude its
  2162. * family. */
  2163. nodelist_add_node_and_family(excluded, node);
  2164. }
  2165. if (state) {
  2166. if (state->need_uptime)
  2167. flags |= CRN_NEED_UPTIME;
  2168. if (state->need_capacity)
  2169. flags |= CRN_NEED_CAPACITY;
  2170. }
  2171. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2172. smartlist_free(excluded);
  2173. return choice;
  2174. }
  2175. /** Return the first non-open hop in cpath, or return NULL if all
  2176. * hops are open. */
  2177. static crypt_path_t *
  2178. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2179. {
  2180. crypt_path_t *hop = cpath;
  2181. do {
  2182. if (hop->state != CPATH_STATE_OPEN)
  2183. return hop;
  2184. hop = hop->next;
  2185. } while (hop != cpath);
  2186. return NULL;
  2187. }
  2188. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2189. * based on <b>state</b>. Append the hop info to head_ptr.
  2190. *
  2191. * Return 1 if the path is complete, 0 if we successfully added a hop,
  2192. * and -1 on error.
  2193. */
  2194. static int
  2195. onion_extend_cpath(origin_circuit_t *circ)
  2196. {
  2197. uint8_t purpose = circ->base_.purpose;
  2198. cpath_build_state_t *state = circ->build_state;
  2199. int cur_len = circuit_get_cpath_len(circ);
  2200. extend_info_t *info = NULL;
  2201. if (cur_len >= state->desired_path_len) {
  2202. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2203. state->desired_path_len);
  2204. return 1;
  2205. }
  2206. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2207. state->desired_path_len);
  2208. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2209. info = extend_info_dup(state->chosen_exit);
  2210. } else if (cur_len == 0) { /* picking first node */
  2211. const node_t *r = choose_good_entry_server(purpose, state,
  2212. &circ->guard_state);
  2213. if (r) {
  2214. /* If we're a client, use the preferred address rather than the
  2215. primary address, for potentially connecting to an IPv6 OR
  2216. port. Servers always want the primary (IPv4) address. */
  2217. int client = (server_mode(get_options()) == 0);
  2218. info = extend_info_from_node(r, client);
  2219. /* Clients can fail to find an allowed address */
  2220. tor_assert_nonfatal(info || client);
  2221. }
  2222. } else {
  2223. const node_t *r =
  2224. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2225. if (r) {
  2226. info = extend_info_from_node(r, 0);
  2227. tor_assert_nonfatal(info);
  2228. }
  2229. }
  2230. if (!info) {
  2231. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2232. "this circuit.", cur_len);
  2233. return -1;
  2234. }
  2235. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2236. extend_info_describe(info),
  2237. cur_len+1, build_state_get_exit_nickname(state));
  2238. onion_append_hop(&circ->cpath, info);
  2239. extend_info_free(info);
  2240. return 0;
  2241. }
  2242. /** Create a new hop, annotate it with information about its
  2243. * corresponding router <b>choice</b>, and append it to the
  2244. * end of the cpath <b>head_ptr</b>. */
  2245. static int
  2246. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2247. {
  2248. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2249. /* link hop into the cpath, at the end. */
  2250. onion_append_to_cpath(head_ptr, hop);
  2251. hop->magic = CRYPT_PATH_MAGIC;
  2252. hop->state = CPATH_STATE_CLOSED;
  2253. hop->extend_info = extend_info_dup(choice);
  2254. hop->package_window = circuit_initial_package_window();
  2255. hop->deliver_window = CIRCWINDOW_START;
  2256. return 0;
  2257. }
  2258. /** Allocate a new extend_info object based on the various arguments. */
  2259. extend_info_t *
  2260. extend_info_new(const char *nickname,
  2261. const char *rsa_id_digest,
  2262. const ed25519_public_key_t *ed_id,
  2263. crypto_pk_t *onion_key,
  2264. const curve25519_public_key_t *ntor_key,
  2265. const tor_addr_t *addr, uint16_t port)
  2266. {
  2267. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2268. memcpy(info->identity_digest, rsa_id_digest, DIGEST_LEN);
  2269. if (ed_id && !ed25519_public_key_is_zero(ed_id))
  2270. memcpy(&info->ed_identity, ed_id, sizeof(ed25519_public_key_t));
  2271. if (nickname)
  2272. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2273. if (onion_key)
  2274. info->onion_key = crypto_pk_dup_key(onion_key);
  2275. if (ntor_key)
  2276. memcpy(&info->curve25519_onion_key, ntor_key,
  2277. sizeof(curve25519_public_key_t));
  2278. tor_addr_copy(&info->addr, addr);
  2279. info->port = port;
  2280. return info;
  2281. }
  2282. /** Allocate and return a new extend_info that can be used to build a
  2283. * circuit to or through the node <b>node</b>. Use the primary address
  2284. * of the node (i.e. its IPv4 address) unless
  2285. * <b>for_direct_connect</b> is true, in which case the preferred
  2286. * address is used instead. May return NULL if there is not enough
  2287. * info about <b>node</b> to extend to it--for example, if there is no
  2288. * routerinfo_t or microdesc_t, or if for_direct_connect is true and none of
  2289. * the node's addresses are allowed by tor's firewall and IP version config.
  2290. **/
  2291. extend_info_t *
  2292. extend_info_from_node(const node_t *node, int for_direct_connect)
  2293. {
  2294. tor_addr_port_t ap;
  2295. int valid_addr = 0;
  2296. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2297. return NULL;
  2298. /* Choose a preferred address first, but fall back to an allowed address.
  2299. * choose_address returns 1 on success, but get_prim_orport returns 0. */
  2300. if (for_direct_connect)
  2301. valid_addr = fascist_firewall_choose_address_node(node,
  2302. FIREWALL_OR_CONNECTION,
  2303. 0, &ap);
  2304. else
  2305. valid_addr = !node_get_prim_orport(node, &ap);
  2306. if (valid_addr)
  2307. log_debug(LD_CIRC, "using %s for %s",
  2308. fmt_addrport(&ap.addr, ap.port),
  2309. node->ri ? node->ri->nickname : node->rs->nickname);
  2310. else
  2311. log_warn(LD_CIRC, "Could not choose valid address for %s",
  2312. node->ri ? node->ri->nickname : node->rs->nickname);
  2313. /* Every node we connect or extend to must support ntor */
  2314. if (!node_has_curve25519_onion_key(node)) {
  2315. log_fn(LOG_PROTOCOL_WARN, LD_CIRC,
  2316. "Attempted to create extend_info for a node that does not support "
  2317. "ntor: %s", node_describe(node));
  2318. return NULL;
  2319. }
  2320. const ed25519_public_key_t *ed_pubkey = NULL;
  2321. /* Don't send the ed25519 pubkey unless the target node actually supports
  2322. * authenticating with it. */
  2323. if (node_supports_ed25519_link_authentication(node)) {
  2324. log_info(LD_CIRC, "Including Ed25519 ID for %s", node_describe(node));
  2325. ed_pubkey = node_get_ed25519_id(node);
  2326. } else if (node_get_ed25519_id(node)) {
  2327. log_info(LD_CIRC, "Not including the ed25519 ID for %s, since it won't "
  2328. " be able to authenticate it.",
  2329. node_describe(node));
  2330. }
  2331. if (valid_addr && node->ri)
  2332. return extend_info_new(node->ri->nickname,
  2333. node->identity,
  2334. ed_pubkey,
  2335. node->ri->onion_pkey,
  2336. node->ri->onion_curve25519_pkey,
  2337. &ap.addr,
  2338. ap.port);
  2339. else if (valid_addr && node->rs && node->md)
  2340. return extend_info_new(node->rs->nickname,
  2341. node->identity,
  2342. ed_pubkey,
  2343. node->md->onion_pkey,
  2344. node->md->onion_curve25519_pkey,
  2345. &ap.addr,
  2346. ap.port);
  2347. else
  2348. return NULL;
  2349. }
  2350. /** Release storage held by an extend_info_t struct. */
  2351. void
  2352. extend_info_free(extend_info_t *info)
  2353. {
  2354. if (!info)
  2355. return;
  2356. crypto_pk_free(info->onion_key);
  2357. tor_free(info);
  2358. }
  2359. /** Allocate and return a new extend_info_t with the same contents as
  2360. * <b>info</b>. */
  2361. extend_info_t *
  2362. extend_info_dup(extend_info_t *info)
  2363. {
  2364. extend_info_t *newinfo;
  2365. tor_assert(info);
  2366. newinfo = tor_malloc(sizeof(extend_info_t));
  2367. memcpy(newinfo, info, sizeof(extend_info_t));
  2368. if (info->onion_key)
  2369. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2370. else
  2371. newinfo->onion_key = NULL;
  2372. return newinfo;
  2373. }
  2374. /** Return the node_t for the chosen exit router in <b>state</b>.
  2375. * If there is no chosen exit, or if we don't know the node_t for
  2376. * the chosen exit, return NULL.
  2377. */
  2378. const node_t *
  2379. build_state_get_exit_node(cpath_build_state_t *state)
  2380. {
  2381. if (!state || !state->chosen_exit)
  2382. return NULL;
  2383. return node_get_by_id(state->chosen_exit->identity_digest);
  2384. }
  2385. /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
  2386. * If there is no chosen exit, return NULL.
  2387. */
  2388. const uint8_t *
  2389. build_state_get_exit_rsa_id(cpath_build_state_t *state)
  2390. {
  2391. if (!state || !state->chosen_exit)
  2392. return NULL;
  2393. return (const uint8_t *) state->chosen_exit->identity_digest;
  2394. }
  2395. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2396. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2397. * chosen exit, return NULL.
  2398. */
  2399. const char *
  2400. build_state_get_exit_nickname(cpath_build_state_t *state)
  2401. {
  2402. if (!state || !state->chosen_exit)
  2403. return NULL;
  2404. return state->chosen_exit->nickname;
  2405. }
  2406. /** Return true iff the given address can be used to extend to. */
  2407. int
  2408. extend_info_addr_is_allowed(const tor_addr_t *addr)
  2409. {
  2410. tor_assert(addr);
  2411. /* Check if we have a private address and if we can extend to it. */
  2412. if ((tor_addr_is_internal(addr, 0) || tor_addr_is_multicast(addr)) &&
  2413. !get_options()->ExtendAllowPrivateAddresses) {
  2414. goto disallow;
  2415. }
  2416. /* Allowed! */
  2417. return 1;
  2418. disallow:
  2419. return 0;
  2420. }
  2421. /* Does ei have a valid TAP key? */
  2422. int
  2423. extend_info_supports_tap(const extend_info_t* ei)
  2424. {
  2425. tor_assert(ei);
  2426. /* Valid TAP keys are not NULL */
  2427. return ei->onion_key != NULL;
  2428. }
  2429. /* Does ei have a valid ntor key? */
  2430. int
  2431. extend_info_supports_ntor(const extend_info_t* ei)
  2432. {
  2433. tor_assert(ei);
  2434. /* Valid ntor keys have at least one non-zero byte */
  2435. return !tor_mem_is_zero(
  2436. (const char*)ei->curve25519_onion_key.public_key,
  2437. CURVE25519_PUBKEY_LEN);
  2438. }
  2439. /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
  2440. * The hidden service protocol still uses TAP for some connections, because
  2441. * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
  2442. static int
  2443. circuit_purpose_can_use_tap_impl(uint8_t purpose)
  2444. {
  2445. return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  2446. purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  2447. }
  2448. /* Is circ allowed to use the deprecated TAP encryption protocol?
  2449. * The hidden service protocol still uses TAP for some connections, because
  2450. * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
  2451. int
  2452. circuit_can_use_tap(const origin_circuit_t *circ)
  2453. {
  2454. tor_assert(circ);
  2455. tor_assert(circ->cpath);
  2456. tor_assert(circ->cpath->extend_info);
  2457. return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
  2458. extend_info_supports_tap(circ->cpath->extend_info));
  2459. }
  2460. /* Does circ have an onion key which it's allowed to use? */
  2461. int
  2462. circuit_has_usable_onion_key(const origin_circuit_t *circ)
  2463. {
  2464. tor_assert(circ);
  2465. tor_assert(circ->cpath);
  2466. tor_assert(circ->cpath->extend_info);
  2467. return (extend_info_supports_ntor(circ->cpath->extend_info) ||
  2468. circuit_can_use_tap(circ));
  2469. }
  2470. /* Does ei have an onion key which it would prefer to use?
  2471. * Currently, we prefer ntor keys*/
  2472. int
  2473. extend_info_has_preferred_onion_key(const extend_info_t* ei)
  2474. {
  2475. tor_assert(ei);
  2476. return extend_info_supports_ntor(ei);
  2477. }
  2478. /** Find the circuits that are waiting to find out whether their guards are
  2479. * usable, and if any are ready to become usable, mark them open and try
  2480. * attaching streams as appropriate. */
  2481. void
  2482. circuit_upgrade_circuits_from_guard_wait(void)
  2483. {
  2484. smartlist_t *to_upgrade =
  2485. circuit_find_circuits_to_upgrade_from_guard_wait();
  2486. if (to_upgrade == NULL)
  2487. return;
  2488. log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
  2489. "to 'open'.", smartlist_len(to_upgrade));
  2490. SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
  2491. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2492. circuit_has_opened(circ);
  2493. } SMARTLIST_FOREACH_END(circ);
  2494. smartlist_free(to_upgrade);
  2495. }