circuitbuild.c 97 KB

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