circuitbuild.c 99 KB

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