circuitbuild.c 107 KB

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