circuitbuild.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141
  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. #ifndef MIN
  43. #define MIN(a,b) ((a)<(b)?(a):(b))
  44. #endif
  45. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  46. uint16_t port,
  47. const char *id_digest);
  48. static int circuit_deliver_create_cell(circuit_t *circ,
  49. const create_cell_t *create_cell,
  50. int relayed);
  51. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  52. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  53. static int onion_extend_cpath(origin_circuit_t *circ);
  54. static int count_acceptable_nodes(smartlist_t *routers);
  55. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  56. /** This function tries to get a channel to the specified endpoint,
  57. * and then calls command_setup_channel() to give it the right
  58. * callbacks.
  59. */
  60. static channel_t *
  61. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  62. const char *id_digest)
  63. {
  64. channel_t *chan;
  65. chan = channel_connect(addr, port, id_digest);
  66. if (chan) command_setup_channel(chan);
  67. return chan;
  68. }
  69. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  70. * and with the high bit specified by conn-\>circ_id_type, until we get
  71. * a circ_id that is not in use by any other circuit on that conn.
  72. *
  73. * Return it, or 0 if can't get a unique circ_id.
  74. */
  75. static circid_t
  76. get_unique_circ_id_by_chan(channel_t *chan)
  77. {
  78. circid_t test_circ_id;
  79. circid_t attempts=0;
  80. circid_t high_bit, max_range;
  81. tor_assert(chan);
  82. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  83. log_warn(LD_BUG,
  84. "Trying to pick a circuit ID for a connection from "
  85. "a client with no identity.");
  86. return 0;
  87. }
  88. max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
  89. high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
  90. do {
  91. /* Sequentially iterate over test_circ_id=1...max_range until we find a
  92. * circID such that (high_bit|test_circ_id) is not already used. */
  93. test_circ_id = chan->next_circ_id++;
  94. if (test_circ_id == 0 || test_circ_id >= max_range) {
  95. test_circ_id = 1;
  96. chan->next_circ_id = 2;
  97. }
  98. if (++attempts > max_range) {
  99. /* Make sure we don't loop forever if all circ_id's are used. This
  100. * matters because it's an external DoS opportunity.
  101. */
  102. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  103. return 0;
  104. }
  105. test_circ_id |= high_bit;
  106. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  107. return test_circ_id;
  108. }
  109. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  110. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  111. * list information about link status in a more verbose format using spaces.
  112. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  113. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  114. * names.
  115. */
  116. static char *
  117. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  118. {
  119. crypt_path_t *hop;
  120. smartlist_t *elements;
  121. const char *states[] = {"closed", "waiting for keys", "open"};
  122. char *s;
  123. elements = smartlist_new();
  124. if (verbose) {
  125. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  126. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  127. circ->build_state->is_internal ? "internal" : "exit",
  128. circ->build_state->need_uptime ? " (high-uptime)" : "",
  129. circ->build_state->desired_path_len,
  130. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  131. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  132. (nickname?nickname:"*unnamed*"));
  133. }
  134. hop = circ->cpath;
  135. do {
  136. char *elt;
  137. const char *id;
  138. const node_t *node;
  139. if (!hop)
  140. break;
  141. if (!verbose && hop->state != CPATH_STATE_OPEN)
  142. break;
  143. if (!hop->extend_info)
  144. break;
  145. id = hop->extend_info->identity_digest;
  146. if (verbose_names) {
  147. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  148. if ((node = node_get_by_id(id))) {
  149. node_get_verbose_nickname(node, elt);
  150. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  151. elt[0] = '$';
  152. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  153. elt[HEX_DIGEST_LEN+1]= '~';
  154. strlcpy(elt+HEX_DIGEST_LEN+2,
  155. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  156. } else {
  157. elt[0] = '$';
  158. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  159. }
  160. } else { /* ! verbose_names */
  161. node = node_get_by_id(id);
  162. if (node && node_is_named(node)) {
  163. elt = tor_strdup(node_get_nickname(node));
  164. } else {
  165. elt = tor_malloc(HEX_DIGEST_LEN+2);
  166. elt[0] = '$';
  167. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  168. }
  169. }
  170. tor_assert(elt);
  171. if (verbose) {
  172. tor_assert(hop->state <= 2);
  173. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  174. tor_free(elt);
  175. } else {
  176. smartlist_add(elements, elt);
  177. }
  178. hop = hop->next;
  179. } while (hop != circ->cpath);
  180. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  181. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  182. smartlist_free(elements);
  183. return s;
  184. }
  185. /** If <b>verbose</b> is false, allocate and return a comma-separated
  186. * list of the currently built elements of <b>circ</b>. If
  187. * <b>verbose</b> is true, also list information about link status in
  188. * a more verbose format using spaces.
  189. */
  190. char *
  191. circuit_list_path(origin_circuit_t *circ, int verbose)
  192. {
  193. return circuit_list_path_impl(circ, verbose, 0);
  194. }
  195. /** Allocate and return a comma-separated list of the currently built elements
  196. * of <b>circ</b>, giving each as a verbose nickname.
  197. */
  198. char *
  199. circuit_list_path_for_controller(origin_circuit_t *circ)
  200. {
  201. return circuit_list_path_impl(circ, 0, 1);
  202. }
  203. /** Log, at severity <b>severity</b>, the nicknames of each router in
  204. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  205. * exit point.
  206. */
  207. void
  208. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  209. {
  210. char *s = circuit_list_path(circ,1);
  211. tor_log(severity,domain,"%s",s);
  212. tor_free(s);
  213. }
  214. /** Tell the rep(utation)hist(ory) module about the status of the links
  215. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  216. * extended; the _first_ hop that isn't open (if any) is marked as
  217. * unable to extend.
  218. */
  219. /* XXXX Someday we should learn from OR circuits too. */
  220. void
  221. circuit_rep_hist_note_result(origin_circuit_t *circ)
  222. {
  223. crypt_path_t *hop;
  224. const char *prev_digest = NULL;
  225. hop = circ->cpath;
  226. if (!hop) /* circuit hasn't started building yet. */
  227. return;
  228. if (server_mode(get_options())) {
  229. const routerinfo_t *me = router_get_my_routerinfo();
  230. if (!me)
  231. return;
  232. prev_digest = me->cache_info.identity_digest;
  233. }
  234. do {
  235. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  236. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  237. if (prev_digest) {
  238. if (hop->state == CPATH_STATE_OPEN)
  239. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  240. else {
  241. rep_hist_note_extend_failed(prev_digest, node->identity);
  242. break;
  243. }
  244. }
  245. prev_digest = node->identity;
  246. } else {
  247. prev_digest = NULL;
  248. }
  249. hop=hop->next;
  250. } while (hop!=circ->cpath);
  251. }
  252. /** Pick all the entries in our cpath. Stop and return 0 when we're
  253. * happy, or return -1 if an error occurs. */
  254. static int
  255. onion_populate_cpath(origin_circuit_t *circ)
  256. {
  257. int r;
  258. again:
  259. r = onion_extend_cpath(circ);
  260. if (r < 0) {
  261. log_info(LD_CIRC,"Generating cpath hop failed.");
  262. return -1;
  263. }
  264. if (r == 0)
  265. goto again;
  266. return 0; /* if r == 1 */
  267. }
  268. /** Create and return a new origin circuit. Initialize its purpose and
  269. * build-state based on our arguments. The <b>flags</b> argument is a
  270. * bitfield of CIRCLAUNCH_* flags. */
  271. origin_circuit_t *
  272. origin_circuit_init(uint8_t purpose, int flags)
  273. {
  274. /* sets circ->p_circ_id and circ->p_chan */
  275. origin_circuit_t *circ = origin_circuit_new();
  276. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  277. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  278. circ->build_state->onehop_tunnel =
  279. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  280. circ->build_state->need_uptime =
  281. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  282. circ->build_state->need_capacity =
  283. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  284. circ->build_state->is_internal =
  285. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  286. circ->base_.purpose = purpose;
  287. return circ;
  288. }
  289. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  290. * is defined, then use that as your exit router, else choose a suitable
  291. * exit node.
  292. *
  293. * Also launch a connection to the first OR in the chosen path, if
  294. * it's not open already.
  295. */
  296. origin_circuit_t *
  297. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  298. {
  299. origin_circuit_t *circ;
  300. int err_reason = 0;
  301. circ = origin_circuit_init(purpose, flags);
  302. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  303. onion_populate_cpath(circ) < 0) {
  304. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  305. return NULL;
  306. }
  307. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  308. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  309. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  310. return NULL;
  311. }
  312. return circ;
  313. }
  314. /** Start establishing the first hop of our circuit. Figure out what
  315. * OR we should connect to, and if necessary start the connection to
  316. * it. If we're already connected, then send the 'create' cell.
  317. * Return 0 for ok, -reason if circ should be marked-for-close. */
  318. int
  319. circuit_handle_first_hop(origin_circuit_t *circ)
  320. {
  321. crypt_path_t *firsthop;
  322. channel_t *n_chan;
  323. int err_reason = 0;
  324. const char *msg = NULL;
  325. int should_launch = 0;
  326. firsthop = onion_next_hop_in_cpath(circ->cpath);
  327. tor_assert(firsthop);
  328. tor_assert(firsthop->extend_info);
  329. /* now see if we're already connected to the first OR in 'route' */
  330. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  331. fmt_addrport(&firsthop->extend_info->addr,
  332. firsthop->extend_info->port));
  333. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  334. &firsthop->extend_info->addr,
  335. &msg,
  336. &should_launch);
  337. if (!n_chan) {
  338. /* not currently connected in a useful way. */
  339. log_info(LD_CIRC, "Next router is %s: %s",
  340. safe_str_client(extend_info_describe(firsthop->extend_info)),
  341. msg?msg:"???");
  342. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  343. if (should_launch) {
  344. if (circ->build_state->onehop_tunnel)
  345. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  346. n_chan = channel_connect_for_circuit(
  347. &firsthop->extend_info->addr,
  348. firsthop->extend_info->port,
  349. firsthop->extend_info->identity_digest);
  350. if (!n_chan) { /* connect failed, forget the whole thing */
  351. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  352. return -END_CIRC_REASON_CONNECTFAILED;
  353. }
  354. }
  355. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  356. /* return success. The onion/circuit/etc will be taken care of
  357. * automatically (may already have been) whenever n_chan reaches
  358. * OR_CONN_STATE_OPEN.
  359. */
  360. return 0;
  361. } else { /* it's already open. use it. */
  362. tor_assert(!circ->base_.n_hop);
  363. circ->base_.n_chan = n_chan;
  364. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  365. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  366. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  367. return err_reason;
  368. }
  369. }
  370. return 0;
  371. }
  372. /** Find any circuits that are waiting on <b>or_conn</b> to become
  373. * open and get them to send their create cells forward.
  374. *
  375. * Status is 1 if connect succeeded, or 0 if connect failed.
  376. */
  377. void
  378. circuit_n_chan_done(channel_t *chan, int status)
  379. {
  380. smartlist_t *pending_circs;
  381. int err_reason = 0;
  382. tor_assert(chan);
  383. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  384. chan->nickname ? chan->nickname : "NULL",
  385. channel_get_canonical_remote_descr(chan), status);
  386. pending_circs = smartlist_new();
  387. circuit_get_all_pending_on_channel(pending_circs, chan);
  388. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  389. {
  390. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  391. * leaving them in in case it's possible for the status of a circuit to
  392. * change as we're going down the list. */
  393. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  394. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  395. continue;
  396. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  397. /* Look at addr/port. This is an unkeyed connection. */
  398. if (!channel_matches_extend_info(chan, circ->n_hop))
  399. continue;
  400. } else {
  401. /* We expected a key. See if it's the right one. */
  402. if (tor_memneq(chan->identity_digest,
  403. circ->n_hop->identity_digest, DIGEST_LEN))
  404. continue;
  405. }
  406. if (!status) { /* chan failed; close circ */
  407. log_info(LD_CIRC,"Channel failed; closing circ.");
  408. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  409. continue;
  410. }
  411. log_debug(LD_CIRC, "Found circ, sending create cell.");
  412. /* circuit_deliver_create_cell will set n_circ_id and add us to
  413. * chan_circuid_circuit_map, so we don't need to call
  414. * set_circid_chan here. */
  415. circ->n_chan = chan;
  416. extend_info_free(circ->n_hop);
  417. circ->n_hop = NULL;
  418. if (CIRCUIT_IS_ORIGIN(circ)) {
  419. if ((err_reason =
  420. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  421. log_info(LD_CIRC,
  422. "send_next_onion_skin failed; circuit marked for closing.");
  423. circuit_mark_for_close(circ, -err_reason);
  424. continue;
  425. /* XXX could this be bad, eg if next_onion_skin failed because conn
  426. * died? */
  427. }
  428. } else {
  429. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  430. tor_assert(circ->n_chan_create_cell);
  431. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  432. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  433. continue;
  434. }
  435. tor_free(circ->n_chan_create_cell);
  436. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  437. }
  438. }
  439. SMARTLIST_FOREACH_END(circ);
  440. smartlist_free(pending_circs);
  441. }
  442. /** Find a new circid that isn't currently in use on the circ->n_chan
  443. * for the outgoing
  444. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  445. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  446. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  447. * it. Return -1 if we failed to find a suitable circid, else return 0.
  448. */
  449. static int
  450. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  451. int relayed)
  452. {
  453. cell_t cell;
  454. circid_t id;
  455. int r;
  456. tor_assert(circ);
  457. tor_assert(circ->n_chan);
  458. tor_assert(create_cell);
  459. tor_assert(create_cell->cell_type == CELL_CREATE ||
  460. create_cell->cell_type == CELL_CREATE_FAST ||
  461. create_cell->cell_type == CELL_CREATE2);
  462. id = get_unique_circ_id_by_chan(circ->n_chan);
  463. if (!id) {
  464. log_warn(LD_CIRC,"failed to get unique circID.");
  465. return -1;
  466. }
  467. log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
  468. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  469. memset(&cell, 0, sizeof(cell_t));
  470. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  471. : create_cell_format(&cell, create_cell);
  472. if (r < 0) {
  473. log_warn(LD_CIRC,"Couldn't format create cell");
  474. return -1;
  475. }
  476. cell.circ_id = circ->n_circ_id;
  477. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  478. CELL_DIRECTION_OUT, 0);
  479. if (CIRCUIT_IS_ORIGIN(circ)) {
  480. /* Update began timestamp for circuits starting their first hop */
  481. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  482. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  483. log_warn(LD_CIRC,
  484. "Got first hop for a circuit without an opened channel. "
  485. "State: %s.", channel_state_to_string(circ->n_chan->state));
  486. tor_fragile_assert();
  487. }
  488. tor_gettimeofday(&circ->timestamp_began);
  489. }
  490. /* mark it so it gets better rate limiting treatment. */
  491. channel_timestamp_client(circ->n_chan);
  492. }
  493. return 0;
  494. }
  495. /** We've decided to start our reachability testing. If all
  496. * is set, log this to the user. Return 1 if we did, or 0 if
  497. * we chose not to log anything. */
  498. int
  499. inform_testing_reachability(void)
  500. {
  501. char dirbuf[128];
  502. const routerinfo_t *me = router_get_my_routerinfo();
  503. if (!me)
  504. return 0;
  505. control_event_server_status(LOG_NOTICE,
  506. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  507. me->address, me->or_port);
  508. if (me->dir_port) {
  509. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  510. me->address, me->dir_port);
  511. control_event_server_status(LOG_NOTICE,
  512. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  513. me->address, me->dir_port);
  514. }
  515. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  516. "(this may take up to %d minutes -- look for log "
  517. "messages indicating success)",
  518. me->address, me->or_port,
  519. me->dir_port ? dirbuf : "",
  520. me->dir_port ? "are" : "is",
  521. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  522. return 1;
  523. }
  524. /** Return true iff we should send a create_fast cell to start building a given
  525. * circuit */
  526. static INLINE int
  527. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  528. {
  529. const or_options_t *options = get_options();
  530. tor_assert(circ->cpath);
  531. tor_assert(circ->cpath->extend_info);
  532. if (!circ->cpath->extend_info->onion_key)
  533. return 1; /* our hand is forced: only a create_fast will work. */
  534. if (public_server_mode(options)) {
  535. /* We're a server, and we know an onion key. We can choose.
  536. * Prefer to blend our circuit into the other circuits we are
  537. * creating on behalf of others. */
  538. return 0;
  539. }
  540. if (options->FastFirstHopPK == -1) {
  541. /* option is "auto", so look at the consensus. */
  542. return networkstatus_get_param(NULL, "usecreatefast", 1, 0, 1);
  543. }
  544. return options->FastFirstHopPK;
  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. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  977. * (The body of <b>reply</b> varies depending on what sort of handshake
  978. * this is.)
  979. *
  980. * Calculate the appropriate keys and digests, make sure KH is
  981. * correct, and initialize this hop of the cpath.
  982. *
  983. * Return - reason if we want to mark circ for close, else return 0.
  984. */
  985. int
  986. circuit_finish_handshake(origin_circuit_t *circ,
  987. const created_cell_t *reply)
  988. {
  989. char keys[CPATH_KEY_MATERIAL_LEN];
  990. crypt_path_t *hop;
  991. int rv;
  992. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  993. return rv;
  994. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  995. hop = circ->cpath;
  996. } else {
  997. hop = onion_next_hop_in_cpath(circ->cpath);
  998. if (!hop) { /* got an extended when we're all done? */
  999. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1000. return - END_CIRC_REASON_TORPROTOCOL;
  1001. }
  1002. }
  1003. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1004. {
  1005. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1006. &hop->handshake_state,
  1007. reply->reply, reply->handshake_len,
  1008. (uint8_t*)keys, sizeof(keys),
  1009. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1010. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1011. return -END_CIRC_REASON_TORPROTOCOL;
  1012. }
  1013. }
  1014. onion_handshake_state_release(&hop->handshake_state);
  1015. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1016. return -END_CIRC_REASON_TORPROTOCOL;
  1017. }
  1018. hop->state = CPATH_STATE_OPEN;
  1019. log_info(LD_CIRC,"Finished building circuit hop:");
  1020. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1021. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1022. return 0;
  1023. }
  1024. /** We received a relay truncated cell on circ.
  1025. *
  1026. * Since we don't send truncates currently, getting a truncated
  1027. * means that a connection broke or an extend failed. For now,
  1028. * just give up: force circ to close, and return 0.
  1029. */
  1030. int
  1031. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1032. {
  1033. // crypt_path_t *victim;
  1034. // connection_t *stream;
  1035. tor_assert(circ);
  1036. tor_assert(layer);
  1037. /* XXX Since we don't send truncates currently, getting a truncated
  1038. * means that a connection broke or an extend failed. For now,
  1039. * just give up.
  1040. */
  1041. circuit_mark_for_close(TO_CIRCUIT(circ),
  1042. END_CIRC_REASON_FLAG_REMOTE|reason);
  1043. return 0;
  1044. #if 0
  1045. while (layer->next != circ->cpath) {
  1046. /* we need to clear out layer->next */
  1047. victim = layer->next;
  1048. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1049. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1050. if (stream->cpath_layer == victim) {
  1051. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1052. stream->stream_id);
  1053. /* no need to send 'end' relay cells,
  1054. * because the other side's already dead
  1055. */
  1056. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1057. }
  1058. }
  1059. layer->next = victim->next;
  1060. circuit_free_cpath_node(victim);
  1061. }
  1062. log_info(LD_CIRC, "finished");
  1063. return 0;
  1064. #endif
  1065. }
  1066. /** Given a response payload and keys, initialize, then send a created
  1067. * cell back.
  1068. */
  1069. int
  1070. onionskin_answer(or_circuit_t *circ,
  1071. const created_cell_t *created_cell,
  1072. const char *keys,
  1073. const uint8_t *rend_circ_nonce)
  1074. {
  1075. cell_t cell;
  1076. crypt_path_t *tmp_cpath;
  1077. if (created_cell_format(&cell, created_cell) < 0) {
  1078. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1079. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1080. return -1;
  1081. }
  1082. cell.circ_id = circ->p_circ_id;
  1083. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1084. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1085. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1086. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1087. (unsigned int)get_uint32(keys),
  1088. (unsigned int)get_uint32(keys+20));
  1089. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1090. log_warn(LD_BUG,"Circuit initialization failed");
  1091. tor_free(tmp_cpath);
  1092. return -1;
  1093. }
  1094. circ->n_digest = tmp_cpath->f_digest;
  1095. circ->n_crypto = tmp_cpath->f_crypto;
  1096. circ->p_digest = tmp_cpath->b_digest;
  1097. circ->p_crypto = tmp_cpath->b_crypto;
  1098. tmp_cpath->magic = 0;
  1099. tor_free(tmp_cpath);
  1100. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1101. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1102. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1103. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1104. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1105. circ->is_first_hop ? "created_fast" : "created");
  1106. if (!channel_is_local(circ->p_chan) &&
  1107. !channel_is_outgoing(circ->p_chan)) {
  1108. /* record that we could process create cells from a non-local conn
  1109. * that we didn't initiate; presumably this means that create cells
  1110. * can reach us too. */
  1111. router_orport_found_reachable();
  1112. }
  1113. return 0;
  1114. }
  1115. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  1116. * number of endpoints that would give something away about our destination.
  1117. *
  1118. * If the routerlist <b>nodes</b> doesn't have enough routers
  1119. * to handle the desired path length, return -1.
  1120. */
  1121. static int
  1122. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  1123. {
  1124. int num_acceptable_routers;
  1125. int routelen;
  1126. tor_assert(nodes);
  1127. routelen = DEFAULT_ROUTE_LEN;
  1128. if (exit &&
  1129. purpose != CIRCUIT_PURPOSE_TESTING &&
  1130. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1131. routelen++;
  1132. num_acceptable_routers = count_acceptable_nodes(nodes);
  1133. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1134. routelen, num_acceptable_routers, smartlist_len(nodes));
  1135. if (num_acceptable_routers < routelen) {
  1136. log_info(LD_CIRC,
  1137. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1138. num_acceptable_routers, routelen);
  1139. return -1;
  1140. }
  1141. return routelen;
  1142. }
  1143. /** Return a newly allocated list of uint16_t * for each predicted port not
  1144. * handled by a current circuit. */
  1145. static smartlist_t *
  1146. circuit_get_unhandled_ports(time_t now)
  1147. {
  1148. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1149. circuit_remove_handled_ports(dest);
  1150. return dest;
  1151. }
  1152. /** Return 1 if we already have circuits present or on the way for
  1153. * all anticipated ports. Return 0 if we should make more.
  1154. *
  1155. * If we're returning 0, set need_uptime and need_capacity to
  1156. * indicate any requirements that the unhandled ports have.
  1157. */
  1158. int
  1159. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1160. int *need_capacity)
  1161. {
  1162. int i, enough;
  1163. uint16_t *port;
  1164. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1165. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1166. tor_assert(need_uptime);
  1167. tor_assert(need_capacity);
  1168. // Always predict need_capacity
  1169. *need_capacity = 1;
  1170. enough = (smartlist_len(sl) == 0);
  1171. for (i = 0; i < smartlist_len(sl); ++i) {
  1172. port = smartlist_get(sl, i);
  1173. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1174. *need_uptime = 1;
  1175. tor_free(port);
  1176. }
  1177. smartlist_free(sl);
  1178. return enough;
  1179. }
  1180. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1181. * <b>needed_ports</b>, else return 0.
  1182. */
  1183. static int
  1184. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1185. { /* XXXX MOVE */
  1186. int i;
  1187. uint16_t port;
  1188. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1189. addr_policy_result_t r;
  1190. /* alignment issues aren't a worry for this dereference, since
  1191. needed_ports is explicitly a smartlist of uint16_t's */
  1192. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1193. tor_assert(port);
  1194. if (node)
  1195. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1196. else
  1197. continue;
  1198. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1199. return 1;
  1200. }
  1201. return 0;
  1202. }
  1203. /** Return true iff <b>conn</b> needs another general circuit to be
  1204. * built. */
  1205. static int
  1206. ap_stream_wants_exit_attention(connection_t *conn)
  1207. {
  1208. entry_connection_t *entry;
  1209. if (conn->type != CONN_TYPE_AP)
  1210. return 0;
  1211. entry = TO_ENTRY_CONN(conn);
  1212. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1213. !conn->marked_for_close &&
  1214. !(entry->want_onehop) && /* ignore one-hop streams */
  1215. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1216. !(entry->chosen_exit_name) && /* ignore defined streams */
  1217. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1218. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1219. MIN_CIRCUITS_HANDLING_STREAM))
  1220. return 1;
  1221. return 0;
  1222. }
  1223. /** Return a pointer to a suitable router to be the exit node for the
  1224. * general-purpose circuit we're about to build.
  1225. *
  1226. * Look through the connection array, and choose a router that maximizes
  1227. * the number of pending streams that can exit from this router.
  1228. *
  1229. * Return NULL if we can't find any suitable routers.
  1230. */
  1231. static const node_t *
  1232. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1233. {
  1234. int *n_supported;
  1235. int n_pending_connections = 0;
  1236. smartlist_t *connections;
  1237. int best_support = -1;
  1238. int n_best_support=0;
  1239. const or_options_t *options = get_options();
  1240. const smartlist_t *the_nodes;
  1241. const node_t *node=NULL;
  1242. connections = get_connection_array();
  1243. /* Count how many connections are waiting for a circuit to be built.
  1244. * We use this for log messages now, but in the future we may depend on it.
  1245. */
  1246. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1247. {
  1248. if (ap_stream_wants_exit_attention(conn))
  1249. ++n_pending_connections;
  1250. });
  1251. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1252. // n_pending_connections);
  1253. /* Now we count, for each of the routers in the directory, how many
  1254. * of the pending connections could possibly exit from that
  1255. * router (n_supported[i]). (We can't be sure about cases where we
  1256. * don't know the IP address of the pending connection.)
  1257. *
  1258. * -1 means "Don't use this router at all."
  1259. */
  1260. the_nodes = nodelist_get_list();
  1261. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1262. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1263. const int i = node_sl_idx;
  1264. if (router_digest_is_me(node->identity)) {
  1265. n_supported[i] = -1;
  1266. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1267. /* XXX there's probably a reverse predecessor attack here, but
  1268. * it's slow. should we take this out? -RD
  1269. */
  1270. continue;
  1271. }
  1272. if (!node_has_descriptor(node)) {
  1273. n_supported[i] = -1;
  1274. continue;
  1275. }
  1276. if (!node->is_running || node->is_bad_exit) {
  1277. n_supported[i] = -1;
  1278. continue; /* skip routers that are known to be down or bad exits */
  1279. }
  1280. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1281. /* never pick a non-general node as a random exit. */
  1282. n_supported[i] = -1;
  1283. continue;
  1284. }
  1285. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1286. n_supported[i] = -1;
  1287. continue; /* user asked us not to use it, no matter what */
  1288. }
  1289. if (options->ExitNodes &&
  1290. !routerset_contains_node(options->ExitNodes, node)) {
  1291. n_supported[i] = -1;
  1292. continue; /* not one of our chosen exit nodes */
  1293. }
  1294. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1295. n_supported[i] = -1;
  1296. continue; /* skip routers that are not suitable. Don't worry if
  1297. * this makes us reject all the possible routers: if so,
  1298. * we'll retry later in this function with need_update and
  1299. * need_capacity set to 0. */
  1300. }
  1301. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1302. /* if it's invalid and we don't want it */
  1303. n_supported[i] = -1;
  1304. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1305. // router->nickname, i);
  1306. continue; /* skip invalid routers */
  1307. }
  1308. if (options->ExcludeSingleHopRelays &&
  1309. node_allows_single_hop_exits(node)) {
  1310. n_supported[i] = -1;
  1311. continue;
  1312. }
  1313. if (node_exit_policy_rejects_all(node)) {
  1314. n_supported[i] = -1;
  1315. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1316. // router->nickname, i);
  1317. continue; /* skip routers that reject all */
  1318. }
  1319. n_supported[i] = 0;
  1320. /* iterate over connections */
  1321. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1322. if (!ap_stream_wants_exit_attention(conn))
  1323. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1324. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1325. ++n_supported[i];
  1326. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1327. // router->nickname, i, n_supported[i]);
  1328. } else {
  1329. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1330. // router->nickname, i);
  1331. }
  1332. } SMARTLIST_FOREACH_END(conn);
  1333. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1334. /* Leave best_support at -1 if that's where it is, so we can
  1335. * distinguish it later. */
  1336. continue;
  1337. }
  1338. if (n_supported[i] > best_support) {
  1339. /* If this router is better than previous ones, remember its index
  1340. * and goodness, and start counting how many routers are this good. */
  1341. best_support = n_supported[i]; n_best_support=1;
  1342. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1343. // router->nickname);
  1344. } else if (n_supported[i] == best_support) {
  1345. /* If this router is _as good_ as the best one, just increment the
  1346. * count of equally good routers.*/
  1347. ++n_best_support;
  1348. }
  1349. } SMARTLIST_FOREACH_END(node);
  1350. log_info(LD_CIRC,
  1351. "Found %d servers that might support %d/%d pending connections.",
  1352. n_best_support, best_support >= 0 ? best_support : 0,
  1353. n_pending_connections);
  1354. /* If any routers definitely support any pending connections, choose one
  1355. * at random. */
  1356. if (best_support > 0) {
  1357. smartlist_t *supporting = smartlist_new();
  1358. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1359. if (n_supported[node_sl_idx] == best_support)
  1360. smartlist_add(supporting, (void*)node);
  1361. });
  1362. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1363. smartlist_free(supporting);
  1364. } else {
  1365. /* Either there are no pending connections, or no routers even seem to
  1366. * possibly support any of them. Choose a router at random that satisfies
  1367. * at least one predicted exit port. */
  1368. int attempt;
  1369. smartlist_t *needed_ports, *supporting;
  1370. if (best_support == -1) {
  1371. if (need_uptime || need_capacity) {
  1372. log_info(LD_CIRC,
  1373. "We couldn't find any live%s%s routers; falling back "
  1374. "to list of all routers.",
  1375. need_capacity?", fast":"",
  1376. need_uptime?", stable":"");
  1377. tor_free(n_supported);
  1378. return choose_good_exit_server_general(0, 0);
  1379. }
  1380. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1381. "choosing a doomed exit at random.",
  1382. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1383. }
  1384. supporting = smartlist_new();
  1385. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1386. for (attempt = 0; attempt < 2; attempt++) {
  1387. /* try once to pick only from routers that satisfy a needed port,
  1388. * then if there are none, pick from any that support exiting. */
  1389. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1390. if (n_supported[node_sl_idx] != -1 &&
  1391. (attempt || node_handles_some_port(node, needed_ports))) {
  1392. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1393. // try, router->nickname);
  1394. smartlist_add(supporting, (void*)node);
  1395. }
  1396. } SMARTLIST_FOREACH_END(node);
  1397. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1398. if (node)
  1399. break;
  1400. smartlist_clear(supporting);
  1401. /* If we reach this point, we can't actually support any unhandled
  1402. * predicted ports, so clear all the remaining ones. */
  1403. if (smartlist_len(needed_ports))
  1404. rep_hist_remove_predicted_ports(needed_ports);
  1405. }
  1406. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1407. smartlist_free(needed_ports);
  1408. smartlist_free(supporting);
  1409. }
  1410. tor_free(n_supported);
  1411. if (node) {
  1412. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1413. return node;
  1414. }
  1415. if (options->ExitNodes) {
  1416. log_warn(LD_CIRC,
  1417. "No specified %sexit routers seem to be running: "
  1418. "can't choose an exit.",
  1419. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1420. }
  1421. return NULL;
  1422. }
  1423. /** Return a pointer to a suitable router to be the exit node for the
  1424. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1425. * if no router is suitable).
  1426. *
  1427. * For general-purpose circuits, pass it off to
  1428. * choose_good_exit_server_general()
  1429. *
  1430. * For client-side rendezvous circuits, choose a random node, weighted
  1431. * toward the preferences in 'options'.
  1432. */
  1433. static const node_t *
  1434. choose_good_exit_server(uint8_t purpose,
  1435. int need_uptime, int need_capacity, int is_internal)
  1436. {
  1437. const or_options_t *options = get_options();
  1438. router_crn_flags_t flags = CRN_NEED_DESC;
  1439. if (need_uptime)
  1440. flags |= CRN_NEED_UPTIME;
  1441. if (need_capacity)
  1442. flags |= CRN_NEED_CAPACITY;
  1443. switch (purpose) {
  1444. case CIRCUIT_PURPOSE_C_GENERAL:
  1445. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1446. flags |= CRN_ALLOW_INVALID;
  1447. if (is_internal) /* pick it like a middle hop */
  1448. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1449. else
  1450. return choose_good_exit_server_general(need_uptime,need_capacity);
  1451. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1452. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1453. flags |= CRN_ALLOW_INVALID;
  1454. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1455. }
  1456. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1457. tor_fragile_assert();
  1458. return NULL;
  1459. }
  1460. /** Log a warning if the user specified an exit for the circuit that
  1461. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1462. static void
  1463. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1464. {
  1465. const or_options_t *options = get_options();
  1466. routerset_t *rs = options->ExcludeNodes;
  1467. const char *description;
  1468. uint8_t purpose = circ->base_.purpose;
  1469. if (circ->build_state->onehop_tunnel)
  1470. return;
  1471. switch (purpose)
  1472. {
  1473. default:
  1474. case CIRCUIT_PURPOSE_OR:
  1475. case CIRCUIT_PURPOSE_INTRO_POINT:
  1476. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1477. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1478. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1479. (int)purpose,
  1480. circuit_purpose_to_string(purpose));
  1481. return;
  1482. case CIRCUIT_PURPOSE_C_GENERAL:
  1483. if (circ->build_state->is_internal)
  1484. return;
  1485. description = "requested exit node";
  1486. rs = options->ExcludeExitNodesUnion_;
  1487. break;
  1488. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1489. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1490. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1491. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1492. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1493. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1494. case CIRCUIT_PURPOSE_TESTING:
  1495. return;
  1496. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1497. case CIRCUIT_PURPOSE_C_REND_READY:
  1498. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1499. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1500. description = "chosen rendezvous point";
  1501. break;
  1502. case CIRCUIT_PURPOSE_CONTROLLER:
  1503. rs = options->ExcludeExitNodesUnion_;
  1504. description = "controller-selected circuit target";
  1505. break;
  1506. }
  1507. if (routerset_contains_extendinfo(rs, exit)) {
  1508. /* We should never get here if StrictNodes is set to 1. */
  1509. if (options->StrictNodes) {
  1510. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1511. "even though StrictNodes is set. Please report. "
  1512. "(Circuit purpose: %s)",
  1513. description, extend_info_describe(exit),
  1514. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1515. circuit_purpose_to_string(purpose));
  1516. } else {
  1517. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1518. "ExcludeNodes%s, because no better options were available. To "
  1519. "prevent this (and possibly break your Tor functionality), "
  1520. "set the StrictNodes configuration option. "
  1521. "(Circuit purpose: %s)",
  1522. description, extend_info_describe(exit),
  1523. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1524. circuit_purpose_to_string(purpose));
  1525. }
  1526. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1527. }
  1528. return;
  1529. }
  1530. /** Decide a suitable length for circ's cpath, and pick an exit
  1531. * router (or use <b>exit</b> if provided). Store these in the
  1532. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1533. static int
  1534. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1535. {
  1536. cpath_build_state_t *state = circ->build_state;
  1537. if (state->onehop_tunnel) {
  1538. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1539. state->desired_path_len = 1;
  1540. } else {
  1541. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1542. if (r < 1) /* must be at least 1 */
  1543. return -1;
  1544. state->desired_path_len = r;
  1545. }
  1546. if (exit) { /* the circuit-builder pre-requested one */
  1547. warn_if_last_router_excluded(circ, exit);
  1548. log_info(LD_CIRC,"Using requested exit node '%s'",
  1549. extend_info_describe(exit));
  1550. exit = extend_info_dup(exit);
  1551. } else { /* we have to decide one */
  1552. const node_t *node =
  1553. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1554. state->need_capacity, state->is_internal);
  1555. if (!node) {
  1556. log_warn(LD_CIRC,"failed to choose an exit server");
  1557. return -1;
  1558. }
  1559. exit = extend_info_from_node(node, 0);
  1560. tor_assert(exit);
  1561. }
  1562. state->chosen_exit = exit;
  1563. return 0;
  1564. }
  1565. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1566. * hop to the cpath reflecting this. Don't send the next extend cell --
  1567. * the caller will do this if it wants to.
  1568. */
  1569. int
  1570. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1571. {
  1572. cpath_build_state_t *state;
  1573. tor_assert(exit);
  1574. tor_assert(circ);
  1575. state = circ->build_state;
  1576. tor_assert(state);
  1577. extend_info_free(state->chosen_exit);
  1578. state->chosen_exit = extend_info_dup(exit);
  1579. ++circ->build_state->desired_path_len;
  1580. onion_append_hop(&circ->cpath, exit);
  1581. return 0;
  1582. }
  1583. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1584. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1585. * send the next extend cell to begin connecting to that hop.
  1586. */
  1587. int
  1588. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1589. {
  1590. int err_reason = 0;
  1591. warn_if_last_router_excluded(circ, exit);
  1592. tor_gettimeofday(&circ->base_.timestamp_began);
  1593. circuit_append_new_exit(circ, exit);
  1594. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1595. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1596. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1597. extend_info_describe(exit));
  1598. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1599. return -1;
  1600. }
  1601. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  1602. return 0;
  1603. }
  1604. /** Return the number of routers in <b>routers</b> that are currently up
  1605. * and available for building circuits through.
  1606. */
  1607. static int
  1608. count_acceptable_nodes(smartlist_t *nodes)
  1609. {
  1610. int num=0;
  1611. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1612. // log_debug(LD_CIRC,
  1613. // "Contemplating whether router %d (%s) is a new option.",
  1614. // i, r->nickname);
  1615. if (! node->is_running)
  1616. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1617. continue;
  1618. if (! node->is_valid)
  1619. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1620. continue;
  1621. if (! node_has_descriptor(node))
  1622. continue;
  1623. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1624. * allows this node in some places, then we're getting an inaccurate
  1625. * count. For now, be conservative and don't count it. But later we
  1626. * should try to be smarter. */
  1627. ++num;
  1628. } SMARTLIST_FOREACH_END(node);
  1629. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1630. return num;
  1631. }
  1632. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1633. * This function is used to extend cpath by another hop.
  1634. */
  1635. void
  1636. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1637. {
  1638. if (*head_ptr) {
  1639. new_hop->next = (*head_ptr);
  1640. new_hop->prev = (*head_ptr)->prev;
  1641. (*head_ptr)->prev->next = new_hop;
  1642. (*head_ptr)->prev = new_hop;
  1643. } else {
  1644. *head_ptr = new_hop;
  1645. new_hop->prev = new_hop->next = new_hop;
  1646. }
  1647. }
  1648. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1649. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1650. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1651. * circuit. In particular, make sure we don't pick the exit node or its
  1652. * family, and make sure we don't duplicate any previous nodes or their
  1653. * families. */
  1654. static const node_t *
  1655. choose_good_middle_server(uint8_t purpose,
  1656. cpath_build_state_t *state,
  1657. crypt_path_t *head,
  1658. int cur_len)
  1659. {
  1660. int i;
  1661. const node_t *r, *choice;
  1662. crypt_path_t *cpath;
  1663. smartlist_t *excluded;
  1664. const or_options_t *options = get_options();
  1665. router_crn_flags_t flags = CRN_NEED_DESC;
  1666. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1667. purpose <= CIRCUIT_PURPOSE_MAX_);
  1668. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1669. excluded = smartlist_new();
  1670. if ((r = build_state_get_exit_node(state))) {
  1671. nodelist_add_node_and_family(excluded, r);
  1672. }
  1673. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1674. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1675. nodelist_add_node_and_family(excluded, r);
  1676. }
  1677. }
  1678. if (state->need_uptime)
  1679. flags |= CRN_NEED_UPTIME;
  1680. if (state->need_capacity)
  1681. flags |= CRN_NEED_CAPACITY;
  1682. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1683. flags |= CRN_ALLOW_INVALID;
  1684. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1685. smartlist_free(excluded);
  1686. return choice;
  1687. }
  1688. /** Pick a good entry server for the circuit to be built according to
  1689. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1690. * router (if we're an OR), and respect firewall settings; if we're
  1691. * configured to use entry guards, return one.
  1692. *
  1693. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1694. * guard, not for any particular circuit.
  1695. */
  1696. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1697. const node_t *
  1698. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1699. {
  1700. const node_t *choice;
  1701. smartlist_t *excluded;
  1702. const or_options_t *options = get_options();
  1703. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1704. const node_t *node;
  1705. if (state && options->UseEntryGuards &&
  1706. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1707. /* This request is for an entry server to use for a regular circuit,
  1708. * and we use entry guard nodes. Just return one of the guard nodes. */
  1709. return choose_random_entry(state);
  1710. }
  1711. excluded = smartlist_new();
  1712. if (state && (node = build_state_get_exit_node(state))) {
  1713. /* Exclude the exit node from the state, if we have one. Also exclude its
  1714. * family. */
  1715. nodelist_add_node_and_family(excluded, node);
  1716. }
  1717. if (firewall_is_fascist_or()) {
  1718. /* Exclude all ORs that we can't reach through our firewall */
  1719. smartlist_t *nodes = nodelist_get_list();
  1720. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1721. if (!fascist_firewall_allows_node(node))
  1722. smartlist_add(excluded, (void*)node);
  1723. });
  1724. }
  1725. /* and exclude current entry guards and their families, if applicable */
  1726. /*XXXX025 use the using_as_guard flag to accomplish this.*/
  1727. if (options->UseEntryGuards) {
  1728. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1729. {
  1730. if ((node = node_get_by_id(entry->identity))) {
  1731. nodelist_add_node_and_family(excluded, node);
  1732. }
  1733. });
  1734. }
  1735. if (state) {
  1736. if (state->need_uptime)
  1737. flags |= CRN_NEED_UPTIME;
  1738. if (state->need_capacity)
  1739. flags |= CRN_NEED_CAPACITY;
  1740. }
  1741. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1742. flags |= CRN_ALLOW_INVALID;
  1743. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1744. smartlist_free(excluded);
  1745. return choice;
  1746. }
  1747. /** Return the first non-open hop in cpath, or return NULL if all
  1748. * hops are open. */
  1749. static crypt_path_t *
  1750. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1751. {
  1752. crypt_path_t *hop = cpath;
  1753. do {
  1754. if (hop->state != CPATH_STATE_OPEN)
  1755. return hop;
  1756. hop = hop->next;
  1757. } while (hop != cpath);
  1758. return NULL;
  1759. }
  1760. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1761. * based on <b>state</b>. Append the hop info to head_ptr.
  1762. */
  1763. static int
  1764. onion_extend_cpath(origin_circuit_t *circ)
  1765. {
  1766. uint8_t purpose = circ->base_.purpose;
  1767. cpath_build_state_t *state = circ->build_state;
  1768. int cur_len = circuit_get_cpath_len(circ);
  1769. extend_info_t *info = NULL;
  1770. if (cur_len >= state->desired_path_len) {
  1771. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1772. state->desired_path_len);
  1773. return 1;
  1774. }
  1775. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1776. state->desired_path_len);
  1777. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1778. info = extend_info_dup(state->chosen_exit);
  1779. } else if (cur_len == 0) { /* picking first node */
  1780. const node_t *r = choose_good_entry_server(purpose, state);
  1781. if (r) {
  1782. /* If we're a client, use the preferred address rather than the
  1783. primary address, for potentially connecting to an IPv6 OR
  1784. port. */
  1785. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  1786. tor_assert(info);
  1787. }
  1788. } else {
  1789. const node_t *r =
  1790. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1791. if (r) {
  1792. info = extend_info_from_node(r, 0);
  1793. tor_assert(info);
  1794. }
  1795. }
  1796. if (!info) {
  1797. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1798. "this circuit.", cur_len);
  1799. return -1;
  1800. }
  1801. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1802. extend_info_describe(info),
  1803. cur_len+1, build_state_get_exit_nickname(state));
  1804. onion_append_hop(&circ->cpath, info);
  1805. extend_info_free(info);
  1806. return 0;
  1807. }
  1808. /** Create a new hop, annotate it with information about its
  1809. * corresponding router <b>choice</b>, and append it to the
  1810. * end of the cpath <b>head_ptr</b>. */
  1811. static int
  1812. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1813. {
  1814. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1815. /* link hop into the cpath, at the end. */
  1816. onion_append_to_cpath(head_ptr, hop);
  1817. hop->magic = CRYPT_PATH_MAGIC;
  1818. hop->state = CPATH_STATE_CLOSED;
  1819. hop->extend_info = extend_info_dup(choice);
  1820. hop->package_window = circuit_initial_package_window();
  1821. hop->deliver_window = CIRCWINDOW_START;
  1822. return 0;
  1823. }
  1824. /** Allocate a new extend_info object based on the various arguments. */
  1825. extend_info_t *
  1826. extend_info_new(const char *nickname, const char *digest,
  1827. crypto_pk_t *onion_key,
  1828. const curve25519_public_key_t *curve25519_key,
  1829. const tor_addr_t *addr, uint16_t port)
  1830. {
  1831. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1832. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1833. if (nickname)
  1834. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1835. if (onion_key)
  1836. info->onion_key = crypto_pk_dup_key(onion_key);
  1837. #ifdef CURVE25519_ENABLED
  1838. if (curve25519_key)
  1839. memcpy(&info->curve25519_onion_key, curve25519_key,
  1840. sizeof(curve25519_public_key_t));
  1841. #else
  1842. (void)curve25519_key;
  1843. #endif
  1844. tor_addr_copy(&info->addr, addr);
  1845. info->port = port;
  1846. return info;
  1847. }
  1848. /** Allocate and return a new extend_info that can be used to build a
  1849. * circuit to or through the node <b>node</b>. Use the primary address
  1850. * of the node (i.e. its IPv4 address) unless
  1851. * <b>for_direct_connect</b> is true, in which case the preferred
  1852. * address is used instead. May return NULL if there is not enough
  1853. * info about <b>node</b> to extend to it--for example, if there is no
  1854. * routerinfo_t or microdesc_t.
  1855. **/
  1856. extend_info_t *
  1857. extend_info_from_node(const node_t *node, int for_direct_connect)
  1858. {
  1859. tor_addr_port_t ap;
  1860. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  1861. return NULL;
  1862. if (for_direct_connect)
  1863. node_get_pref_orport(node, &ap);
  1864. else
  1865. node_get_prim_orport(node, &ap);
  1866. log_debug(LD_CIRC, "using %s for %s",
  1867. fmt_addrport(&ap.addr, ap.port),
  1868. node->ri ? node->ri->nickname : node->rs->nickname);
  1869. if (node->ri)
  1870. return extend_info_new(node->ri->nickname,
  1871. node->identity,
  1872. node->ri->onion_pkey,
  1873. node->ri->onion_curve25519_pkey,
  1874. &ap.addr,
  1875. ap.port);
  1876. else if (node->rs && node->md)
  1877. return extend_info_new(node->rs->nickname,
  1878. node->identity,
  1879. node->md->onion_pkey,
  1880. node->md->onion_curve25519_pkey,
  1881. &ap.addr,
  1882. ap.port);
  1883. else
  1884. return NULL;
  1885. }
  1886. /** Release storage held by an extend_info_t struct. */
  1887. void
  1888. extend_info_free(extend_info_t *info)
  1889. {
  1890. if (!info)
  1891. return;
  1892. crypto_pk_free(info->onion_key);
  1893. tor_free(info);
  1894. }
  1895. /** Allocate and return a new extend_info_t with the same contents as
  1896. * <b>info</b>. */
  1897. extend_info_t *
  1898. extend_info_dup(extend_info_t *info)
  1899. {
  1900. extend_info_t *newinfo;
  1901. tor_assert(info);
  1902. newinfo = tor_malloc(sizeof(extend_info_t));
  1903. memcpy(newinfo, info, sizeof(extend_info_t));
  1904. if (info->onion_key)
  1905. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1906. else
  1907. newinfo->onion_key = NULL;
  1908. return newinfo;
  1909. }
  1910. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1911. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1912. * the chosen exit, return NULL.
  1913. */
  1914. const node_t *
  1915. build_state_get_exit_node(cpath_build_state_t *state)
  1916. {
  1917. if (!state || !state->chosen_exit)
  1918. return NULL;
  1919. return node_get_by_id(state->chosen_exit->identity_digest);
  1920. }
  1921. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1922. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1923. * chosen exit, return NULL.
  1924. */
  1925. const char *
  1926. build_state_get_exit_nickname(cpath_build_state_t *state)
  1927. {
  1928. if (!state || !state->chosen_exit)
  1929. return NULL;
  1930. return state->chosen_exit->nickname;
  1931. }