circuitbuild.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  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-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #include "or.h"
  11. #include "channel.h"
  12. #include "circpathbias.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "circuitstats.h"
  16. #include "circuituse.h"
  17. #include "command.h"
  18. #include "config.h"
  19. #include "confparse.h"
  20. #include "connection.h"
  21. #include "connection_edge.h"
  22. #include "connection_or.h"
  23. #include "control.h"
  24. #include "directory.h"
  25. #include "entrynodes.h"
  26. #include "main.h"
  27. #include "microdesc.h"
  28. #include "networkstatus.h"
  29. #include "nodelist.h"
  30. #include "onion.h"
  31. #include "onion_tap.h"
  32. #include "onion_fast.h"
  33. #include "policies.h"
  34. #include "transports.h"
  35. #include "relay.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #include "routerset.h"
  41. #include "crypto.h"
  42. #include "connection_edge.h"
  43. #ifndef MIN
  44. #define MIN(a,b) ((a)<(b)?(a):(b))
  45. #endif
  46. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  47. uint16_t port,
  48. const char *id_digest);
  49. static int circuit_deliver_create_cell(circuit_t *circ,
  50. const create_cell_t *create_cell,
  51. int relayed);
  52. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  53. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  54. static int onion_extend_cpath(origin_circuit_t *circ);
  55. static int count_acceptable_nodes(smartlist_t *routers);
  56. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  57. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  58. /** This function tries to get a channel to the specified endpoint,
  59. * and then calls command_setup_channel() to give it the right
  60. * callbacks.
  61. */
  62. static channel_t *
  63. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  64. const char *id_digest)
  65. {
  66. channel_t *chan;
  67. chan = channel_connect(addr, port, id_digest);
  68. if (chan) command_setup_channel(chan);
  69. return chan;
  70. }
  71. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  72. * and with the high bit specified by conn-\>circ_id_type, until we get
  73. * a circ_id that is not in use by any other circuit on that conn.
  74. *
  75. * Return it, or 0 if can't get a unique circ_id.
  76. */
  77. static circid_t
  78. get_unique_circ_id_by_chan(channel_t *chan)
  79. {
  80. circid_t test_circ_id;
  81. circid_t attempts=0;
  82. circid_t high_bit, max_range;
  83. tor_assert(chan);
  84. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  85. log_warn(LD_BUG,
  86. "Trying to pick a circuit ID for a connection from "
  87. "a client with no identity.");
  88. return 0;
  89. }
  90. max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
  91. high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
  92. do {
  93. /* Sequentially iterate over test_circ_id=1...max_range until we find a
  94. * circID such that (high_bit|test_circ_id) is not already used. */
  95. test_circ_id = chan->next_circ_id++;
  96. if (test_circ_id == 0 || test_circ_id >= max_range) {
  97. test_circ_id = 1;
  98. chan->next_circ_id = 2;
  99. }
  100. if (++attempts > max_range) {
  101. /* Make sure we don't loop forever if all circ_id's are used. This
  102. * matters because it's an external DoS opportunity.
  103. */
  104. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  105. return 0;
  106. }
  107. test_circ_id |= high_bit;
  108. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  109. return test_circ_id;
  110. }
  111. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  112. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  113. * list information about link status in a more verbose format using spaces.
  114. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  115. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  116. * names.
  117. */
  118. static char *
  119. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  120. {
  121. crypt_path_t *hop;
  122. smartlist_t *elements;
  123. const char *states[] = {"closed", "waiting for keys", "open"};
  124. char *s;
  125. elements = smartlist_new();
  126. if (verbose) {
  127. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  128. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  129. circ->build_state->is_internal ? "internal" : "exit",
  130. circ->build_state->need_uptime ? " (high-uptime)" : "",
  131. circ->build_state->desired_path_len,
  132. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  133. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  134. (nickname?nickname:"*unnamed*"));
  135. }
  136. hop = circ->cpath;
  137. do {
  138. char *elt;
  139. const char *id;
  140. const node_t *node;
  141. if (!hop)
  142. break;
  143. if (!verbose && hop->state != CPATH_STATE_OPEN)
  144. break;
  145. if (!hop->extend_info)
  146. break;
  147. id = hop->extend_info->identity_digest;
  148. if (verbose_names) {
  149. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  150. if ((node = node_get_by_id(id))) {
  151. node_get_verbose_nickname(node, elt);
  152. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  153. elt[0] = '$';
  154. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  155. elt[HEX_DIGEST_LEN+1]= '~';
  156. strlcpy(elt+HEX_DIGEST_LEN+2,
  157. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  158. } else {
  159. elt[0] = '$';
  160. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  161. }
  162. } else { /* ! verbose_names */
  163. node = node_get_by_id(id);
  164. if (node && node_is_named(node)) {
  165. elt = tor_strdup(node_get_nickname(node));
  166. } else {
  167. elt = tor_malloc(HEX_DIGEST_LEN+2);
  168. elt[0] = '$';
  169. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  170. }
  171. }
  172. tor_assert(elt);
  173. if (verbose) {
  174. tor_assert(hop->state <= 2);
  175. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  176. tor_free(elt);
  177. } else {
  178. smartlist_add(elements, elt);
  179. }
  180. hop = hop->next;
  181. } while (hop != circ->cpath);
  182. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  183. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  184. smartlist_free(elements);
  185. return s;
  186. }
  187. /** If <b>verbose</b> is false, allocate and return a comma-separated
  188. * list of the currently built elements of <b>circ</b>. If
  189. * <b>verbose</b> is true, also list information about link status in
  190. * a more verbose format using spaces.
  191. */
  192. char *
  193. circuit_list_path(origin_circuit_t *circ, int verbose)
  194. {
  195. return circuit_list_path_impl(circ, verbose, 0);
  196. }
  197. /** Allocate and return a comma-separated list of the currently built elements
  198. * of <b>circ</b>, giving each as a verbose nickname.
  199. */
  200. char *
  201. circuit_list_path_for_controller(origin_circuit_t *circ)
  202. {
  203. return circuit_list_path_impl(circ, 0, 1);
  204. }
  205. /** Log, at severity <b>severity</b>, the nicknames of each router in
  206. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  207. * exit point.
  208. */
  209. void
  210. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  211. {
  212. char *s = circuit_list_path(circ,1);
  213. tor_log(severity,domain,"%s",s);
  214. tor_free(s);
  215. }
  216. /** Tell the rep(utation)hist(ory) module about the status of the links
  217. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  218. * extended; the _first_ hop that isn't open (if any) is marked as
  219. * unable to extend.
  220. */
  221. /* XXXX Someday we should learn from OR circuits too. */
  222. void
  223. circuit_rep_hist_note_result(origin_circuit_t *circ)
  224. {
  225. crypt_path_t *hop;
  226. const char *prev_digest = NULL;
  227. hop = circ->cpath;
  228. if (!hop) /* circuit hasn't started building yet. */
  229. return;
  230. if (server_mode(get_options())) {
  231. const routerinfo_t *me = router_get_my_routerinfo();
  232. if (!me)
  233. return;
  234. prev_digest = me->cache_info.identity_digest;
  235. }
  236. do {
  237. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  238. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  239. if (prev_digest) {
  240. if (hop->state == CPATH_STATE_OPEN)
  241. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  242. else {
  243. rep_hist_note_extend_failed(prev_digest, node->identity);
  244. break;
  245. }
  246. }
  247. prev_digest = node->identity;
  248. } else {
  249. prev_digest = NULL;
  250. }
  251. hop=hop->next;
  252. } while (hop!=circ->cpath);
  253. }
  254. /** Pick all the entries in our cpath. Stop and return 0 when we're
  255. * happy, or return -1 if an error occurs. */
  256. static int
  257. onion_populate_cpath(origin_circuit_t *circ)
  258. {
  259. int r;
  260. again:
  261. r = onion_extend_cpath(circ);
  262. if (r < 0) {
  263. log_info(LD_CIRC,"Generating cpath hop failed.");
  264. return -1;
  265. }
  266. if (r == 0)
  267. goto again;
  268. return 0; /* if r == 1 */
  269. }
  270. /** Create and return a new origin circuit. Initialize its purpose and
  271. * build-state based on our arguments. The <b>flags</b> argument is a
  272. * bitfield of CIRCLAUNCH_* flags. */
  273. origin_circuit_t *
  274. origin_circuit_init(uint8_t purpose, int flags)
  275. {
  276. /* sets circ->p_circ_id and circ->p_chan */
  277. origin_circuit_t *circ = origin_circuit_new();
  278. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  279. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  280. circ->build_state->onehop_tunnel =
  281. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  282. circ->build_state->need_uptime =
  283. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  284. circ->build_state->need_capacity =
  285. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  286. circ->build_state->is_internal =
  287. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  288. circ->base_.purpose = purpose;
  289. return circ;
  290. }
  291. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  292. * is defined, then use that as your exit router, else choose a suitable
  293. * exit node.
  294. *
  295. * Also launch a connection to the first OR in the chosen path, if
  296. * it's not open already.
  297. */
  298. origin_circuit_t *
  299. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  300. {
  301. origin_circuit_t *circ;
  302. int err_reason = 0;
  303. circ = origin_circuit_init(purpose, flags);
  304. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  305. onion_populate_cpath(circ) < 0) {
  306. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  307. return NULL;
  308. }
  309. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  310. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  311. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  312. return NULL;
  313. }
  314. return circ;
  315. }
  316. /** Start establishing the first hop of our circuit. Figure out what
  317. * OR we should connect to, and if necessary start the connection to
  318. * it. If we're already connected, then send the 'create' cell.
  319. * Return 0 for ok, -reason if circ should be marked-for-close. */
  320. int
  321. circuit_handle_first_hop(origin_circuit_t *circ)
  322. {
  323. crypt_path_t *firsthop;
  324. channel_t *n_chan;
  325. int err_reason = 0;
  326. const char *msg = NULL;
  327. int should_launch = 0;
  328. firsthop = onion_next_hop_in_cpath(circ->cpath);
  329. tor_assert(firsthop);
  330. tor_assert(firsthop->extend_info);
  331. /* now see if we're already connected to the first OR in 'route' */
  332. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  333. fmt_addrport(&firsthop->extend_info->addr,
  334. firsthop->extend_info->port));
  335. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  336. &firsthop->extend_info->addr,
  337. &msg,
  338. &should_launch);
  339. if (!n_chan) {
  340. /* not currently connected in a useful way. */
  341. log_info(LD_CIRC, "Next router is %s: %s",
  342. safe_str_client(extend_info_describe(firsthop->extend_info)),
  343. msg?msg:"???");
  344. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  345. if (should_launch) {
  346. if (circ->build_state->onehop_tunnel)
  347. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  348. n_chan = channel_connect_for_circuit(
  349. &firsthop->extend_info->addr,
  350. firsthop->extend_info->port,
  351. firsthop->extend_info->identity_digest);
  352. if (!n_chan) { /* connect failed, forget the whole thing */
  353. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  354. return -END_CIRC_REASON_CONNECTFAILED;
  355. }
  356. }
  357. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  358. /* return success. The onion/circuit/etc will be taken care of
  359. * automatically (may already have been) whenever n_chan reaches
  360. * OR_CONN_STATE_OPEN.
  361. */
  362. return 0;
  363. } else { /* it's already open. use it. */
  364. tor_assert(!circ->base_.n_hop);
  365. circ->base_.n_chan = n_chan;
  366. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  367. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  368. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  369. return err_reason;
  370. }
  371. }
  372. return 0;
  373. }
  374. /** Find any circuits that are waiting on <b>or_conn</b> to become
  375. * open and get them to send their create cells forward.
  376. *
  377. * Status is 1 if connect succeeded, or 0 if connect failed.
  378. */
  379. void
  380. circuit_n_chan_done(channel_t *chan, int status)
  381. {
  382. smartlist_t *pending_circs;
  383. int err_reason = 0;
  384. tor_assert(chan);
  385. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  386. chan->nickname ? chan->nickname : "NULL",
  387. channel_get_canonical_remote_descr(chan), status);
  388. pending_circs = smartlist_new();
  389. circuit_get_all_pending_on_channel(pending_circs, chan);
  390. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  391. {
  392. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  393. * leaving them in in case it's possible for the status of a circuit to
  394. * change as we're going down the list. */
  395. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  396. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  397. continue;
  398. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  399. /* Look at addr/port. This is an unkeyed connection. */
  400. if (!channel_matches_extend_info(chan, circ->n_hop))
  401. continue;
  402. } else {
  403. /* We expected a key. See if it's the right one. */
  404. if (tor_memneq(chan->identity_digest,
  405. circ->n_hop->identity_digest, DIGEST_LEN))
  406. continue;
  407. }
  408. if (!status) { /* chan failed; close circ */
  409. log_info(LD_CIRC,"Channel failed; closing circ.");
  410. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  411. continue;
  412. }
  413. log_debug(LD_CIRC, "Found circ, sending create cell.");
  414. /* circuit_deliver_create_cell will set n_circ_id and add us to
  415. * chan_circuid_circuit_map, so we don't need to call
  416. * set_circid_chan here. */
  417. circ->n_chan = chan;
  418. extend_info_free(circ->n_hop);
  419. circ->n_hop = NULL;
  420. if (CIRCUIT_IS_ORIGIN(circ)) {
  421. if ((err_reason =
  422. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  423. log_info(LD_CIRC,
  424. "send_next_onion_skin failed; circuit marked for closing.");
  425. circuit_mark_for_close(circ, -err_reason);
  426. continue;
  427. /* XXX could this be bad, eg if next_onion_skin failed because conn
  428. * died? */
  429. }
  430. } else {
  431. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  432. tor_assert(circ->n_chan_create_cell);
  433. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  434. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  435. continue;
  436. }
  437. tor_free(circ->n_chan_create_cell);
  438. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  439. }
  440. }
  441. SMARTLIST_FOREACH_END(circ);
  442. smartlist_free(pending_circs);
  443. }
  444. /** Find a new circid that isn't currently in use on the circ->n_chan
  445. * for the outgoing
  446. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  447. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  448. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  449. * it. Return -1 if we failed to find a suitable circid, else return 0.
  450. */
  451. static int
  452. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  453. int relayed)
  454. {
  455. cell_t cell;
  456. circid_t id;
  457. int r;
  458. tor_assert(circ);
  459. tor_assert(circ->n_chan);
  460. tor_assert(create_cell);
  461. tor_assert(create_cell->cell_type == CELL_CREATE ||
  462. create_cell->cell_type == CELL_CREATE_FAST ||
  463. create_cell->cell_type == CELL_CREATE2);
  464. id = get_unique_circ_id_by_chan(circ->n_chan);
  465. if (!id) {
  466. log_warn(LD_CIRC,"failed to get unique circID.");
  467. return -1;
  468. }
  469. log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
  470. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  471. memset(&cell, 0, sizeof(cell_t));
  472. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  473. : create_cell_format(&cell, create_cell);
  474. if (r < 0) {
  475. log_warn(LD_CIRC,"Couldn't format create cell");
  476. return -1;
  477. }
  478. cell.circ_id = circ->n_circ_id;
  479. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  480. CELL_DIRECTION_OUT, 0);
  481. if (CIRCUIT_IS_ORIGIN(circ)) {
  482. /* Update began timestamp for circuits starting their first hop */
  483. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  484. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  485. log_warn(LD_CIRC,
  486. "Got first hop for a circuit without an opened channel. "
  487. "State: %s.", channel_state_to_string(circ->n_chan->state));
  488. tor_fragile_assert();
  489. }
  490. tor_gettimeofday(&circ->timestamp_began);
  491. }
  492. /* mark it so it gets better rate limiting treatment. */
  493. channel_timestamp_client(circ->n_chan);
  494. }
  495. return 0;
  496. }
  497. /** We've decided to start our reachability testing. If all
  498. * is set, log this to the user. Return 1 if we did, or 0 if
  499. * we chose not to log anything. */
  500. int
  501. inform_testing_reachability(void)
  502. {
  503. char dirbuf[128];
  504. const routerinfo_t *me = router_get_my_routerinfo();
  505. if (!me)
  506. return 0;
  507. control_event_server_status(LOG_NOTICE,
  508. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  509. me->address, me->or_port);
  510. if (me->dir_port) {
  511. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  512. me->address, me->dir_port);
  513. control_event_server_status(LOG_NOTICE,
  514. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  515. me->address, me->dir_port);
  516. }
  517. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  518. "(this may take up to %d minutes -- look for log "
  519. "messages indicating success)",
  520. me->address, me->or_port,
  521. me->dir_port ? dirbuf : "",
  522. me->dir_port ? "are" : "is",
  523. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  524. return 1;
  525. }
  526. /** Return true iff we should send a create_fast cell to start building a given
  527. * circuit */
  528. static INLINE int
  529. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  530. {
  531. const or_options_t *options = get_options();
  532. tor_assert(circ->cpath);
  533. tor_assert(circ->cpath->extend_info);
  534. if (!circ->cpath->extend_info->onion_key)
  535. return 1; /* our hand is forced: only a create_fast will work. */
  536. if (!options->FastFirstHopPK)
  537. return 0; /* we prefer to avoid create_fast */
  538. if (public_server_mode(options)) {
  539. /* We're a server, and we know an onion key. We can choose.
  540. * Prefer to blend our circuit into the other circuits we are
  541. * creating on behalf of others. */
  542. return 0;
  543. }
  544. return 1;
  545. }
  546. /** Return true if <b>circ</b> is the type of circuit we want to count
  547. * timeouts from. In particular, we want it to have not completed yet
  548. * (already completing indicates we cannibalized it), and we want it to
  549. * have exactly three hops.
  550. */
  551. int
  552. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  553. {
  554. return !circ->has_opened
  555. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  556. }
  557. #ifdef CURVE25519_ENABLED
  558. /** Return true if the ntor handshake is enabled in the configuration, or if
  559. * it's been set to "auto" in the configuration and it's enabled in the
  560. * consensus. */
  561. static int
  562. circuits_can_use_ntor(void)
  563. {
  564. const or_options_t *options = get_options();
  565. if (options->UseNTorHandshake != -1)
  566. return options->UseNTorHandshake;
  567. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  568. }
  569. #endif
  570. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  571. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  572. * accordingly. */
  573. static void
  574. circuit_pick_create_handshake(uint8_t *cell_type_out,
  575. uint16_t *handshake_type_out,
  576. const extend_info_t *ei)
  577. {
  578. #ifdef CURVE25519_ENABLED
  579. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  580. CURVE25519_PUBKEY_LEN) &&
  581. circuits_can_use_ntor()) {
  582. *cell_type_out = CELL_CREATE2;
  583. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  584. return;
  585. }
  586. #else
  587. (void) ei;
  588. #endif
  589. *cell_type_out = CELL_CREATE;
  590. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  591. }
  592. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  593. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  594. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  595. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  596. * *<b>create_cell_type_out</b> accordingly. */
  597. static void
  598. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  599. uint8_t *create_cell_type_out,
  600. uint16_t *handshake_type_out,
  601. const node_t *node_prev,
  602. const extend_info_t *ei)
  603. {
  604. uint8_t t;
  605. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  606. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  607. * proxy for whether it can do extend2 cells; once a version that
  608. * handles extend2 cells is out, remove it. */
  609. if (node_prev &&
  610. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  611. (node_has_curve25519_onion_key(node_prev) ||
  612. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  613. *cell_type_out = RELAY_COMMAND_EXTEND2;
  614. *create_cell_type_out = CELL_CREATE2;
  615. } else {
  616. *cell_type_out = RELAY_COMMAND_EXTEND;
  617. *create_cell_type_out = CELL_CREATE;
  618. }
  619. }
  620. /** This is the backbone function for building circuits.
  621. *
  622. * If circ's first hop is closed, then we need to build a create
  623. * cell and send it forward.
  624. *
  625. * Otherwise, we need to build a relay extend cell and send it
  626. * forward.
  627. *
  628. * Return -reason if we want to tear down circ, else return 0.
  629. */
  630. int
  631. circuit_send_next_onion_skin(origin_circuit_t *circ)
  632. {
  633. crypt_path_t *hop;
  634. const node_t *node;
  635. tor_assert(circ);
  636. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  637. /* This is the first hop. */
  638. create_cell_t cc;
  639. int fast;
  640. int len;
  641. log_debug(LD_CIRC,"First skin; sending create cell.");
  642. memset(&cc, 0, sizeof(cc));
  643. if (circ->build_state->onehop_tunnel)
  644. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  645. else
  646. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  647. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  648. fast = should_use_create_fast_for_circuit(circ);
  649. if (!fast) {
  650. /* We are an OR and we know the right onion key: we should
  651. * send a create cell.
  652. */
  653. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  654. circ->cpath->extend_info);
  655. note_request("cell: create", 1);
  656. } else {
  657. /* We are not an OR, and we're building the first hop of a circuit to a
  658. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  659. * and a DH operation. */
  660. cc.cell_type = CELL_CREATE_FAST;
  661. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  662. note_request("cell: create fast", 1);
  663. }
  664. len = onion_skin_create(cc.handshake_type,
  665. circ->cpath->extend_info,
  666. &circ->cpath->handshake_state,
  667. cc.onionskin);
  668. if (len < 0) {
  669. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  670. return - END_CIRC_REASON_INTERNAL;
  671. }
  672. cc.handshake_len = len;
  673. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  674. return - END_CIRC_REASON_RESOURCELIMIT;
  675. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  676. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  677. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  678. fast ? "CREATE_FAST" : "CREATE",
  679. node ? node_describe(node) : "<unnamed>");
  680. } else {
  681. extend_cell_t ec;
  682. int len;
  683. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  684. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  685. log_debug(LD_CIRC,"starting to send subsequent skin.");
  686. hop = onion_next_hop_in_cpath(circ->cpath);
  687. memset(&ec, 0, sizeof(ec));
  688. if (!hop) {
  689. /* done building the circuit. whew. */
  690. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  691. if (circuit_timeout_want_to_count_circ(circ)) {
  692. struct timeval end;
  693. long timediff;
  694. tor_gettimeofday(&end);
  695. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  696. /*
  697. * If the circuit build time is much greater than we would have cut
  698. * it off at, we probably had a suspend event along this codepath,
  699. * and we should discard the value.
  700. */
  701. if (timediff < 0 ||
  702. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  703. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  704. "Assuming clock jump. Purpose %d (%s)", timediff,
  705. circ->base_.purpose,
  706. circuit_purpose_to_string(circ->base_.purpose));
  707. } else if (!circuit_build_times_disabled()) {
  708. /* Only count circuit times if the network is live */
  709. if (circuit_build_times_network_check_live(
  710. get_circuit_build_times())) {
  711. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  712. (build_time_t)timediff);
  713. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  714. }
  715. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  716. circuit_build_times_network_circ_success(
  717. get_circuit_build_times_mutable());
  718. }
  719. }
  720. }
  721. log_info(LD_CIRC,"circuit built!");
  722. circuit_reset_failure_count(0);
  723. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  724. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  725. }
  726. pathbias_count_build_success(circ);
  727. circuit_rep_hist_note_result(circ);
  728. circuit_has_opened(circ); /* do other actions as necessary */
  729. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  730. const or_options_t *options = get_options();
  731. can_complete_circuit=1;
  732. /* FFFF Log a count of known routers here */
  733. log_notice(LD_GENERAL,
  734. "Tor has successfully opened a circuit. "
  735. "Looks like client functionality is working.");
  736. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  737. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  738. clear_broken_connection_map(1);
  739. if (server_mode(options) && !check_whether_orport_reachable()) {
  740. inform_testing_reachability();
  741. consider_testing_reachability(1, 1);
  742. }
  743. }
  744. /* We're done with measurement circuits here. Just close them */
  745. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  746. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  747. }
  748. return 0;
  749. }
  750. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  751. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  752. return - END_CIRC_REASON_INTERNAL;
  753. }
  754. {
  755. const node_t *prev_node;
  756. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  757. circuit_pick_extend_handshake(&ec.cell_type,
  758. &ec.create_cell.cell_type,
  759. &ec.create_cell.handshake_type,
  760. prev_node,
  761. hop->extend_info);
  762. }
  763. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  764. ec.orport_ipv4.port = hop->extend_info->port;
  765. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  766. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  767. len = onion_skin_create(ec.create_cell.handshake_type,
  768. hop->extend_info,
  769. &hop->handshake_state,
  770. ec.create_cell.onionskin);
  771. if (len < 0) {
  772. log_warn(LD_CIRC,"onion_skin_create failed.");
  773. return - END_CIRC_REASON_INTERNAL;
  774. }
  775. ec.create_cell.handshake_len = len;
  776. log_info(LD_CIRC,"Sending extend relay cell.");
  777. note_request("cell: extend", 1);
  778. {
  779. uint8_t command = 0;
  780. uint16_t payload_len=0;
  781. uint8_t payload[RELAY_PAYLOAD_SIZE];
  782. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  783. log_warn(LD_CIRC,"Couldn't format extend cell");
  784. return -END_CIRC_REASON_INTERNAL;
  785. }
  786. /* send it to hop->prev, because it will transfer
  787. * it to a create cell and then send to hop */
  788. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  789. command,
  790. (char*)payload, payload_len,
  791. hop->prev) < 0)
  792. return 0; /* circuit is closed */
  793. }
  794. hop->state = CPATH_STATE_AWAITING_KEYS;
  795. }
  796. return 0;
  797. }
  798. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  799. * something has also gone wrong with our network: notify the user,
  800. * and abandon all not-yet-used circuits. */
  801. void
  802. circuit_note_clock_jumped(int seconds_elapsed)
  803. {
  804. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  805. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  806. "assuming established circuits no longer work.",
  807. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  808. seconds_elapsed >=0 ? "forward" : "backward");
  809. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  810. seconds_elapsed);
  811. can_complete_circuit=0; /* so it'll log when it works again */
  812. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  813. "CLOCK_JUMPED");
  814. circuit_mark_all_unused_circs();
  815. circuit_mark_all_dirty_circs_as_unusable();
  816. }
  817. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  818. * skin and identity digest for the next hop. If we're already connected,
  819. * pass the onion skin to the next hop using a create cell; otherwise
  820. * launch a new OR connection, and <b>circ</b> will notice when the
  821. * connection succeeds or fails.
  822. *
  823. * Return -1 if we want to warn and tear down the circuit, else return 0.
  824. */
  825. int
  826. circuit_extend(cell_t *cell, circuit_t *circ)
  827. {
  828. channel_t *n_chan;
  829. relay_header_t rh;
  830. extend_cell_t ec;
  831. const char *msg = NULL;
  832. int should_launch = 0;
  833. if (circ->n_chan) {
  834. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  835. "n_chan already set. Bug/attack. Closing.");
  836. return -1;
  837. }
  838. if (circ->n_hop) {
  839. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  840. "conn to next hop already launched. Bug/attack. Closing.");
  841. return -1;
  842. }
  843. if (!server_mode(get_options())) {
  844. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  845. "Got an extend cell, but running as a client. Closing.");
  846. return -1;
  847. }
  848. relay_header_unpack(&rh, cell->payload);
  849. if (extend_cell_parse(&ec, rh.command,
  850. cell->payload+RELAY_HEADER_SIZE,
  851. rh.length) < 0) {
  852. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  853. "Can't parse extend cell. Closing circuit.");
  854. return -1;
  855. }
  856. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  857. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  858. "Client asked me to extend to zero destination port or addr.");
  859. return -1;
  860. }
  861. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  862. !get_options()->ExtendAllowPrivateAddresses) {
  863. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  864. "Client asked me to extend to a private address");
  865. return -1;
  866. }
  867. /* Check if they asked us for 0000..0000. We support using
  868. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  869. * but we don't want to let people send us extend cells for empty
  870. * fingerprints -- a) because it opens the user up to a mitm attack,
  871. * and b) because it lets an attacker force the relay to hold open a
  872. * new TLS connection for each extend request. */
  873. if (tor_digest_is_zero((const char*)ec.node_id)) {
  874. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  875. "Client asked me to extend without specifying an id_digest.");
  876. return -1;
  877. }
  878. /* Next, check if we're being asked to connect to the hop that the
  879. * extend cell came from. There isn't any reason for that, and it can
  880. * assist circular-path attacks. */
  881. if (tor_memeq(ec.node_id,
  882. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  883. DIGEST_LEN)) {
  884. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  885. "Client asked me to extend back to the previous hop.");
  886. return -1;
  887. }
  888. n_chan = channel_get_for_extend((const char*)ec.node_id,
  889. &ec.orport_ipv4.addr,
  890. &msg,
  891. &should_launch);
  892. if (!n_chan) {
  893. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  894. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  895. msg?msg:"????");
  896. circ->n_hop = extend_info_new(NULL /*nickname*/,
  897. (const char*)ec.node_id,
  898. NULL /*onion_key*/,
  899. NULL /*curve25519_key*/,
  900. &ec.orport_ipv4.addr,
  901. ec.orport_ipv4.port);
  902. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  903. sizeof(ec.create_cell));
  904. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  905. if (should_launch) {
  906. /* we should try to open a connection */
  907. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  908. ec.orport_ipv4.port,
  909. (const char*)ec.node_id);
  910. if (!n_chan) {
  911. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  912. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  913. return 0;
  914. }
  915. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  916. }
  917. /* return success. The onion/circuit/etc will be taken care of
  918. * automatically (may already have been) whenever n_chan reaches
  919. * OR_CONN_STATE_OPEN.
  920. */
  921. return 0;
  922. }
  923. tor_assert(!circ->n_hop); /* Connection is already established. */
  924. circ->n_chan = n_chan;
  925. log_debug(LD_CIRC,
  926. "n_chan is %s",
  927. channel_get_canonical_remote_descr(n_chan));
  928. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  929. return -1;
  930. return 0;
  931. }
  932. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  933. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  934. * used as follows:
  935. * - 20 to initialize f_digest
  936. * - 20 to initialize b_digest
  937. * - 16 to key f_crypto
  938. * - 16 to key b_crypto
  939. *
  940. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  941. */
  942. int
  943. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  944. int reverse)
  945. {
  946. crypto_digest_t *tmp_digest;
  947. crypto_cipher_t *tmp_crypto;
  948. tor_assert(cpath);
  949. tor_assert(key_data);
  950. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  951. cpath->f_digest || cpath->b_digest));
  952. cpath->f_digest = crypto_digest_new();
  953. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  954. cpath->b_digest = crypto_digest_new();
  955. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  956. if (!(cpath->f_crypto =
  957. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  958. log_warn(LD_BUG,"Forward cipher initialization failed.");
  959. return -1;
  960. }
  961. if (!(cpath->b_crypto =
  962. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  963. log_warn(LD_BUG,"Backward cipher initialization failed.");
  964. return -1;
  965. }
  966. if (reverse) {
  967. tmp_digest = cpath->f_digest;
  968. cpath->f_digest = cpath->b_digest;
  969. cpath->b_digest = tmp_digest;
  970. tmp_crypto = cpath->f_crypto;
  971. cpath->f_crypto = cpath->b_crypto;
  972. cpath->b_crypto = tmp_crypto;
  973. }
  974. return 0;
  975. }
  976. /** Increment the number of times we successfully extended a circuit to
  977. * <b>guard</b>, first checking if the failure rate is high enough that
  978. * we should eliminate the guard. Return -1 if the guard looks no good;
  979. * return 0 if the guard looks fine.
  980. */
  981. static int
  982. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  983. {
  984. entry_guards_changed();
  985. pathbias_measure_close_rate(guard);
  986. if (guard->path_bias_disabled)
  987. return -1;
  988. pathbias_scale_close_rates(guard);
  989. guard->circ_attempts++;
  990. log_info(LD_CIRC, "Got success count %f/%f for guard %s ($%s)",
  991. guard->circ_successes, guard->circ_attempts, guard->nickname,
  992. hex_str(guard->identity, DIGEST_LEN));
  993. return 0;
  994. }
  995. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  996. * (The body of <b>reply</b> varies depending on what sort of handshake
  997. * this is.)
  998. *
  999. * Calculate the appropriate keys and digests, make sure KH is
  1000. * correct, and initialize this hop of the cpath.
  1001. *
  1002. * Return - reason if we want to mark circ for close, else return 0.
  1003. */
  1004. int
  1005. circuit_finish_handshake(origin_circuit_t *circ,
  1006. const created_cell_t *reply)
  1007. {
  1008. char keys[CPATH_KEY_MATERIAL_LEN];
  1009. crypt_path_t *hop;
  1010. int rv;
  1011. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  1012. return rv;
  1013. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1014. hop = circ->cpath;
  1015. } else {
  1016. hop = onion_next_hop_in_cpath(circ->cpath);
  1017. if (!hop) { /* got an extended when we're all done? */
  1018. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1019. return - END_CIRC_REASON_TORPROTOCOL;
  1020. }
  1021. }
  1022. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1023. {
  1024. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1025. &hop->handshake_state,
  1026. reply->reply, reply->handshake_len,
  1027. (uint8_t*)keys, sizeof(keys),
  1028. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1029. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1030. return -END_CIRC_REASON_TORPROTOCOL;
  1031. }
  1032. }
  1033. onion_handshake_state_release(&hop->handshake_state);
  1034. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1035. return -END_CIRC_REASON_TORPROTOCOL;
  1036. }
  1037. hop->state = CPATH_STATE_OPEN;
  1038. log_info(LD_CIRC,"Finished building circuit hop:");
  1039. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1040. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1041. return 0;
  1042. }
  1043. /** We received a relay truncated cell on circ.
  1044. *
  1045. * Since we don't send truncates currently, getting a truncated
  1046. * means that a connection broke or an extend failed. For now,
  1047. * just give up: force circ to close, and return 0.
  1048. */
  1049. int
  1050. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1051. {
  1052. // crypt_path_t *victim;
  1053. // connection_t *stream;
  1054. tor_assert(circ);
  1055. tor_assert(layer);
  1056. /* XXX Since we don't send truncates currently, getting a truncated
  1057. * means that a connection broke or an extend failed. For now,
  1058. * just give up.
  1059. */
  1060. circuit_mark_for_close(TO_CIRCUIT(circ),
  1061. END_CIRC_REASON_FLAG_REMOTE|reason);
  1062. return 0;
  1063. #if 0
  1064. while (layer->next != circ->cpath) {
  1065. /* we need to clear out layer->next */
  1066. victim = layer->next;
  1067. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1068. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1069. if (stream->cpath_layer == victim) {
  1070. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1071. stream->stream_id);
  1072. /* no need to send 'end' relay cells,
  1073. * because the other side's already dead
  1074. */
  1075. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1076. }
  1077. }
  1078. layer->next = victim->next;
  1079. circuit_free_cpath_node(victim);
  1080. }
  1081. log_info(LD_CIRC, "finished");
  1082. return 0;
  1083. #endif
  1084. }
  1085. /** Given a response payload and keys, initialize, then send a created
  1086. * cell back.
  1087. */
  1088. int
  1089. onionskin_answer(or_circuit_t *circ,
  1090. const created_cell_t *created_cell,
  1091. const char *keys,
  1092. const uint8_t *rend_circ_nonce)
  1093. {
  1094. cell_t cell;
  1095. crypt_path_t *tmp_cpath;
  1096. if (created_cell_format(&cell, created_cell) < 0) {
  1097. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1098. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1099. return -1;
  1100. }
  1101. cell.circ_id = circ->p_circ_id;
  1102. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1103. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1104. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1105. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1106. (unsigned int)get_uint32(keys),
  1107. (unsigned int)get_uint32(keys+20));
  1108. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1109. log_warn(LD_BUG,"Circuit initialization failed");
  1110. tor_free(tmp_cpath);
  1111. return -1;
  1112. }
  1113. circ->n_digest = tmp_cpath->f_digest;
  1114. circ->n_crypto = tmp_cpath->f_crypto;
  1115. circ->p_digest = tmp_cpath->b_digest;
  1116. circ->p_crypto = tmp_cpath->b_crypto;
  1117. tmp_cpath->magic = 0;
  1118. tor_free(tmp_cpath);
  1119. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1120. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1121. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1122. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1123. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1124. circ->is_first_hop ? "created_fast" : "created");
  1125. if (!channel_is_local(circ->p_chan) &&
  1126. !channel_is_outgoing(circ->p_chan)) {
  1127. /* record that we could process create cells from a non-local conn
  1128. * that we didn't initiate; presumably this means that create cells
  1129. * can reach us too. */
  1130. router_orport_found_reachable();
  1131. }
  1132. return 0;
  1133. }
  1134. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  1135. * number of endpoints that would give something away about our destination.
  1136. *
  1137. * If the routerlist <b>nodes</b> doesn't have enough routers
  1138. * to handle the desired path length, return -1.
  1139. */
  1140. static int
  1141. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  1142. {
  1143. int num_acceptable_routers;
  1144. int routelen;
  1145. tor_assert(nodes);
  1146. routelen = DEFAULT_ROUTE_LEN;
  1147. if (exit &&
  1148. purpose != CIRCUIT_PURPOSE_TESTING &&
  1149. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1150. routelen++;
  1151. num_acceptable_routers = count_acceptable_nodes(nodes);
  1152. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1153. routelen, num_acceptable_routers, smartlist_len(nodes));
  1154. if (num_acceptable_routers < routelen) {
  1155. log_info(LD_CIRC,
  1156. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1157. num_acceptable_routers, routelen);
  1158. return -1;
  1159. }
  1160. return routelen;
  1161. }
  1162. /** Return a newly allocated list of uint16_t * for each predicted port not
  1163. * handled by a current circuit. */
  1164. static smartlist_t *
  1165. circuit_get_unhandled_ports(time_t now)
  1166. {
  1167. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1168. circuit_remove_handled_ports(dest);
  1169. return dest;
  1170. }
  1171. /** Return 1 if we already have circuits present or on the way for
  1172. * all anticipated ports. Return 0 if we should make more.
  1173. *
  1174. * If we're returning 0, set need_uptime and need_capacity to
  1175. * indicate any requirements that the unhandled ports have.
  1176. */
  1177. int
  1178. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1179. int *need_capacity)
  1180. {
  1181. int i, enough;
  1182. uint16_t *port;
  1183. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1184. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1185. tor_assert(need_uptime);
  1186. tor_assert(need_capacity);
  1187. // Always predict need_capacity
  1188. *need_capacity = 1;
  1189. enough = (smartlist_len(sl) == 0);
  1190. for (i = 0; i < smartlist_len(sl); ++i) {
  1191. port = smartlist_get(sl, i);
  1192. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1193. *need_uptime = 1;
  1194. tor_free(port);
  1195. }
  1196. smartlist_free(sl);
  1197. return enough;
  1198. }
  1199. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1200. * <b>needed_ports</b>, else return 0.
  1201. */
  1202. static int
  1203. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1204. { /* XXXX MOVE */
  1205. int i;
  1206. uint16_t port;
  1207. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1208. addr_policy_result_t r;
  1209. /* alignment issues aren't a worry for this dereference, since
  1210. needed_ports is explicitly a smartlist of uint16_t's */
  1211. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1212. tor_assert(port);
  1213. if (node)
  1214. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1215. else
  1216. continue;
  1217. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1218. return 1;
  1219. }
  1220. return 0;
  1221. }
  1222. /** Return true iff <b>conn</b> needs another general circuit to be
  1223. * built. */
  1224. static int
  1225. ap_stream_wants_exit_attention(connection_t *conn)
  1226. {
  1227. entry_connection_t *entry;
  1228. if (conn->type != CONN_TYPE_AP)
  1229. return 0;
  1230. entry = TO_ENTRY_CONN(conn);
  1231. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1232. !conn->marked_for_close &&
  1233. !(entry->want_onehop) && /* ignore one-hop streams */
  1234. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1235. !(entry->chosen_exit_name) && /* ignore defined streams */
  1236. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1237. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1238. MIN_CIRCUITS_HANDLING_STREAM))
  1239. return 1;
  1240. return 0;
  1241. }
  1242. /** Return a pointer to a suitable router to be the exit node for the
  1243. * general-purpose circuit we're about to build.
  1244. *
  1245. * Look through the connection array, and choose a router that maximizes
  1246. * the number of pending streams that can exit from this router.
  1247. *
  1248. * Return NULL if we can't find any suitable routers.
  1249. */
  1250. static const node_t *
  1251. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1252. {
  1253. int *n_supported;
  1254. int n_pending_connections = 0;
  1255. smartlist_t *connections;
  1256. int best_support = -1;
  1257. int n_best_support=0;
  1258. const or_options_t *options = get_options();
  1259. const smartlist_t *the_nodes;
  1260. const node_t *node=NULL;
  1261. connections = get_connection_array();
  1262. /* Count how many connections are waiting for a circuit to be built.
  1263. * We use this for log messages now, but in the future we may depend on it.
  1264. */
  1265. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1266. {
  1267. if (ap_stream_wants_exit_attention(conn))
  1268. ++n_pending_connections;
  1269. });
  1270. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1271. // n_pending_connections);
  1272. /* Now we count, for each of the routers in the directory, how many
  1273. * of the pending connections could possibly exit from that
  1274. * router (n_supported[i]). (We can't be sure about cases where we
  1275. * don't know the IP address of the pending connection.)
  1276. *
  1277. * -1 means "Don't use this router at all."
  1278. */
  1279. the_nodes = nodelist_get_list();
  1280. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1281. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1282. const int i = node_sl_idx;
  1283. if (router_digest_is_me(node->identity)) {
  1284. n_supported[i] = -1;
  1285. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1286. /* XXX there's probably a reverse predecessor attack here, but
  1287. * it's slow. should we take this out? -RD
  1288. */
  1289. continue;
  1290. }
  1291. if (!node_has_descriptor(node)) {
  1292. n_supported[i] = -1;
  1293. continue;
  1294. }
  1295. if (!node->is_running || node->is_bad_exit) {
  1296. n_supported[i] = -1;
  1297. continue; /* skip routers that are known to be down or bad exits */
  1298. }
  1299. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1300. /* never pick a non-general node as a random exit. */
  1301. n_supported[i] = -1;
  1302. continue;
  1303. }
  1304. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1305. n_supported[i] = -1;
  1306. continue; /* user asked us not to use it, no matter what */
  1307. }
  1308. if (options->ExitNodes &&
  1309. !routerset_contains_node(options->ExitNodes, node)) {
  1310. n_supported[i] = -1;
  1311. continue; /* not one of our chosen exit nodes */
  1312. }
  1313. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1314. n_supported[i] = -1;
  1315. continue; /* skip routers that are not suitable. Don't worry if
  1316. * this makes us reject all the possible routers: if so,
  1317. * we'll retry later in this function with need_update and
  1318. * need_capacity set to 0. */
  1319. }
  1320. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1321. /* if it's invalid and we don't want it */
  1322. n_supported[i] = -1;
  1323. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1324. // router->nickname, i);
  1325. continue; /* skip invalid routers */
  1326. }
  1327. if (options->ExcludeSingleHopRelays &&
  1328. node_allows_single_hop_exits(node)) {
  1329. n_supported[i] = -1;
  1330. continue;
  1331. }
  1332. if (node_exit_policy_rejects_all(node)) {
  1333. n_supported[i] = -1;
  1334. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1335. // router->nickname, i);
  1336. continue; /* skip routers that reject all */
  1337. }
  1338. n_supported[i] = 0;
  1339. /* iterate over connections */
  1340. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1341. if (!ap_stream_wants_exit_attention(conn))
  1342. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1343. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1344. ++n_supported[i];
  1345. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1346. // router->nickname, i, n_supported[i]);
  1347. } else {
  1348. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1349. // router->nickname, i);
  1350. }
  1351. } SMARTLIST_FOREACH_END(conn);
  1352. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1353. /* Leave best_support at -1 if that's where it is, so we can
  1354. * distinguish it later. */
  1355. continue;
  1356. }
  1357. if (n_supported[i] > best_support) {
  1358. /* If this router is better than previous ones, remember its index
  1359. * and goodness, and start counting how many routers are this good. */
  1360. best_support = n_supported[i]; n_best_support=1;
  1361. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1362. // router->nickname);
  1363. } else if (n_supported[i] == best_support) {
  1364. /* If this router is _as good_ as the best one, just increment the
  1365. * count of equally good routers.*/
  1366. ++n_best_support;
  1367. }
  1368. } SMARTLIST_FOREACH_END(node);
  1369. log_info(LD_CIRC,
  1370. "Found %d servers that might support %d/%d pending connections.",
  1371. n_best_support, best_support >= 0 ? best_support : 0,
  1372. n_pending_connections);
  1373. /* If any routers definitely support any pending connections, choose one
  1374. * at random. */
  1375. if (best_support > 0) {
  1376. smartlist_t *supporting = smartlist_new();
  1377. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1378. if (n_supported[node_sl_idx] == best_support)
  1379. smartlist_add(supporting, (void*)node);
  1380. });
  1381. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1382. smartlist_free(supporting);
  1383. } else {
  1384. /* Either there are no pending connections, or no routers even seem to
  1385. * possibly support any of them. Choose a router at random that satisfies
  1386. * at least one predicted exit port. */
  1387. int attempt;
  1388. smartlist_t *needed_ports, *supporting;
  1389. if (best_support == -1) {
  1390. if (need_uptime || need_capacity) {
  1391. log_info(LD_CIRC,
  1392. "We couldn't find any live%s%s routers; falling back "
  1393. "to list of all routers.",
  1394. need_capacity?", fast":"",
  1395. need_uptime?", stable":"");
  1396. tor_free(n_supported);
  1397. return choose_good_exit_server_general(0, 0);
  1398. }
  1399. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1400. "choosing a doomed exit at random.",
  1401. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1402. }
  1403. supporting = smartlist_new();
  1404. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1405. for (attempt = 0; attempt < 2; attempt++) {
  1406. /* try once to pick only from routers that satisfy a needed port,
  1407. * then if there are none, pick from any that support exiting. */
  1408. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1409. if (n_supported[node_sl_idx] != -1 &&
  1410. (attempt || node_handles_some_port(node, needed_ports))) {
  1411. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1412. // try, router->nickname);
  1413. smartlist_add(supporting, (void*)node);
  1414. }
  1415. } SMARTLIST_FOREACH_END(node);
  1416. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1417. if (node)
  1418. break;
  1419. smartlist_clear(supporting);
  1420. /* If we reach this point, we can't actually support any unhandled
  1421. * predicted ports, so clear all the remaining ones. */
  1422. if (smartlist_len(needed_ports))
  1423. rep_hist_remove_predicted_ports(needed_ports);
  1424. }
  1425. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1426. smartlist_free(needed_ports);
  1427. smartlist_free(supporting);
  1428. }
  1429. tor_free(n_supported);
  1430. if (node) {
  1431. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1432. return node;
  1433. }
  1434. if (options->ExitNodes) {
  1435. log_warn(LD_CIRC,
  1436. "No specified %sexit routers seem to be running: "
  1437. "can't choose an exit.",
  1438. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1439. }
  1440. return NULL;
  1441. }
  1442. /** Return a pointer to a suitable router to be the exit node for the
  1443. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1444. * if no router is suitable).
  1445. *
  1446. * For general-purpose circuits, pass it off to
  1447. * choose_good_exit_server_general()
  1448. *
  1449. * For client-side rendezvous circuits, choose a random node, weighted
  1450. * toward the preferences in 'options'.
  1451. */
  1452. static const node_t *
  1453. choose_good_exit_server(uint8_t purpose,
  1454. int need_uptime, int need_capacity, int is_internal)
  1455. {
  1456. const or_options_t *options = get_options();
  1457. router_crn_flags_t flags = CRN_NEED_DESC;
  1458. if (need_uptime)
  1459. flags |= CRN_NEED_UPTIME;
  1460. if (need_capacity)
  1461. flags |= CRN_NEED_CAPACITY;
  1462. switch (purpose) {
  1463. case CIRCUIT_PURPOSE_C_GENERAL:
  1464. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1465. flags |= CRN_ALLOW_INVALID;
  1466. if (is_internal) /* pick it like a middle hop */
  1467. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1468. else
  1469. return choose_good_exit_server_general(need_uptime,need_capacity);
  1470. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1471. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1472. flags |= CRN_ALLOW_INVALID;
  1473. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1474. }
  1475. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1476. tor_fragile_assert();
  1477. return NULL;
  1478. }
  1479. /** Log a warning if the user specified an exit for the circuit that
  1480. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1481. static void
  1482. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1483. {
  1484. const or_options_t *options = get_options();
  1485. routerset_t *rs = options->ExcludeNodes;
  1486. const char *description;
  1487. uint8_t purpose = circ->base_.purpose;
  1488. if (circ->build_state->onehop_tunnel)
  1489. return;
  1490. switch (purpose)
  1491. {
  1492. default:
  1493. case CIRCUIT_PURPOSE_OR:
  1494. case CIRCUIT_PURPOSE_INTRO_POINT:
  1495. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1496. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1497. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1498. (int)purpose,
  1499. circuit_purpose_to_string(purpose));
  1500. return;
  1501. case CIRCUIT_PURPOSE_C_GENERAL:
  1502. if (circ->build_state->is_internal)
  1503. return;
  1504. description = "requested exit node";
  1505. rs = options->ExcludeExitNodesUnion_;
  1506. break;
  1507. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1508. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1509. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1510. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1511. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1512. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1513. case CIRCUIT_PURPOSE_TESTING:
  1514. return;
  1515. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1516. case CIRCUIT_PURPOSE_C_REND_READY:
  1517. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1518. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1519. description = "chosen rendezvous point";
  1520. break;
  1521. case CIRCUIT_PURPOSE_CONTROLLER:
  1522. rs = options->ExcludeExitNodesUnion_;
  1523. description = "controller-selected circuit target";
  1524. break;
  1525. }
  1526. if (routerset_contains_extendinfo(rs, exit)) {
  1527. /* We should never get here if StrictNodes is set to 1. */
  1528. if (options->StrictNodes) {
  1529. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1530. "even though StrictNodes is set. Please report. "
  1531. "(Circuit purpose: %s)",
  1532. description, extend_info_describe(exit),
  1533. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1534. circuit_purpose_to_string(purpose));
  1535. } else {
  1536. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1537. "ExcludeNodes%s, because no better options were available. To "
  1538. "prevent this (and possibly break your Tor functionality), "
  1539. "set the StrictNodes configuration option. "
  1540. "(Circuit purpose: %s)",
  1541. description, extend_info_describe(exit),
  1542. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1543. circuit_purpose_to_string(purpose));
  1544. }
  1545. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1546. }
  1547. return;
  1548. }
  1549. /** Decide a suitable length for circ's cpath, and pick an exit
  1550. * router (or use <b>exit</b> if provided). Store these in the
  1551. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1552. static int
  1553. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1554. {
  1555. cpath_build_state_t *state = circ->build_state;
  1556. if (state->onehop_tunnel) {
  1557. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1558. state->desired_path_len = 1;
  1559. } else {
  1560. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1561. if (r < 1) /* must be at least 1 */
  1562. return -1;
  1563. state->desired_path_len = r;
  1564. }
  1565. if (exit) { /* the circuit-builder pre-requested one */
  1566. warn_if_last_router_excluded(circ, exit);
  1567. log_info(LD_CIRC,"Using requested exit node '%s'",
  1568. extend_info_describe(exit));
  1569. exit = extend_info_dup(exit);
  1570. } else { /* we have to decide one */
  1571. const node_t *node =
  1572. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1573. state->need_capacity, state->is_internal);
  1574. if (!node) {
  1575. log_warn(LD_CIRC,"failed to choose an exit server");
  1576. return -1;
  1577. }
  1578. exit = extend_info_from_node(node, 0);
  1579. tor_assert(exit);
  1580. }
  1581. state->chosen_exit = exit;
  1582. return 0;
  1583. }
  1584. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1585. * hop to the cpath reflecting this. Don't send the next extend cell --
  1586. * the caller will do this if it wants to.
  1587. */
  1588. int
  1589. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1590. {
  1591. cpath_build_state_t *state;
  1592. tor_assert(exit);
  1593. tor_assert(circ);
  1594. state = circ->build_state;
  1595. tor_assert(state);
  1596. extend_info_free(state->chosen_exit);
  1597. state->chosen_exit = extend_info_dup(exit);
  1598. ++circ->build_state->desired_path_len;
  1599. onion_append_hop(&circ->cpath, exit);
  1600. return 0;
  1601. }
  1602. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1603. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1604. * send the next extend cell to begin connecting to that hop.
  1605. */
  1606. int
  1607. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1608. {
  1609. int err_reason = 0;
  1610. warn_if_last_router_excluded(circ, exit);
  1611. tor_gettimeofday(&circ->base_.timestamp_began);
  1612. circuit_append_new_exit(circ, exit);
  1613. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1614. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1615. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1616. extend_info_describe(exit));
  1617. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1618. return -1;
  1619. }
  1620. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  1621. return 0;
  1622. }
  1623. /** Return the number of routers in <b>routers</b> that are currently up
  1624. * and available for building circuits through.
  1625. */
  1626. static int
  1627. count_acceptable_nodes(smartlist_t *nodes)
  1628. {
  1629. int num=0;
  1630. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1631. // log_debug(LD_CIRC,
  1632. // "Contemplating whether router %d (%s) is a new option.",
  1633. // i, r->nickname);
  1634. if (! node->is_running)
  1635. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1636. continue;
  1637. if (! node->is_valid)
  1638. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1639. continue;
  1640. if (! node_has_descriptor(node))
  1641. continue;
  1642. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1643. * allows this node in some places, then we're getting an inaccurate
  1644. * count. For now, be conservative and don't count it. But later we
  1645. * should try to be smarter. */
  1646. ++num;
  1647. } SMARTLIST_FOREACH_END(node);
  1648. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1649. return num;
  1650. }
  1651. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1652. * This function is used to extend cpath by another hop.
  1653. */
  1654. void
  1655. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1656. {
  1657. if (*head_ptr) {
  1658. new_hop->next = (*head_ptr);
  1659. new_hop->prev = (*head_ptr)->prev;
  1660. (*head_ptr)->prev->next = new_hop;
  1661. (*head_ptr)->prev = new_hop;
  1662. } else {
  1663. *head_ptr = new_hop;
  1664. new_hop->prev = new_hop->next = new_hop;
  1665. }
  1666. }
  1667. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1668. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1669. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1670. * circuit. In particular, make sure we don't pick the exit node or its
  1671. * family, and make sure we don't duplicate any previous nodes or their
  1672. * families. */
  1673. static const node_t *
  1674. choose_good_middle_server(uint8_t purpose,
  1675. cpath_build_state_t *state,
  1676. crypt_path_t *head,
  1677. int cur_len)
  1678. {
  1679. int i;
  1680. const node_t *r, *choice;
  1681. crypt_path_t *cpath;
  1682. smartlist_t *excluded;
  1683. const or_options_t *options = get_options();
  1684. router_crn_flags_t flags = CRN_NEED_DESC;
  1685. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1686. purpose <= CIRCUIT_PURPOSE_MAX_);
  1687. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1688. excluded = smartlist_new();
  1689. if ((r = build_state_get_exit_node(state))) {
  1690. nodelist_add_node_and_family(excluded, r);
  1691. }
  1692. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1693. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1694. nodelist_add_node_and_family(excluded, r);
  1695. }
  1696. }
  1697. if (state->need_uptime)
  1698. flags |= CRN_NEED_UPTIME;
  1699. if (state->need_capacity)
  1700. flags |= CRN_NEED_CAPACITY;
  1701. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1702. flags |= CRN_ALLOW_INVALID;
  1703. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1704. smartlist_free(excluded);
  1705. return choice;
  1706. }
  1707. /** Pick a good entry server for the circuit to be built according to
  1708. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1709. * router (if we're an OR), and respect firewall settings; if we're
  1710. * configured to use entry guards, return one.
  1711. *
  1712. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1713. * guard, not for any particular circuit.
  1714. */
  1715. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1716. const node_t *
  1717. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1718. {
  1719. const node_t *choice;
  1720. smartlist_t *excluded;
  1721. const or_options_t *options = get_options();
  1722. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1723. const node_t *node;
  1724. if (state && options->UseEntryGuards &&
  1725. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1726. /* This request is for an entry server to use for a regular circuit,
  1727. * and we use entry guard nodes. Just return one of the guard nodes. */
  1728. return choose_random_entry(state);
  1729. }
  1730. excluded = smartlist_new();
  1731. if (state && (node = build_state_get_exit_node(state))) {
  1732. /* Exclude the exit node from the state, if we have one. Also exclude its
  1733. * family. */
  1734. nodelist_add_node_and_family(excluded, node);
  1735. }
  1736. if (firewall_is_fascist_or()) {
  1737. /* Exclude all ORs that we can't reach through our firewall */
  1738. smartlist_t *nodes = nodelist_get_list();
  1739. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1740. if (!fascist_firewall_allows_node(node))
  1741. smartlist_add(excluded, (void*)node);
  1742. });
  1743. }
  1744. /* and exclude current entry guards and their families, if applicable */
  1745. /*XXXX025 use the using_as_guard flag to accomplish this.*/
  1746. if (options->UseEntryGuards) {
  1747. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1748. {
  1749. if ((node = node_get_by_id(entry->identity))) {
  1750. nodelist_add_node_and_family(excluded, node);
  1751. }
  1752. });
  1753. }
  1754. if (state) {
  1755. if (state->need_uptime)
  1756. flags |= CRN_NEED_UPTIME;
  1757. if (state->need_capacity)
  1758. flags |= CRN_NEED_CAPACITY;
  1759. }
  1760. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1761. flags |= CRN_ALLOW_INVALID;
  1762. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1763. smartlist_free(excluded);
  1764. return choice;
  1765. }
  1766. /** Return the first non-open hop in cpath, or return NULL if all
  1767. * hops are open. */
  1768. static crypt_path_t *
  1769. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1770. {
  1771. crypt_path_t *hop = cpath;
  1772. do {
  1773. if (hop->state != CPATH_STATE_OPEN)
  1774. return hop;
  1775. hop = hop->next;
  1776. } while (hop != cpath);
  1777. return NULL;
  1778. }
  1779. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1780. * based on <b>state</b>. Append the hop info to head_ptr.
  1781. */
  1782. static int
  1783. onion_extend_cpath(origin_circuit_t *circ)
  1784. {
  1785. uint8_t purpose = circ->base_.purpose;
  1786. cpath_build_state_t *state = circ->build_state;
  1787. int cur_len = circuit_get_cpath_len(circ);
  1788. extend_info_t *info = NULL;
  1789. if (cur_len >= state->desired_path_len) {
  1790. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1791. state->desired_path_len);
  1792. return 1;
  1793. }
  1794. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1795. state->desired_path_len);
  1796. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1797. info = extend_info_dup(state->chosen_exit);
  1798. } else if (cur_len == 0) { /* picking first node */
  1799. const node_t *r = choose_good_entry_server(purpose, state);
  1800. if (r) {
  1801. /* If we're a client, use the preferred address rather than the
  1802. primary address, for potentially connecting to an IPv6 OR
  1803. port. */
  1804. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  1805. tor_assert(info);
  1806. }
  1807. } else {
  1808. const node_t *r =
  1809. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1810. if (r) {
  1811. info = extend_info_from_node(r, 0);
  1812. tor_assert(info);
  1813. }
  1814. }
  1815. if (!info) {
  1816. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1817. "this circuit.", cur_len);
  1818. return -1;
  1819. }
  1820. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1821. extend_info_describe(info),
  1822. cur_len+1, build_state_get_exit_nickname(state));
  1823. onion_append_hop(&circ->cpath, info);
  1824. extend_info_free(info);
  1825. return 0;
  1826. }
  1827. /** Create a new hop, annotate it with information about its
  1828. * corresponding router <b>choice</b>, and append it to the
  1829. * end of the cpath <b>head_ptr</b>. */
  1830. static int
  1831. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1832. {
  1833. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1834. /* link hop into the cpath, at the end. */
  1835. onion_append_to_cpath(head_ptr, hop);
  1836. hop->magic = CRYPT_PATH_MAGIC;
  1837. hop->state = CPATH_STATE_CLOSED;
  1838. hop->extend_info = extend_info_dup(choice);
  1839. hop->package_window = circuit_initial_package_window();
  1840. hop->deliver_window = CIRCWINDOW_START;
  1841. return 0;
  1842. }
  1843. /** Allocate a new extend_info object based on the various arguments. */
  1844. extend_info_t *
  1845. extend_info_new(const char *nickname, const char *digest,
  1846. crypto_pk_t *onion_key,
  1847. const curve25519_public_key_t *curve25519_key,
  1848. const tor_addr_t *addr, uint16_t port)
  1849. {
  1850. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1851. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1852. if (nickname)
  1853. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1854. if (onion_key)
  1855. info->onion_key = crypto_pk_dup_key(onion_key);
  1856. #ifdef CURVE25519_ENABLED
  1857. if (curve25519_key)
  1858. memcpy(&info->curve25519_onion_key, curve25519_key,
  1859. sizeof(curve25519_public_key_t));
  1860. #else
  1861. (void)curve25519_key;
  1862. #endif
  1863. tor_addr_copy(&info->addr, addr);
  1864. info->port = port;
  1865. return info;
  1866. }
  1867. /** Allocate and return a new extend_info that can be used to build a
  1868. * circuit to or through the node <b>node</b>. Use the primary address
  1869. * of the node (i.e. its IPv4 address) unless
  1870. * <b>for_direct_connect</b> is true, in which case the preferred
  1871. * address is used instead. May return NULL if there is not enough
  1872. * info about <b>node</b> to extend to it--for example, if there is no
  1873. * routerinfo_t or microdesc_t.
  1874. **/
  1875. extend_info_t *
  1876. extend_info_from_node(const node_t *node, int for_direct_connect)
  1877. {
  1878. tor_addr_port_t ap;
  1879. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  1880. return NULL;
  1881. if (for_direct_connect)
  1882. node_get_pref_orport(node, &ap);
  1883. else
  1884. node_get_prim_orport(node, &ap);
  1885. log_debug(LD_CIRC, "using %s for %s",
  1886. fmt_addrport(&ap.addr, ap.port),
  1887. node->ri ? node->ri->nickname : node->rs->nickname);
  1888. if (node->ri)
  1889. return extend_info_new(node->ri->nickname,
  1890. node->identity,
  1891. node->ri->onion_pkey,
  1892. node->ri->onion_curve25519_pkey,
  1893. &ap.addr,
  1894. ap.port);
  1895. else if (node->rs && node->md)
  1896. return extend_info_new(node->rs->nickname,
  1897. node->identity,
  1898. node->md->onion_pkey,
  1899. node->md->onion_curve25519_pkey,
  1900. &ap.addr,
  1901. ap.port);
  1902. else
  1903. return NULL;
  1904. }
  1905. /** Release storage held by an extend_info_t struct. */
  1906. void
  1907. extend_info_free(extend_info_t *info)
  1908. {
  1909. if (!info)
  1910. return;
  1911. crypto_pk_free(info->onion_key);
  1912. tor_free(info);
  1913. }
  1914. /** Allocate and return a new extend_info_t with the same contents as
  1915. * <b>info</b>. */
  1916. extend_info_t *
  1917. extend_info_dup(extend_info_t *info)
  1918. {
  1919. extend_info_t *newinfo;
  1920. tor_assert(info);
  1921. newinfo = tor_malloc(sizeof(extend_info_t));
  1922. memcpy(newinfo, info, sizeof(extend_info_t));
  1923. if (info->onion_key)
  1924. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1925. else
  1926. newinfo->onion_key = NULL;
  1927. return newinfo;
  1928. }
  1929. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1930. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1931. * the chosen exit, return NULL.
  1932. */
  1933. const node_t *
  1934. build_state_get_exit_node(cpath_build_state_t *state)
  1935. {
  1936. if (!state || !state->chosen_exit)
  1937. return NULL;
  1938. return node_get_by_id(state->chosen_exit->identity_digest);
  1939. }
  1940. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1941. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1942. * chosen exit, return NULL.
  1943. */
  1944. const char *
  1945. build_state_get_exit_nickname(cpath_build_state_t *state)
  1946. {
  1947. if (!state || !state->chosen_exit)
  1948. return NULL;
  1949. return state->chosen_exit->nickname;
  1950. }