circuitbuild.c 91 KB

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