circuitbuild.c 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  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-2012, 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 "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuitstats.h"
  15. #include "circuituse.h"
  16. #include "command.h"
  17. #include "config.h"
  18. #include "confparse.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "directory.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "onion.h"
  29. #include "onion_tap.h"
  30. #include "onion_fast.h"
  31. #include "policies.h"
  32. #include "transports.h"
  33. #include "relay.h"
  34. #include "rephist.h"
  35. #include "router.h"
  36. #include "routerlist.h"
  37. #include "routerparse.h"
  38. #include "routerset.h"
  39. #include "crypto.h"
  40. #include "connection_edge.h"
  41. #ifndef MIN
  42. #define MIN(a,b) ((a)<(b)?(a):(b))
  43. #endif
  44. /********* START VARIABLES **********/
  45. /** A global list of all circuits at this hop. */
  46. extern circuit_t *global_circuitlist;
  47. /********* END VARIABLES ************/
  48. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  49. uint16_t port,
  50. const char *id_digest);
  51. static int circuit_deliver_create_cell(circuit_t *circ,
  52. const create_cell_t *create_cell,
  53. int relayed);
  54. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  55. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  56. static int onion_extend_cpath(origin_circuit_t *circ);
  57. static int count_acceptable_nodes(smartlist_t *routers);
  58. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  59. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  60. static void pathbias_count_build_success(origin_circuit_t *circ);
  61. static void pathbias_count_successful_close(origin_circuit_t *circ);
  62. static void pathbias_count_collapse(origin_circuit_t *circ);
  63. static void pathbias_count_unusable(origin_circuit_t *circ);
  64. /** This function tries to get a channel to the specified endpoint,
  65. * and then calls command_setup_channel() to give it the right
  66. * callbacks.
  67. */
  68. static channel_t *
  69. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  70. const char *id_digest)
  71. {
  72. channel_t *chan;
  73. chan = channel_connect(addr, port, id_digest);
  74. if (chan) command_setup_channel(chan);
  75. return chan;
  76. }
  77. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  78. * and with the high bit specified by conn-\>circ_id_type, until we get
  79. * a circ_id that is not in use by any other circuit on that conn.
  80. *
  81. * Return it, or 0 if can't get a unique circ_id.
  82. */
  83. static circid_t
  84. get_unique_circ_id_by_chan(channel_t *chan)
  85. {
  86. circid_t test_circ_id;
  87. circid_t attempts=0;
  88. circid_t high_bit;
  89. tor_assert(chan);
  90. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  91. log_warn(LD_BUG,
  92. "Trying to pick a circuit ID for a connection from "
  93. "a client with no identity.");
  94. return 0;
  95. }
  96. high_bit =
  97. (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  98. do {
  99. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  100. * circID such that (high_bit|test_circ_id) is not already used. */
  101. test_circ_id = chan->next_circ_id++;
  102. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  103. test_circ_id = 1;
  104. chan->next_circ_id = 2;
  105. }
  106. if (++attempts > 1<<15) {
  107. /* Make sure we don't loop forever if all circ_id's are used. This
  108. * matters because it's an external DoS opportunity.
  109. */
  110. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  111. return 0;
  112. }
  113. test_circ_id |= high_bit;
  114. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  115. return test_circ_id;
  116. }
  117. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  118. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  119. * list information about link status in a more verbose format using spaces.
  120. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  121. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  122. * names.
  123. */
  124. static char *
  125. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  126. {
  127. crypt_path_t *hop;
  128. smartlist_t *elements;
  129. const char *states[] = {"closed", "waiting for keys", "open"};
  130. char *s;
  131. elements = smartlist_new();
  132. if (verbose) {
  133. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  134. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  135. circ->build_state->is_internal ? "internal" : "exit",
  136. circ->build_state->need_uptime ? " (high-uptime)" : "",
  137. circ->build_state->desired_path_len,
  138. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  139. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  140. (nickname?nickname:"*unnamed*"));
  141. }
  142. hop = circ->cpath;
  143. do {
  144. char *elt;
  145. const char *id;
  146. const node_t *node;
  147. if (!hop)
  148. break;
  149. if (!verbose && hop->state != CPATH_STATE_OPEN)
  150. break;
  151. if (!hop->extend_info)
  152. break;
  153. id = hop->extend_info->identity_digest;
  154. if (verbose_names) {
  155. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  156. if ((node = node_get_by_id(id))) {
  157. node_get_verbose_nickname(node, elt);
  158. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  159. elt[0] = '$';
  160. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  161. elt[HEX_DIGEST_LEN+1]= '~';
  162. strlcpy(elt+HEX_DIGEST_LEN+2,
  163. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  164. } else {
  165. elt[0] = '$';
  166. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  167. }
  168. } else { /* ! verbose_names */
  169. node = node_get_by_id(id);
  170. if (node && node_is_named(node)) {
  171. elt = tor_strdup(node_get_nickname(node));
  172. } else {
  173. elt = tor_malloc(HEX_DIGEST_LEN+2);
  174. elt[0] = '$';
  175. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  176. }
  177. }
  178. tor_assert(elt);
  179. if (verbose) {
  180. tor_assert(hop->state <= 2);
  181. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  182. tor_free(elt);
  183. } else {
  184. smartlist_add(elements, elt);
  185. }
  186. hop = hop->next;
  187. } while (hop != circ->cpath);
  188. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  189. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  190. smartlist_free(elements);
  191. return s;
  192. }
  193. /** If <b>verbose</b> is false, allocate and return a comma-separated
  194. * list of the currently built elements of <b>circ</b>. If
  195. * <b>verbose</b> is true, also list information about link status in
  196. * a more verbose format using spaces.
  197. */
  198. char *
  199. circuit_list_path(origin_circuit_t *circ, int verbose)
  200. {
  201. return circuit_list_path_impl(circ, verbose, 0);
  202. }
  203. /** Allocate and return a comma-separated list of the currently built elements
  204. * of <b>circ</b>, giving each as a verbose nickname.
  205. */
  206. char *
  207. circuit_list_path_for_controller(origin_circuit_t *circ)
  208. {
  209. return circuit_list_path_impl(circ, 0, 1);
  210. }
  211. /** Log, at severity <b>severity</b>, the nicknames of each router in
  212. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  213. * exit point.
  214. */
  215. void
  216. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  217. {
  218. char *s = circuit_list_path(circ,1);
  219. tor_log(severity,domain,"%s",s);
  220. tor_free(s);
  221. }
  222. /** Tell the rep(utation)hist(ory) module about the status of the links
  223. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  224. * extended; the _first_ hop that isn't open (if any) is marked as
  225. * unable to extend.
  226. */
  227. /* XXXX Someday we should learn from OR circuits too. */
  228. void
  229. circuit_rep_hist_note_result(origin_circuit_t *circ)
  230. {
  231. crypt_path_t *hop;
  232. const char *prev_digest = NULL;
  233. hop = circ->cpath;
  234. if (!hop) /* circuit hasn't started building yet. */
  235. return;
  236. if (server_mode(get_options())) {
  237. const routerinfo_t *me = router_get_my_routerinfo();
  238. if (!me)
  239. return;
  240. prev_digest = me->cache_info.identity_digest;
  241. }
  242. do {
  243. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  244. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  245. if (prev_digest) {
  246. if (hop->state == CPATH_STATE_OPEN)
  247. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  248. else {
  249. rep_hist_note_extend_failed(prev_digest, node->identity);
  250. break;
  251. }
  252. }
  253. prev_digest = node->identity;
  254. } else {
  255. prev_digest = NULL;
  256. }
  257. hop=hop->next;
  258. } while (hop!=circ->cpath);
  259. }
  260. /** Pick all the entries in our cpath. Stop and return 0 when we're
  261. * happy, or return -1 if an error occurs. */
  262. static int
  263. onion_populate_cpath(origin_circuit_t *circ)
  264. {
  265. int r;
  266. again:
  267. r = onion_extend_cpath(circ);
  268. if (r < 0) {
  269. log_info(LD_CIRC,"Generating cpath hop failed.");
  270. return -1;
  271. }
  272. if (r == 0)
  273. goto again;
  274. return 0; /* if r == 1 */
  275. }
  276. /** Create and return a new origin circuit. Initialize its purpose and
  277. * build-state based on our arguments. The <b>flags</b> argument is a
  278. * bitfield of CIRCLAUNCH_* flags. */
  279. origin_circuit_t *
  280. origin_circuit_init(uint8_t purpose, int flags)
  281. {
  282. /* sets circ->p_circ_id and circ->p_chan */
  283. origin_circuit_t *circ = origin_circuit_new();
  284. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  285. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  286. circ->build_state->onehop_tunnel =
  287. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  288. circ->build_state->need_uptime =
  289. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  290. circ->build_state->need_capacity =
  291. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  292. circ->build_state->is_internal =
  293. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  294. circ->base_.purpose = purpose;
  295. return circ;
  296. }
  297. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  298. * is defined, then use that as your exit router, else choose a suitable
  299. * exit node.
  300. *
  301. * Also launch a connection to the first OR in the chosen path, if
  302. * it's not open already.
  303. */
  304. origin_circuit_t *
  305. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  306. {
  307. origin_circuit_t *circ;
  308. int err_reason = 0;
  309. circ = origin_circuit_init(purpose, flags);
  310. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  311. onion_populate_cpath(circ) < 0) {
  312. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  313. return NULL;
  314. }
  315. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  316. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  317. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  318. return NULL;
  319. }
  320. return circ;
  321. }
  322. /** Start establishing the first hop of our circuit. Figure out what
  323. * OR we should connect to, and if necessary start the connection to
  324. * it. If we're already connected, then send the 'create' cell.
  325. * Return 0 for ok, -reason if circ should be marked-for-close. */
  326. int
  327. circuit_handle_first_hop(origin_circuit_t *circ)
  328. {
  329. crypt_path_t *firsthop;
  330. channel_t *n_chan;
  331. int err_reason = 0;
  332. const char *msg = NULL;
  333. int should_launch = 0;
  334. firsthop = onion_next_hop_in_cpath(circ->cpath);
  335. tor_assert(firsthop);
  336. tor_assert(firsthop->extend_info);
  337. /* now see if we're already connected to the first OR in 'route' */
  338. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  339. fmt_addrport(&firsthop->extend_info->addr,
  340. firsthop->extend_info->port));
  341. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  342. &firsthop->extend_info->addr,
  343. &msg,
  344. &should_launch);
  345. if (!n_chan) {
  346. /* not currently connected in a useful way. */
  347. log_info(LD_CIRC, "Next router is %s: %s",
  348. safe_str_client(extend_info_describe(firsthop->extend_info)),
  349. msg?msg:"???");
  350. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  351. if (should_launch) {
  352. if (circ->build_state->onehop_tunnel)
  353. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  354. n_chan = channel_connect_for_circuit(
  355. &firsthop->extend_info->addr,
  356. firsthop->extend_info->port,
  357. firsthop->extend_info->identity_digest);
  358. if (!n_chan) { /* connect failed, forget the whole thing */
  359. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  360. return -END_CIRC_REASON_CONNECTFAILED;
  361. }
  362. }
  363. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  364. /* return success. The onion/circuit/etc will be taken care of
  365. * automatically (may already have been) whenever n_chan reaches
  366. * OR_CONN_STATE_OPEN.
  367. */
  368. return 0;
  369. } else { /* it's already open. use it. */
  370. tor_assert(!circ->base_.n_hop);
  371. circ->base_.n_chan = n_chan;
  372. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  373. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  374. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  375. return err_reason;
  376. }
  377. }
  378. return 0;
  379. }
  380. /** Find any circuits that are waiting on <b>or_conn</b> to become
  381. * open and get them to send their create cells forward.
  382. *
  383. * Status is 1 if connect succeeded, or 0 if connect failed.
  384. */
  385. void
  386. circuit_n_chan_done(channel_t *chan, int status)
  387. {
  388. smartlist_t *pending_circs;
  389. int err_reason = 0;
  390. tor_assert(chan);
  391. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  392. chan->nickname ? chan->nickname : "NULL",
  393. channel_get_canonical_remote_descr(chan), status);
  394. pending_circs = smartlist_new();
  395. circuit_get_all_pending_on_channel(pending_circs, chan);
  396. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  397. {
  398. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  399. * leaving them in in case it's possible for the status of a circuit to
  400. * change as we're going down the list. */
  401. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  402. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  403. continue;
  404. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  405. /* Look at addr/port. This is an unkeyed connection. */
  406. if (!channel_matches_extend_info(chan, circ->n_hop))
  407. continue;
  408. } else {
  409. /* We expected a key. See if it's the right one. */
  410. if (tor_memneq(chan->identity_digest,
  411. circ->n_hop->identity_digest, DIGEST_LEN))
  412. continue;
  413. }
  414. if (!status) { /* chan failed; close circ */
  415. log_info(LD_CIRC,"Channel failed; closing circ.");
  416. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  417. continue;
  418. }
  419. log_debug(LD_CIRC, "Found circ, sending create cell.");
  420. /* circuit_deliver_create_cell will set n_circ_id and add us to
  421. * chan_circuid_circuit_map, so we don't need to call
  422. * set_circid_chan here. */
  423. circ->n_chan = chan;
  424. extend_info_free(circ->n_hop);
  425. circ->n_hop = NULL;
  426. if (CIRCUIT_IS_ORIGIN(circ)) {
  427. if ((err_reason =
  428. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  429. log_info(LD_CIRC,
  430. "send_next_onion_skin failed; circuit marked for closing.");
  431. circuit_mark_for_close(circ, -err_reason);
  432. continue;
  433. /* XXX could this be bad, eg if next_onion_skin failed because conn
  434. * died? */
  435. }
  436. } else {
  437. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  438. tor_assert(circ->n_chan_create_cell);
  439. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  440. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  441. continue;
  442. }
  443. tor_free(circ->n_chan_create_cell);
  444. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  445. }
  446. }
  447. SMARTLIST_FOREACH_END(circ);
  448. smartlist_free(pending_circs);
  449. }
  450. /** Find a new circid that isn't currently in use on the circ->n_chan
  451. * for the outgoing
  452. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  453. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  454. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  455. * it. Return -1 if we failed to find a suitable circid, else return 0.
  456. */
  457. static int
  458. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  459. int relayed)
  460. {
  461. cell_t cell;
  462. circid_t id;
  463. int r;
  464. tor_assert(circ);
  465. tor_assert(circ->n_chan);
  466. tor_assert(create_cell);
  467. tor_assert(create_cell->cell_type == CELL_CREATE ||
  468. create_cell->cell_type == CELL_CREATE_FAST ||
  469. create_cell->cell_type == CELL_CREATE2);
  470. id = get_unique_circ_id_by_chan(circ->n_chan);
  471. if (!id) {
  472. log_warn(LD_CIRC,"failed to get unique circID.");
  473. return -1;
  474. }
  475. log_debug(LD_CIRC,"Chosen circID %u.", id);
  476. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  477. memset(&cell, 0, sizeof(cell_t));
  478. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  479. : create_cell_format(&cell, create_cell);
  480. if (r < 0) {
  481. log_warn(LD_CIRC,"Couldn't format create cell");
  482. return -1;
  483. }
  484. cell.circ_id = circ->n_circ_id;
  485. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  486. CELL_DIRECTION_OUT, 0);
  487. if (CIRCUIT_IS_ORIGIN(circ)) {
  488. /* Update began timestamp for circuits starting their first hop */
  489. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  490. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  491. log_warn(LD_CIRC,
  492. "Got first hop for a circuit without an opened channel. "
  493. "State: %s.", channel_state_to_string(circ->n_chan->state));
  494. tor_fragile_assert();
  495. }
  496. tor_gettimeofday(&circ->timestamp_began);
  497. }
  498. /* mark it so it gets better rate limiting treatment. */
  499. channel_timestamp_client(circ->n_chan);
  500. }
  501. return 0;
  502. }
  503. /** We've decided to start our reachability testing. If all
  504. * is set, log this to the user. Return 1 if we did, or 0 if
  505. * we chose not to log anything. */
  506. int
  507. inform_testing_reachability(void)
  508. {
  509. char dirbuf[128];
  510. const routerinfo_t *me = router_get_my_routerinfo();
  511. if (!me)
  512. return 0;
  513. control_event_server_status(LOG_NOTICE,
  514. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  515. me->address, me->or_port);
  516. if (me->dir_port) {
  517. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  518. me->address, me->dir_port);
  519. control_event_server_status(LOG_NOTICE,
  520. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  521. me->address, me->dir_port);
  522. }
  523. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  524. "(this may take up to %d minutes -- look for log "
  525. "messages indicating success)",
  526. me->address, me->or_port,
  527. me->dir_port ? dirbuf : "",
  528. me->dir_port ? "are" : "is",
  529. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  530. return 1;
  531. }
  532. /** Return true iff we should send a create_fast cell to start building a given
  533. * circuit */
  534. static INLINE int
  535. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  536. {
  537. const or_options_t *options = get_options();
  538. tor_assert(circ->cpath);
  539. tor_assert(circ->cpath->extend_info);
  540. if (!circ->cpath->extend_info->onion_key)
  541. return 1; /* our hand is forced: only a create_fast will work. */
  542. if (!options->FastFirstHopPK)
  543. return 0; /* we prefer to avoid create_fast */
  544. if (public_server_mode(options)) {
  545. /* We're a server, and we know an onion key. We can choose.
  546. * Prefer to blend our circuit into the other circuits we are
  547. * creating on behalf of others. */
  548. return 0;
  549. }
  550. return 1;
  551. }
  552. /** Return true if <b>circ</b> is the type of circuit we want to count
  553. * timeouts from. In particular, we want it to have not completed yet
  554. * (already completing indicates we cannibalized it), and we want it to
  555. * have exactly three hops.
  556. */
  557. int
  558. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  559. {
  560. return !circ->has_opened
  561. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  562. }
  563. #ifdef CURVE25519_ENABLED
  564. /** Return true if the ntor handshake is enabled in the configuration, or if
  565. * it's been set to "auto" in the configuration and it's enabled in the
  566. * consensus. */
  567. static int
  568. circuits_can_use_ntor(void)
  569. {
  570. const or_options_t *options = get_options();
  571. if (options->UseNTorHandshake != -1)
  572. return options->UseNTorHandshake;
  573. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  574. }
  575. #endif
  576. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  577. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  578. * accordingly. */
  579. static void
  580. circuit_pick_create_handshake(uint8_t *cell_type_out,
  581. uint16_t *handshake_type_out,
  582. const extend_info_t *ei)
  583. {
  584. #ifdef CURVE25519_ENABLED
  585. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  586. CURVE25519_PUBKEY_LEN) &&
  587. circuits_can_use_ntor()) {
  588. *cell_type_out = CELL_CREATE2;
  589. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  590. return;
  591. }
  592. #else
  593. (void) ei;
  594. #endif
  595. *cell_type_out = CELL_CREATE;
  596. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  597. }
  598. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  599. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  600. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  601. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  602. * *<b>create_cell_type_out</b> accordingly. */
  603. static void
  604. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  605. uint8_t *create_cell_type_out,
  606. uint16_t *handshake_type_out,
  607. const node_t *node_prev,
  608. const extend_info_t *ei)
  609. {
  610. uint8_t t;
  611. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  612. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  613. * proxy for whether it can do extend2 cells; once a version that
  614. * handles extend2 cells is out, remove it. */
  615. if (node_prev &&
  616. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  617. (node_has_curve25519_onion_key(node_prev) ||
  618. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  619. *cell_type_out = RELAY_COMMAND_EXTEND2;
  620. *create_cell_type_out = CELL_CREATE2;
  621. } else {
  622. *cell_type_out = RELAY_COMMAND_EXTEND;
  623. *create_cell_type_out = CELL_CREATE;
  624. }
  625. }
  626. /** This is the backbone function for building circuits.
  627. *
  628. * If circ's first hop is closed, then we need to build a create
  629. * cell and send it forward.
  630. *
  631. * Otherwise, we need to build a relay extend cell and send it
  632. * forward.
  633. *
  634. * Return -reason if we want to tear down circ, else return 0.
  635. */
  636. int
  637. circuit_send_next_onion_skin(origin_circuit_t *circ)
  638. {
  639. crypt_path_t *hop;
  640. const node_t *node;
  641. tor_assert(circ);
  642. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  643. /* This is the first hop. */
  644. create_cell_t cc;
  645. int fast;
  646. int len;
  647. log_debug(LD_CIRC,"First skin; sending create cell.");
  648. memset(&cc, 0, sizeof(cc));
  649. if (circ->build_state->onehop_tunnel)
  650. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  651. else
  652. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  653. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  654. fast = should_use_create_fast_for_circuit(circ);
  655. if (!fast) {
  656. /* We are an OR and we know the right onion key: we should
  657. * send a create cell.
  658. */
  659. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  660. circ->cpath->extend_info);
  661. note_request("cell: create", 1);
  662. } else {
  663. /* We are not an OR, and we're building the first hop of a circuit to a
  664. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  665. * and a DH operation. */
  666. cc.cell_type = CELL_CREATE_FAST;
  667. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  668. note_request("cell: create fast", 1);
  669. }
  670. len = onion_skin_create(cc.handshake_type,
  671. circ->cpath->extend_info,
  672. &circ->cpath->handshake_state,
  673. cc.onionskin);
  674. if (len < 0) {
  675. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  676. return - END_CIRC_REASON_INTERNAL;
  677. }
  678. cc.handshake_len = len;
  679. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  680. return - END_CIRC_REASON_RESOURCELIMIT;
  681. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  682. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  683. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  684. fast ? "CREATE_FAST" : "CREATE",
  685. node ? node_describe(node) : "<unnamed>");
  686. } else {
  687. extend_cell_t ec;
  688. int len;
  689. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  690. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  691. log_debug(LD_CIRC,"starting to send subsequent skin.");
  692. hop = onion_next_hop_in_cpath(circ->cpath);
  693. memset(&ec, 0, sizeof(ec));
  694. if (!hop) {
  695. /* done building the circuit. whew. */
  696. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  697. if (circuit_timeout_want_to_count_circ(circ)) {
  698. struct timeval end;
  699. long timediff;
  700. tor_gettimeofday(&end);
  701. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  702. /*
  703. * If the circuit build time is much greater than we would have cut
  704. * it off at, we probably had a suspend event along this codepath,
  705. * and we should discard the value.
  706. */
  707. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  708. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  709. "Assuming clock jump. Purpose %d (%s)", timediff,
  710. circ->base_.purpose,
  711. circuit_purpose_to_string(circ->base_.purpose));
  712. } else if (!circuit_build_times_disabled()) {
  713. /* Only count circuit times if the network is live */
  714. if (circuit_build_times_network_check_live(&circ_times)) {
  715. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  716. circuit_build_times_set_timeout(&circ_times);
  717. }
  718. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  719. circuit_build_times_network_circ_success(&circ_times);
  720. }
  721. }
  722. }
  723. log_info(LD_CIRC,"circuit built!");
  724. circuit_reset_failure_count(0);
  725. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  726. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  727. }
  728. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  729. const or_options_t *options = get_options();
  730. can_complete_circuit=1;
  731. /* FFFF Log a count of known routers here */
  732. log_notice(LD_GENERAL,
  733. "Tor has successfully opened a circuit. "
  734. "Looks like client functionality is working.");
  735. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  736. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  737. clear_broken_connection_map(1);
  738. if (server_mode(options) && !check_whether_orport_reachable()) {
  739. inform_testing_reachability();
  740. consider_testing_reachability(1, 1);
  741. }
  742. }
  743. pathbias_count_build_success(circ);
  744. circuit_rep_hist_note_result(circ);
  745. circuit_has_opened(circ); /* do other actions as necessary */
  746. /* We're done with measurement circuits here. Just close them */
  747. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  748. /* If a measurement circ ever gets back to us, consider it
  749. * succeeded for path bias */
  750. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  751. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  752. }
  753. return 0;
  754. }
  755. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  756. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  757. return - END_CIRC_REASON_INTERNAL;
  758. }
  759. {
  760. const node_t *prev_node;
  761. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  762. circuit_pick_extend_handshake(&ec.cell_type,
  763. &ec.create_cell.cell_type,
  764. &ec.create_cell.handshake_type,
  765. prev_node,
  766. hop->extend_info);
  767. }
  768. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  769. ec.orport_ipv4.port = hop->extend_info->port;
  770. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  771. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  772. len = onion_skin_create(ec.create_cell.handshake_type,
  773. hop->extend_info,
  774. &hop->handshake_state,
  775. ec.create_cell.onionskin);
  776. if (len < 0) {
  777. log_warn(LD_CIRC,"onion_skin_create failed.");
  778. return - END_CIRC_REASON_INTERNAL;
  779. }
  780. ec.create_cell.handshake_len = len;
  781. log_info(LD_CIRC,"Sending extend relay cell.");
  782. note_request("cell: extend", 1);
  783. {
  784. uint8_t command = 0;
  785. uint16_t payload_len=0;
  786. uint8_t payload[RELAY_PAYLOAD_SIZE];
  787. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  788. log_warn(LD_CIRC,"Couldn't format extend cell");
  789. return -END_CIRC_REASON_INTERNAL;
  790. }
  791. /* send it to hop->prev, because it will transfer
  792. * it to a create cell and then send to hop */
  793. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  794. command,
  795. (char*)payload, payload_len,
  796. hop->prev) < 0)
  797. return 0; /* circuit is closed */
  798. }
  799. hop->state = CPATH_STATE_AWAITING_KEYS;
  800. }
  801. return 0;
  802. }
  803. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  804. * something has also gone wrong with our network: notify the user,
  805. * and abandon all not-yet-used circuits. */
  806. void
  807. circuit_note_clock_jumped(int seconds_elapsed)
  808. {
  809. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  810. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  811. "assuming established circuits no longer work.",
  812. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  813. seconds_elapsed >=0 ? "forward" : "backward");
  814. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  815. seconds_elapsed);
  816. can_complete_circuit=0; /* so it'll log when it works again */
  817. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  818. "CLOCK_JUMPED");
  819. circuit_mark_all_unused_circs();
  820. circuit_expire_all_dirty_circs();
  821. }
  822. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  823. * skin and identity digest for the next hop. If we're already connected,
  824. * pass the onion skin to the next hop using a create cell; otherwise
  825. * launch a new OR connection, and <b>circ</b> will notice when the
  826. * connection succeeds or fails.
  827. *
  828. * Return -1 if we want to warn and tear down the circuit, else return 0.
  829. */
  830. int
  831. circuit_extend(cell_t *cell, circuit_t *circ)
  832. {
  833. channel_t *n_chan;
  834. relay_header_t rh;
  835. extend_cell_t ec;
  836. const char *msg = NULL;
  837. int should_launch = 0;
  838. if (circ->n_chan) {
  839. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  840. "n_chan already set. Bug/attack. Closing.");
  841. return -1;
  842. }
  843. if (circ->n_hop) {
  844. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  845. "conn to next hop already launched. Bug/attack. Closing.");
  846. return -1;
  847. }
  848. if (!server_mode(get_options())) {
  849. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  850. "Got an extend cell, but running as a client. Closing.");
  851. return -1;
  852. }
  853. relay_header_unpack(&rh, cell->payload);
  854. if (extend_cell_parse(&ec, rh.command,
  855. cell->payload+RELAY_HEADER_SIZE,
  856. rh.length) < 0) {
  857. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  858. "Can't parse extend cell. Closing circuit.");
  859. return -1;
  860. }
  861. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  862. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  863. "Client asked me to extend to zero destination port or addr.");
  864. return -1;
  865. }
  866. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  867. !get_options()->ExtendAllowPrivateAddresses) {
  868. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  869. "Client asked me to extend to a private address");
  870. return -1;
  871. }
  872. /* Check if they asked us for 0000..0000. We support using
  873. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  874. * but we don't want to let people send us extend cells for empty
  875. * fingerprints -- a) because it opens the user up to a mitm attack,
  876. * and b) because it lets an attacker force the relay to hold open a
  877. * new TLS connection for each extend request. */
  878. if (tor_digest_is_zero((const char*)ec.node_id)) {
  879. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  880. "Client asked me to extend without specifying an id_digest.");
  881. return -1;
  882. }
  883. /* Next, check if we're being asked to connect to the hop that the
  884. * extend cell came from. There isn't any reason for that, and it can
  885. * assist circular-path attacks. */
  886. if (tor_memeq(ec.node_id,
  887. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  888. DIGEST_LEN)) {
  889. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  890. "Client asked me to extend back to the previous hop.");
  891. return -1;
  892. }
  893. n_chan = channel_get_for_extend((const char*)ec.node_id,
  894. &ec.orport_ipv4.addr,
  895. &msg,
  896. &should_launch);
  897. if (!n_chan) {
  898. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  899. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  900. msg?msg:"????");
  901. circ->n_hop = extend_info_new(NULL /*nickname*/,
  902. (const char*)ec.node_id,
  903. NULL /*onion_key*/,
  904. NULL /*curve25519_key*/,
  905. &ec.orport_ipv4.addr,
  906. ec.orport_ipv4.port);
  907. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  908. sizeof(ec.create_cell));
  909. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  910. if (should_launch) {
  911. /* we should try to open a connection */
  912. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  913. ec.orport_ipv4.port,
  914. (const char*)ec.node_id);
  915. if (!n_chan) {
  916. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  917. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  918. return 0;
  919. }
  920. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  921. }
  922. /* return success. The onion/circuit/etc will be taken care of
  923. * automatically (may already have been) whenever n_chan reaches
  924. * OR_CONN_STATE_OPEN.
  925. */
  926. return 0;
  927. }
  928. tor_assert(!circ->n_hop); /* Connection is already established. */
  929. circ->n_chan = n_chan;
  930. log_debug(LD_CIRC,
  931. "n_chan is %s",
  932. channel_get_canonical_remote_descr(n_chan));
  933. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  934. return -1;
  935. return 0;
  936. }
  937. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  938. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  939. * used as follows:
  940. * - 20 to initialize f_digest
  941. * - 20 to initialize b_digest
  942. * - 16 to key f_crypto
  943. * - 16 to key b_crypto
  944. *
  945. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  946. */
  947. int
  948. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  949. int reverse)
  950. {
  951. crypto_digest_t *tmp_digest;
  952. crypto_cipher_t *tmp_crypto;
  953. tor_assert(cpath);
  954. tor_assert(key_data);
  955. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  956. cpath->f_digest || cpath->b_digest));
  957. cpath->f_digest = crypto_digest_new();
  958. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  959. cpath->b_digest = crypto_digest_new();
  960. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  961. if (!(cpath->f_crypto =
  962. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  963. log_warn(LD_BUG,"Forward cipher initialization failed.");
  964. return -1;
  965. }
  966. if (!(cpath->b_crypto =
  967. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  968. log_warn(LD_BUG,"Backward cipher initialization failed.");
  969. return -1;
  970. }
  971. if (reverse) {
  972. tmp_digest = cpath->f_digest;
  973. cpath->f_digest = cpath->b_digest;
  974. cpath->b_digest = tmp_digest;
  975. tmp_crypto = cpath->f_crypto;
  976. cpath->f_crypto = cpath->b_crypto;
  977. cpath->b_crypto = tmp_crypto;
  978. }
  979. return 0;
  980. }
  981. /** The minimum number of circuit attempts before we start
  982. * thinking about warning about path bias and dropping guards */
  983. static int
  984. pathbias_get_min_circs(const or_options_t *options)
  985. {
  986. #define DFLT_PATH_BIAS_MIN_CIRC 150
  987. if (options->PathBiasCircThreshold >= 5)
  988. return options->PathBiasCircThreshold;
  989. else
  990. return networkstatus_get_param(NULL, "pb_mincircs",
  991. DFLT_PATH_BIAS_MIN_CIRC,
  992. 5, INT32_MAX);
  993. }
  994. /** The circuit success rate below which we issue a notice */
  995. static double
  996. pathbias_get_notice_rate(const or_options_t *options)
  997. {
  998. #define DFLT_PATH_BIAS_NOTICE_PCT 70
  999. if (options->PathBiasNoticeRate >= 0.0)
  1000. return options->PathBiasNoticeRate;
  1001. else
  1002. return networkstatus_get_param(NULL, "pb_noticepct",
  1003. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  1004. }
  1005. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1006. /** The circuit success rate below which we issue a warn */
  1007. static double
  1008. pathbias_get_warn_rate(const or_options_t *options)
  1009. {
  1010. #define DFLT_PATH_BIAS_WARN_PCT 50
  1011. if (options->PathBiasWarnRate >= 0.0)
  1012. return options->PathBiasWarnRate;
  1013. else
  1014. return networkstatus_get_param(NULL, "pb_warnpct",
  1015. DFLT_PATH_BIAS_WARN_PCT, 0, 100)/100.0;
  1016. }
  1017. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1018. /**
  1019. * The extreme rate is the rate at which we would drop the guard,
  1020. * if pb_dropguard is also set. Otherwise we just warn.
  1021. */
  1022. double
  1023. pathbias_get_extreme_rate(const or_options_t *options)
  1024. {
  1025. #define DFLT_PATH_BIAS_EXTREME_PCT 30
  1026. if (options->PathBiasExtremeRate >= 0.0)
  1027. return options->PathBiasExtremeRate;
  1028. else
  1029. return networkstatus_get_param(NULL, "pb_extremepct",
  1030. DFLT_PATH_BIAS_EXTREME_PCT, 0, 100)/100.0;
  1031. }
  1032. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1033. /**
  1034. * If 1, we actually disable use of guards that fall below
  1035. * the extreme_pct.
  1036. */
  1037. int
  1038. pathbias_get_dropguards(const or_options_t *options)
  1039. {
  1040. #define DFLT_PATH_BIAS_DROP_GUARDS 0
  1041. if (options->PathBiasDropGuards >= 0)
  1042. return options->PathBiasDropGuards;
  1043. else
  1044. return networkstatus_get_param(NULL, "pb_dropguards",
  1045. DFLT_PATH_BIAS_DROP_GUARDS, 0, 1);
  1046. }
  1047. /**
  1048. * This is the number of circuits at which we scale our
  1049. * counts by mult_factor/scale_factor. Note, this count is
  1050. * not exact, as we only perform the scaling in the event
  1051. * of no integer truncation.
  1052. */
  1053. static int
  1054. pathbias_get_scale_threshold(const or_options_t *options)
  1055. {
  1056. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
  1057. if (options->PathBiasScaleThreshold >= 10)
  1058. return options->PathBiasScaleThreshold;
  1059. else
  1060. return networkstatus_get_param(NULL, "pb_scalecircs",
  1061. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  1062. INT32_MAX);
  1063. }
  1064. /**
  1065. * The scale factor is the denominator for our scaling
  1066. * of circuit counts for our path bias window.
  1067. *
  1068. * Note that our use of doubles for the path bias state
  1069. * file means that powers of 2 work best here.
  1070. */
  1071. static int
  1072. pathbias_get_scale_factor(const or_options_t *options)
  1073. {
  1074. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  1075. if (options->PathBiasScaleFactor >= 1)
  1076. return options->PathBiasScaleFactor;
  1077. else
  1078. return networkstatus_get_param(NULL, "pb_scalefactor",
  1079. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  1080. }
  1081. /**
  1082. * The mult factor is the numerator for our scaling
  1083. * of circuit counts for our path bias window. It
  1084. * allows us to scale by fractions.
  1085. */
  1086. static int
  1087. pathbias_get_mult_factor(const or_options_t *options)
  1088. {
  1089. #define DFLT_PATH_BIAS_MULT_FACTOR 1
  1090. if (options->PathBiasMultFactor >= 1)
  1091. return options->PathBiasMultFactor;
  1092. else
  1093. return networkstatus_get_param(NULL, "pb_multfactor",
  1094. DFLT_PATH_BIAS_MULT_FACTOR, 1,
  1095. pathbias_get_scale_factor(options));
  1096. }
  1097. /**
  1098. * If this parameter is set to a true value (default), we use the
  1099. * successful_circuits_closed. Otherwise, we use the success_count.
  1100. */
  1101. static int
  1102. pathbias_use_close_counts(const or_options_t *options)
  1103. {
  1104. #define DFLT_PATH_BIAS_USE_CLOSE_COUNTS 1
  1105. if (options->PathBiasUseCloseCounts >= 0)
  1106. return options->PathBiasUseCloseCounts;
  1107. else
  1108. return networkstatus_get_param(NULL, "pb_useclosecounts",
  1109. DFLT_PATH_BIAS_USE_CLOSE_COUNTS, 0, 1);
  1110. }
  1111. /**
  1112. * Convert a Guard's path state to string.
  1113. */
  1114. static const char *
  1115. pathbias_state_to_string(path_state_t state)
  1116. {
  1117. switch (state) {
  1118. case PATH_STATE_NEW_CIRC:
  1119. return "new";
  1120. case PATH_STATE_BUILD_ATTEMPTED:
  1121. return "build attempted";
  1122. case PATH_STATE_BUILD_SUCCEEDED:
  1123. return "build succeeded";
  1124. case PATH_STATE_USE_SUCCEEDED:
  1125. return "use succeeded";
  1126. case PATH_STATE_USE_FAILED:
  1127. return "use failed";
  1128. }
  1129. return "unknown";
  1130. }
  1131. /**
  1132. * This function decides if a circuit has progressed far enough to count
  1133. * as a circuit "attempt". As long as end-to-end tagging is possible,
  1134. * we assume the adversary will use it over hop-to-hop failure. Therefore,
  1135. * we only need to account bias for the last hop. This should make us
  1136. * much more resilient to ambient circuit failure, and also make that
  1137. * failure easier to measure (we only need to measure Exit failure rates).
  1138. */
  1139. static int
  1140. pathbias_is_new_circ_attempt(origin_circuit_t *circ)
  1141. {
  1142. #define N2N_TAGGING_IS_POSSIBLE
  1143. #ifdef N2N_TAGGING_IS_POSSIBLE
  1144. /* cpath is a circular list. We want circs with more than one hop,
  1145. * and the second hop must be waiting for keys still (it's just
  1146. * about to get them). */
  1147. return circ->cpath->next != circ->cpath &&
  1148. circ->cpath->next->state == CPATH_STATE_AWAITING_KEYS;
  1149. #else
  1150. /* If tagging attacks are no longer possible, we probably want to
  1151. * count bias from the first hop. However, one could argue that
  1152. * timing-based tagging is still more useful than per-hop failure.
  1153. * In which case, we'd never want to use this.
  1154. */
  1155. return circ->cpath->state == CPATH_STATE_AWAITING_KEYS;
  1156. #endif
  1157. }
  1158. /**
  1159. * Decide if the path bias code should count a circuit.
  1160. *
  1161. * @returns 1 if we should count it, 0 otherwise.
  1162. */
  1163. static int
  1164. pathbias_should_count(origin_circuit_t *circ)
  1165. {
  1166. #define PATHBIAS_COUNT_INTERVAL (600)
  1167. static ratelim_t count_limit =
  1168. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  1169. char *rate_msg = NULL;
  1170. /* We can't do path bias accounting without entry guards.
  1171. * Testing and controller circuits also have no guards.
  1172. *
  1173. * We also don't count server-side rends, because their
  1174. * endpoint could be chosen maliciously.
  1175. * Similarly, we can't count client-side intro attempts,
  1176. * because clients can be manipulated into connecting to
  1177. * malicious intro points. */
  1178. if (get_options()->UseEntryGuards == 0 ||
  1179. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1180. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  1181. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1182. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  1183. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1184. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  1185. return 0;
  1186. }
  1187. /* Completely ignore one hop circuits */
  1188. if (circ->build_state->onehop_tunnel ||
  1189. circ->build_state->desired_path_len == 1) {
  1190. /* Check for inconsistency */
  1191. if (circ->build_state->desired_path_len != 1 ||
  1192. !circ->build_state->onehop_tunnel) {
  1193. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  1194. log_notice(LD_BUG,
  1195. "One-hop circuit has length %d. Path state is %s. "
  1196. "Circuit is a %s currently %s.%s",
  1197. circ->build_state->desired_path_len,
  1198. pathbias_state_to_string(circ->path_state),
  1199. circuit_purpose_to_string(circ->base_.purpose),
  1200. circuit_state_to_string(circ->base_.state),
  1201. rate_msg);
  1202. tor_free(rate_msg);
  1203. }
  1204. tor_fragile_assert();
  1205. }
  1206. return 0;
  1207. }
  1208. return 1;
  1209. }
  1210. /**
  1211. * Check our circuit state to see if this is a successful circuit attempt.
  1212. * If so, record it in the current guard's path bias circ_attempt count.
  1213. *
  1214. * Also check for several potential error cases for bug #6475.
  1215. */
  1216. static int
  1217. pathbias_count_circ_attempt(origin_circuit_t *circ)
  1218. {
  1219. #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
  1220. static ratelim_t circ_attempt_notice_limit =
  1221. RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL);
  1222. char *rate_msg = NULL;
  1223. if (!pathbias_should_count(circ)) {
  1224. return 0;
  1225. }
  1226. if (pathbias_is_new_circ_attempt(circ)) {
  1227. /* Help track down the real cause of bug #6475: */
  1228. if (circ->has_opened && circ->path_state != PATH_STATE_BUILD_ATTEMPTED) {
  1229. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1230. approx_time()))) {
  1231. log_info(LD_BUG,
  1232. "Opened circuit is in strange path state %s. "
  1233. "Circuit is a %s currently %s.%s",
  1234. pathbias_state_to_string(circ->path_state),
  1235. circuit_purpose_to_string(circ->base_.purpose),
  1236. circuit_state_to_string(circ->base_.state),
  1237. rate_msg);
  1238. tor_free(rate_msg);
  1239. }
  1240. }
  1241. /* Don't re-count cannibalized circs.. */
  1242. if (!circ->has_opened) {
  1243. entry_guard_t *guard = NULL;
  1244. if (circ->cpath && circ->cpath->extend_info) {
  1245. guard = entry_guard_get_by_id_digest(
  1246. circ->cpath->extend_info->identity_digest);
  1247. } else if (circ->base_.n_chan) {
  1248. guard =
  1249. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1250. }
  1251. if (guard) {
  1252. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1253. circ->path_state = PATH_STATE_BUILD_ATTEMPTED;
  1254. if (entry_guard_inc_circ_attempt_count(guard) < 0) {
  1255. /* Bogus guard; we already warned. */
  1256. return -END_CIRC_REASON_TORPROTOCOL;
  1257. }
  1258. } else {
  1259. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1260. approx_time()))) {
  1261. log_info(LD_BUG,
  1262. "Unopened circuit has strange path state %s. "
  1263. "Circuit is a %s currently %s.%s",
  1264. pathbias_state_to_string(circ->path_state),
  1265. circuit_purpose_to_string(circ->base_.purpose),
  1266. circuit_state_to_string(circ->base_.state),
  1267. rate_msg);
  1268. tor_free(rate_msg);
  1269. }
  1270. }
  1271. } else {
  1272. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1273. approx_time()))) {
  1274. log_info(LD_CIRC,
  1275. "Unopened circuit has no known guard. "
  1276. "Circuit is a %s currently %s.%s",
  1277. circuit_purpose_to_string(circ->base_.purpose),
  1278. circuit_state_to_string(circ->base_.state),
  1279. rate_msg);
  1280. tor_free(rate_msg);
  1281. }
  1282. }
  1283. }
  1284. }
  1285. return 0;
  1286. }
  1287. /**
  1288. * Check our circuit state to see if this is a successful circuit
  1289. * completion. If so, record it in the current guard's path bias
  1290. * success count.
  1291. *
  1292. * Also check for several potential error cases for bug #6475.
  1293. */
  1294. static void
  1295. pathbias_count_build_success(origin_circuit_t *circ)
  1296. {
  1297. #define SUCCESS_NOTICE_INTERVAL (600)
  1298. static ratelim_t success_notice_limit =
  1299. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1300. char *rate_msg = NULL;
  1301. entry_guard_t *guard = NULL;
  1302. if (!pathbias_should_count(circ)) {
  1303. return;
  1304. }
  1305. /* Don't count cannibalized/reused circs for path bias
  1306. * build success.. They get counted under use success */
  1307. if (!circ->has_opened) {
  1308. if (circ->cpath && circ->cpath->extend_info) {
  1309. guard = entry_guard_get_by_id_digest(
  1310. circ->cpath->extend_info->identity_digest);
  1311. }
  1312. if (guard) {
  1313. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  1314. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  1315. guard->circ_successes++;
  1316. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  1317. guard->circ_successes, guard->circ_attempts,
  1318. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1319. } else {
  1320. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1321. approx_time()))) {
  1322. log_info(LD_BUG,
  1323. "Succeeded circuit is in strange path state %s. "
  1324. "Circuit is a %s currently %s.%s",
  1325. pathbias_state_to_string(circ->path_state),
  1326. circuit_purpose_to_string(circ->base_.purpose),
  1327. circuit_state_to_string(circ->base_.state),
  1328. rate_msg);
  1329. tor_free(rate_msg);
  1330. }
  1331. }
  1332. if (guard->circ_attempts < guard->circ_successes) {
  1333. log_notice(LD_BUG, "Unexpectedly high successes counts (%f/%f) "
  1334. "for guard %s=%s",
  1335. guard->circ_successes, guard->circ_attempts,
  1336. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1337. }
  1338. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1339. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1340. * No need to log that case. */
  1341. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1342. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1343. approx_time()))) {
  1344. log_info(LD_CIRC,
  1345. "Completed circuit has no known guard. "
  1346. "Circuit is a %s currently %s.%s",
  1347. circuit_purpose_to_string(circ->base_.purpose),
  1348. circuit_state_to_string(circ->base_.state),
  1349. rate_msg);
  1350. tor_free(rate_msg);
  1351. }
  1352. }
  1353. } else {
  1354. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1355. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1356. approx_time()))) {
  1357. log_info(LD_BUG,
  1358. "Opened circuit is in strange path state %s. "
  1359. "Circuit is a %s currently %s.%s",
  1360. pathbias_state_to_string(circ->path_state),
  1361. circuit_purpose_to_string(circ->base_.purpose),
  1362. circuit_state_to_string(circ->base_.state),
  1363. rate_msg);
  1364. tor_free(rate_msg);
  1365. }
  1366. }
  1367. }
  1368. }
  1369. /**
  1370. * Send a probe down a circuit that wasn't usable.
  1371. *
  1372. * Returns -1 if we couldn't probe, 0 otherwise.
  1373. */
  1374. static int
  1375. pathbias_send_usable_probe(circuit_t *circ)
  1376. {
  1377. /* Based on connection_ap_handshake_send_begin() */
  1378. char payload[CELL_PAYLOAD_SIZE];
  1379. int payload_len;
  1380. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1381. crypt_path_t *cpath_layer = NULL;
  1382. // XXX: Generate a random 0.a.b.c adddress
  1383. const char *probe_nonce = "0.1.2.3";
  1384. tor_assert(ocirc);
  1385. cpath_layer = ocirc->cpath->prev;
  1386. if (cpath_layer->state != CPATH_STATE_OPEN) {
  1387. /* This can happen for cannibalized circuits. Their
  1388. * last hop isn't yet open */
  1389. log_info(LD_CIRC,
  1390. "Got pathbias probe request for unopened circuit %d. "
  1391. "Opened %d, len %d", ocirc->global_identifier,
  1392. ocirc->has_opened, ocirc->build_state->desired_path_len);
  1393. return -1;
  1394. }
  1395. /* We already went down this road. */
  1396. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING &&
  1397. ocirc->pathbias_probe_id) {
  1398. log_info(LD_CIRC,
  1399. "Got pathbias probe request for circuit %d with "
  1400. "outstanding probe", ocirc->global_identifier);
  1401. return -1;
  1402. }
  1403. circuit_change_purpose(circ, CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1404. /* Update timestamp for circuit_expire_building to kill us */
  1405. tor_gettimeofday(&circ->timestamp_began);
  1406. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:25", probe_nonce);
  1407. tor_addr_parse(&ocirc->pathbias_probe_nonce, probe_nonce);
  1408. payload_len = (int)strlen(payload)+1;
  1409. // XXX: need this? Can we assume ipv4 will always be supported?
  1410. // If not, how do we tell?
  1411. //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  1412. // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  1413. // payload_len += 4;
  1414. //}
  1415. /* Generate+Store stream id, make sure it's non-zero */
  1416. ocirc->pathbias_probe_id = get_unique_stream_id_by_circ(ocirc);
  1417. if (ocirc->pathbias_probe_id==0) {
  1418. log_warn(LD_CIRC,
  1419. "Ran out of stream IDs on circuit %u during "
  1420. "pathbias probe attempt.", ocirc->global_identifier);
  1421. return -1;
  1422. }
  1423. log_info(LD_CIRC,
  1424. "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
  1425. probe_nonce, ocirc->pathbias_probe_id, ocirc->global_identifier);
  1426. /* Send a test relay cell */
  1427. if (relay_send_command_from_edge(ocirc->pathbias_probe_id, circ,
  1428. RELAY_COMMAND_BEGIN, payload,
  1429. payload_len, cpath_layer) < 0) {
  1430. log_notice(LD_CIRC,
  1431. "Failed to send pathbias probe cell on circuit %d.",
  1432. ocirc->global_identifier);
  1433. return -1;
  1434. }
  1435. /* Mark it freshly dirty so it doesn't get expired in the meantime */
  1436. circ->timestamp_dirty = time(NULL);
  1437. return 0;
  1438. }
  1439. /**
  1440. * Check the response to a pathbias probe.
  1441. *
  1442. * If the response is valid, return 0. Otherwise return < 0.
  1443. */
  1444. int
  1445. pathbias_check_probe_response(circuit_t *circ, cell_t *cell)
  1446. {
  1447. /* Based on connection_edge_process_relay_cell() */
  1448. relay_header_t rh;
  1449. int reason;
  1450. uint32_t ipv4_host;
  1451. tor_addr_t host;
  1452. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1453. tor_assert(cell);
  1454. tor_assert(ocirc);
  1455. tor_assert(circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  1456. relay_header_unpack(&rh, cell->payload);
  1457. reason = rh.length > 0 ?
  1458. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1459. if (rh.command == RELAY_COMMAND_END &&
  1460. reason == END_STREAM_REASON_EXITPOLICY &&
  1461. ocirc->pathbias_probe_id == rh.stream_id) {
  1462. /* Check length+extract host: It is in network order after the reason code.
  1463. * See connection_edge_end(). */
  1464. if (rh.length != 9) { /* reason+ipv4+dns_ttl */
  1465. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1466. "Path bias probe response length field is insane (%d).",
  1467. rh.length);
  1468. return - END_CIRC_REASON_TORPROTOCOL;
  1469. }
  1470. ipv4_host = get_uint32(cell->payload+RELAY_HEADER_SIZE+1);
  1471. tor_addr_from_ipv4n(&host, ipv4_host);
  1472. /* Check nonce */
  1473. if (memcmp(&host, &ocirc->pathbias_probe_nonce, sizeof(tor_addr_t)) == 0) {
  1474. ocirc->path_state = PATH_STATE_USE_SUCCEEDED;
  1475. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1476. log_info(LD_CIRC,
  1477. "Got valid path bias probe back for circ %d, stream %d.",
  1478. ocirc->global_identifier, ocirc->pathbias_probe_id);
  1479. return 0;
  1480. }
  1481. }
  1482. log_info(LD_CIRC,
  1483. "Got another cell back back on pathbias probe circuit %d: "
  1484. "Command: %d, Reason: %d, Stream-id: %d",
  1485. ocirc->global_identifier, rh.command, reason, rh.stream_id);
  1486. return -1;
  1487. }
  1488. /**
  1489. * Check if a circuit was used and/or closed successfully.
  1490. *
  1491. * If we attempted to use the circuit to carry a stream but failed
  1492. * for whatever reason, or if the circuit mysteriously died before
  1493. * we could attach any streams, record these two cases.
  1494. *
  1495. * If we *have* successfully used the circuit, or it appears to
  1496. * have been closed by us locally, count it as a success.
  1497. *
  1498. * Returns 0 if we're done making decisions with the circ,
  1499. * or -1 if we want to probe it first.
  1500. */
  1501. int
  1502. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  1503. {
  1504. circuit_t *circ = &ocirc->base_;
  1505. if (!pathbias_should_count(ocirc)) {
  1506. return 0;
  1507. }
  1508. if (ocirc->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1509. if (circ->timestamp_dirty) {
  1510. if (pathbias_send_usable_probe(circ) == 0)
  1511. return -1;
  1512. else
  1513. pathbias_count_unusable(ocirc);
  1514. /* Any circuit where there were attempted streams but no successful
  1515. * streams could be bias */
  1516. log_info(LD_CIRC,
  1517. "Circuit %d closed without successful use for reason %d. "
  1518. "Circuit purpose %d currently %d,%s. Len %d.",
  1519. ocirc->global_identifier,
  1520. reason, circ->purpose, ocirc->has_opened,
  1521. circuit_state_to_string(circ->state),
  1522. ocirc->build_state->desired_path_len);
  1523. } else {
  1524. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  1525. /* Unused remote circ close reasons all could be bias */
  1526. log_info(LD_CIRC,
  1527. "Circuit %d remote-closed without successful use for reason %d. "
  1528. "Circuit purpose %d currently %d,%s. Len %d.",
  1529. ocirc->global_identifier,
  1530. reason, circ->purpose, ocirc->has_opened,
  1531. circuit_state_to_string(circ->state),
  1532. ocirc->build_state->desired_path_len);
  1533. pathbias_count_collapse(ocirc);
  1534. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  1535. == END_CIRC_REASON_CHANNEL_CLOSED &&
  1536. circ->n_chan &&
  1537. circ->n_chan->reason_for_closing
  1538. != CHANNEL_CLOSE_REQUESTED) {
  1539. /* If we didn't close the channel ourselves, it could be bias */
  1540. /* XXX: Only count bias if the network is live?
  1541. * What about clock jumps/suspends? */
  1542. log_info(LD_CIRC,
  1543. "Circuit %d's channel closed without successful use for reason "
  1544. "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
  1545. "%d.", ocirc->global_identifier,
  1546. reason, circ->n_chan->reason_for_closing,
  1547. circ->purpose, ocirc->has_opened,
  1548. circuit_state_to_string(circ->state),
  1549. ocirc->build_state->desired_path_len);
  1550. pathbias_count_collapse(ocirc);
  1551. } else {
  1552. pathbias_count_successful_close(ocirc);
  1553. }
  1554. }
  1555. } else if (ocirc->path_state == PATH_STATE_USE_SUCCEEDED) {
  1556. pathbias_count_successful_close(ocirc);
  1557. }
  1558. return 0;
  1559. }
  1560. /**
  1561. * Count a successfully closed circuit.
  1562. */
  1563. static void
  1564. pathbias_count_successful_close(origin_circuit_t *circ)
  1565. {
  1566. entry_guard_t *guard = NULL;
  1567. if (!pathbias_should_count(circ)) {
  1568. return;
  1569. }
  1570. if (circ->cpath && circ->cpath->extend_info) {
  1571. guard = entry_guard_get_by_id_digest(
  1572. circ->cpath->extend_info->identity_digest);
  1573. }
  1574. if (guard) {
  1575. /* In the long run: circuit_success ~= successful_circuit_close +
  1576. * circ_failure + stream_failure */
  1577. guard->successful_circuits_closed++;
  1578. entry_guards_changed();
  1579. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1580. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1581. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1582. * No need to log that case. */
  1583. log_info(LD_CIRC,
  1584. "Successfully closed circuit has no known guard. "
  1585. "Circuit is a %s currently %s",
  1586. circuit_purpose_to_string(circ->base_.purpose),
  1587. circuit_state_to_string(circ->base_.state));
  1588. }
  1589. }
  1590. /**
  1591. * Count a circuit that fails after it is built, but before it can
  1592. * carry any traffic.
  1593. *
  1594. * This is needed because there are ways to destroy a
  1595. * circuit after it has successfully completed. Right now, this is
  1596. * used for purely informational/debugging purposes.
  1597. */
  1598. static void
  1599. pathbias_count_collapse(origin_circuit_t *circ)
  1600. {
  1601. entry_guard_t *guard = NULL;
  1602. if (!pathbias_should_count(circ)) {
  1603. return;
  1604. }
  1605. if (circ->cpath && circ->cpath->extend_info) {
  1606. guard = entry_guard_get_by_id_digest(
  1607. circ->cpath->extend_info->identity_digest);
  1608. }
  1609. if (guard) {
  1610. guard->collapsed_circuits++;
  1611. entry_guards_changed();
  1612. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1613. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1614. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1615. * No need to log that case. */
  1616. log_info(LD_CIRC,
  1617. "Destroyed circuit has no known guard. "
  1618. "Circuit is a %s currently %s",
  1619. circuit_purpose_to_string(circ->base_.purpose),
  1620. circuit_state_to_string(circ->base_.state));
  1621. }
  1622. }
  1623. static void
  1624. pathbias_count_unusable(origin_circuit_t *circ)
  1625. {
  1626. entry_guard_t *guard = NULL;
  1627. if (!pathbias_should_count(circ)) {
  1628. return;
  1629. }
  1630. if (circ->cpath && circ->cpath->extend_info) {
  1631. guard = entry_guard_get_by_id_digest(
  1632. circ->cpath->extend_info->identity_digest);
  1633. }
  1634. if (guard) {
  1635. guard->unusable_circuits++;
  1636. entry_guards_changed();
  1637. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1638. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1639. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1640. * No need to log that case. */
  1641. log_info(LD_CIRC,
  1642. "Stream-failing circuit has no known guard. "
  1643. "Circuit is a %s currently %s",
  1644. circuit_purpose_to_string(circ->base_.purpose),
  1645. circuit_state_to_string(circ->base_.state));
  1646. }
  1647. }
  1648. /**
  1649. * Count timeouts for path bias log messages.
  1650. *
  1651. * These counts are purely informational.
  1652. */
  1653. void
  1654. pathbias_count_timeout(origin_circuit_t *circ)
  1655. {
  1656. entry_guard_t *guard = NULL;
  1657. if (!pathbias_should_count(circ)) {
  1658. return;
  1659. }
  1660. /* For hidden service circs, they can actually be used
  1661. * successfully and then time out later (because
  1662. * the other side declines to use them). */
  1663. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1664. return;
  1665. }
  1666. if (circ->cpath && circ->cpath->extend_info) {
  1667. guard = entry_guard_get_by_id_digest(
  1668. circ->cpath->extend_info->identity_digest);
  1669. }
  1670. if (guard) {
  1671. guard->timeouts++;
  1672. entry_guards_changed();
  1673. }
  1674. }
  1675. /**
  1676. * Return the number of circuits counted as successfully closed for
  1677. * this guard.
  1678. *
  1679. * Also add in the currently open circuits to give them the benefit
  1680. * of the doubt.
  1681. */
  1682. double
  1683. pathbias_get_closed_count(entry_guard_t *guard)
  1684. {
  1685. circuit_t *circ = global_circuitlist;
  1686. int open_circuits = 0;
  1687. /* Count currently open circuits. Give them the benefit of the doubt */
  1688. for ( ; circ; circ = circ->next) {
  1689. origin_circuit_t *ocirc = NULL;
  1690. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1691. circ->marked_for_close) /* already counted */
  1692. continue;
  1693. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1694. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1695. continue;
  1696. if (ocirc->path_state >= PATH_STATE_BUILD_SUCCEEDED &&
  1697. fast_memeq(guard->identity,
  1698. ocirc->cpath->extend_info->identity_digest,
  1699. DIGEST_LEN)) {
  1700. open_circuits++;
  1701. }
  1702. }
  1703. return guard->successful_circuits_closed + open_circuits;
  1704. }
  1705. /**
  1706. * This function checks the consensus parameters to decide
  1707. * if it should return guard->circ_successes or
  1708. * guard->successful_circuits_closed.
  1709. */
  1710. double
  1711. pathbias_get_success_count(entry_guard_t *guard)
  1712. {
  1713. if (pathbias_use_close_counts(get_options())) {
  1714. return pathbias_get_closed_count(guard);
  1715. } else {
  1716. return guard->circ_successes;
  1717. }
  1718. }
  1719. /** Increment the number of times we successfully extended a circuit to
  1720. * 'guard', first checking if the failure rate is high enough that we should
  1721. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  1722. * guard looks fine. */
  1723. static int
  1724. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  1725. {
  1726. const or_options_t *options = get_options();
  1727. entry_guards_changed();
  1728. if (guard->circ_attempts > pathbias_get_min_circs(options)) {
  1729. /* Note: We rely on the < comparison here to allow us to set a 0
  1730. * rate and disable the feature entirely. If refactoring, don't
  1731. * change to <= */
  1732. if (pathbias_get_success_count(guard)/guard->circ_attempts
  1733. < pathbias_get_extreme_rate(options)) {
  1734. /* Dropping is currently disabled by default. */
  1735. if (pathbias_get_dropguards(options)) {
  1736. if (!guard->path_bias_disabled) {
  1737. log_warn(LD_CIRC,
  1738. "Your Guard %s=%s is failing an extremely large amount of "
  1739. "circuits. To avoid potential route manipluation attacks, "
  1740. "Tor has disabled use of this guard. "
  1741. "Success counts are %ld/%ld. %ld circuits completed, %ld "
  1742. "were unusable, %ld collapsed, and %ld timed out. For "
  1743. "reference, your timeout cutoff is %ld seconds.",
  1744. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1745. tor_lround(pathbias_get_closed_count(guard)),
  1746. tor_lround(guard->circ_attempts),
  1747. tor_lround(guard->circ_successes),
  1748. tor_lround(guard->unusable_circuits),
  1749. tor_lround(guard->collapsed_circuits),
  1750. tor_lround(guard->timeouts),
  1751. tor_lround(circ_times.close_ms/1000));
  1752. guard->path_bias_disabled = 1;
  1753. guard->bad_since = approx_time();
  1754. return -1;
  1755. }
  1756. } else if (!guard->path_bias_extreme) {
  1757. guard->path_bias_extreme = 1;
  1758. log_warn(LD_CIRC,
  1759. "Your Guard %s=%s is failing an extremely large amount of "
  1760. "circuits. This could indicate a route manipulation attack, "
  1761. "extreme network overload, or a bug. "
  1762. "Success counts are %ld/%ld. %ld circuits completed, %ld "
  1763. "were unusable, %ld collapsed, and %ld timed out. For "
  1764. "reference, your timeout cutoff is %ld seconds.",
  1765. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1766. tor_lround(pathbias_get_closed_count(guard)),
  1767. tor_lround(guard->circ_attempts),
  1768. tor_lround(guard->circ_successes),
  1769. tor_lround(guard->unusable_circuits),
  1770. tor_lround(guard->collapsed_circuits),
  1771. tor_lround(guard->timeouts),
  1772. tor_lround(circ_times.close_ms/1000));
  1773. }
  1774. } else if (pathbias_get_success_count(guard)/((double)guard->circ_attempts)
  1775. < pathbias_get_warn_rate(options)) {
  1776. if (!guard->path_bias_warned) {
  1777. guard->path_bias_warned = 1;
  1778. log_warn(LD_CIRC,
  1779. "Your Guard %s=%s is failing a very large amount of "
  1780. "circuits. Most likely this means the Tor network is "
  1781. "overloaded, but it could also mean an attack against "
  1782. "you or the potentially the guard itself. "
  1783. "Success counts are %ld/%ld. %ld circuits completed, %ld "
  1784. "were unusable, %ld collapsed, and %ld timed out. For "
  1785. "reference, your timeout cutoff is %ld seconds.",
  1786. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1787. tor_lround(pathbias_get_closed_count(guard)),
  1788. tor_lround(guard->circ_attempts),
  1789. tor_lround(guard->circ_successes),
  1790. tor_lround(guard->unusable_circuits),
  1791. tor_lround(guard->collapsed_circuits),
  1792. tor_lround(guard->timeouts),
  1793. tor_lround(circ_times.close_ms/1000));
  1794. }
  1795. } else if (pathbias_get_success_count(guard)/((double)guard->circ_attempts)
  1796. < pathbias_get_notice_rate(options)) {
  1797. if (!guard->path_bias_noticed) {
  1798. guard->path_bias_noticed = 1;
  1799. log_notice(LD_CIRC,
  1800. "Your Guard %s=%s is failing more circuits than usual. "
  1801. "Most likely this means the Tor network is overloaded. "
  1802. "Success counts are %ld/%ld. %ld circuits completed, %ld "
  1803. "were unusable, %ld collapsed, and %ld timed out. For "
  1804. "reference, your timeout cutoff is %ld seconds.",
  1805. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1806. tor_lround(pathbias_get_closed_count(guard)),
  1807. tor_lround(guard->circ_attempts),
  1808. tor_lround(guard->circ_successes),
  1809. tor_lround(guard->unusable_circuits),
  1810. tor_lround(guard->collapsed_circuits),
  1811. tor_lround(guard->timeouts),
  1812. tor_lround(circ_times.close_ms/1000));
  1813. }
  1814. }
  1815. }
  1816. /* If we get a ton of circuits, just scale everything down */
  1817. if (guard->circ_attempts > pathbias_get_scale_threshold(options)) {
  1818. const int scale_factor = pathbias_get_scale_factor(options);
  1819. const int mult_factor = pathbias_get_mult_factor(options);
  1820. log_info(LD_CIRC,
  1821. "Scaling pathbias counts to (%f/%f)*(%d/%d) for guard %s=%s",
  1822. guard->circ_successes, guard->circ_attempts,
  1823. mult_factor, scale_factor, guard->nickname,
  1824. hex_str(guard->identity, DIGEST_LEN));
  1825. guard->circ_attempts *= mult_factor;
  1826. guard->circ_successes *= mult_factor;
  1827. guard->timeouts *= mult_factor;
  1828. guard->successful_circuits_closed *= mult_factor;
  1829. guard->collapsed_circuits *= mult_factor;
  1830. guard->unusable_circuits *= mult_factor;
  1831. guard->circ_attempts /= scale_factor;
  1832. guard->circ_successes /= scale_factor;
  1833. guard->timeouts /= scale_factor;
  1834. guard->successful_circuits_closed /= scale_factor;
  1835. guard->collapsed_circuits /= scale_factor;
  1836. guard->unusable_circuits /= scale_factor;
  1837. }
  1838. guard->circ_attempts++;
  1839. log_info(LD_CIRC, "Got success count %f/%f for guard %s=%s",
  1840. guard->circ_successes, guard->circ_attempts, guard->nickname,
  1841. hex_str(guard->identity, DIGEST_LEN));
  1842. return 0;
  1843. }
  1844. /** A created or extended cell came back to us on the circuit, and it included
  1845. * reply_cell as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  1846. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  1847. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  1848. *
  1849. * Calculate the appropriate keys and digests, make sure KH is
  1850. * correct, and initialize this hop of the cpath.
  1851. *
  1852. * Return - reason if we want to mark circ for close, else return 0.
  1853. */
  1854. int
  1855. circuit_finish_handshake(origin_circuit_t *circ,
  1856. const created_cell_t *reply)
  1857. {
  1858. char keys[CPATH_KEY_MATERIAL_LEN];
  1859. crypt_path_t *hop;
  1860. int rv;
  1861. if ((rv = pathbias_count_circ_attempt(circ)) < 0)
  1862. return rv;
  1863. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1864. hop = circ->cpath;
  1865. } else {
  1866. hop = onion_next_hop_in_cpath(circ->cpath);
  1867. if (!hop) { /* got an extended when we're all done? */
  1868. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1869. return - END_CIRC_REASON_TORPROTOCOL;
  1870. }
  1871. }
  1872. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1873. {
  1874. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1875. &hop->handshake_state,
  1876. reply->reply, reply->handshake_len,
  1877. (uint8_t*)keys, sizeof(keys),
  1878. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1879. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1880. return -END_CIRC_REASON_TORPROTOCOL;
  1881. }
  1882. }
  1883. onion_handshake_state_release(&hop->handshake_state);
  1884. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1885. return -END_CIRC_REASON_TORPROTOCOL;
  1886. }
  1887. hop->state = CPATH_STATE_OPEN;
  1888. log_info(LD_CIRC,"Finished building circuit hop:");
  1889. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1890. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1891. return 0;
  1892. }
  1893. /** We received a relay truncated cell on circ.
  1894. *
  1895. * Since we don't ask for truncates currently, getting a truncated
  1896. * means that a connection broke or an extend failed. For now,
  1897. * just give up: for circ to close, and return 0.
  1898. */
  1899. int
  1900. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1901. {
  1902. // crypt_path_t *victim;
  1903. // connection_t *stream;
  1904. tor_assert(circ);
  1905. tor_assert(layer);
  1906. /* XXX Since we don't ask for truncates currently, getting a truncated
  1907. * means that a connection broke or an extend failed. For now,
  1908. * just give up.
  1909. */
  1910. circuit_mark_for_close(TO_CIRCUIT(circ),
  1911. END_CIRC_REASON_FLAG_REMOTE|reason);
  1912. return 0;
  1913. #if 0
  1914. while (layer->next != circ->cpath) {
  1915. /* we need to clear out layer->next */
  1916. victim = layer->next;
  1917. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1918. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1919. if (stream->cpath_layer == victim) {
  1920. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1921. stream->stream_id);
  1922. /* no need to send 'end' relay cells,
  1923. * because the other side's already dead
  1924. */
  1925. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1926. }
  1927. }
  1928. layer->next = victim->next;
  1929. circuit_free_cpath_node(victim);
  1930. }
  1931. log_info(LD_CIRC, "finished");
  1932. return 0;
  1933. #endif
  1934. }
  1935. /** Given a response payload and keys, initialize, then send a created
  1936. * cell back.
  1937. */
  1938. int
  1939. onionskin_answer(or_circuit_t *circ,
  1940. const created_cell_t *created_cell,
  1941. const char *keys,
  1942. const uint8_t *rend_circ_nonce)
  1943. {
  1944. cell_t cell;
  1945. crypt_path_t *tmp_cpath;
  1946. if (created_cell_format(&cell, created_cell) < 0) {
  1947. log_warn(LD_BUG,"couldn't format created cell");
  1948. return -1;
  1949. }
  1950. cell.circ_id = circ->p_circ_id;
  1951. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1952. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1953. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1954. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1955. (unsigned int)get_uint32(keys),
  1956. (unsigned int)get_uint32(keys+20));
  1957. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1958. log_warn(LD_BUG,"Circuit initialization failed");
  1959. tor_free(tmp_cpath);
  1960. return -1;
  1961. }
  1962. circ->n_digest = tmp_cpath->f_digest;
  1963. circ->n_crypto = tmp_cpath->f_crypto;
  1964. circ->p_digest = tmp_cpath->b_digest;
  1965. circ->p_crypto = tmp_cpath->b_crypto;
  1966. tmp_cpath->magic = 0;
  1967. tor_free(tmp_cpath);
  1968. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1969. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1970. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1971. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1972. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1973. circ->is_first_hop ? "created_fast" : "created");
  1974. if (!channel_is_local(circ->p_chan) &&
  1975. !channel_is_outgoing(circ->p_chan)) {
  1976. /* record that we could process create cells from a non-local conn
  1977. * that we didn't initiate; presumably this means that create cells
  1978. * can reach us too. */
  1979. router_orport_found_reachable();
  1980. }
  1981. return 0;
  1982. }
  1983. /** Choose a length for a circuit of purpose <b>purpose</b>.
  1984. * Default length is 3 + the number of endpoints that would give something
  1985. * away. If the routerlist <b>routers</b> doesn't have enough routers
  1986. * to handle the desired path length, return as large a path length as
  1987. * is feasible, except if it's less than 2, in which case return -1.
  1988. */
  1989. static int
  1990. new_route_len(uint8_t purpose, extend_info_t *exit,
  1991. smartlist_t *nodes)
  1992. {
  1993. int num_acceptable_routers;
  1994. int routelen;
  1995. tor_assert(nodes);
  1996. routelen = DEFAULT_ROUTE_LEN;
  1997. if (exit &&
  1998. purpose != CIRCUIT_PURPOSE_TESTING &&
  1999. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2000. routelen++;
  2001. num_acceptable_routers = count_acceptable_nodes(nodes);
  2002. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2003. routelen, num_acceptable_routers, smartlist_len(nodes));
  2004. if (num_acceptable_routers < 2) {
  2005. log_info(LD_CIRC,
  2006. "Not enough acceptable routers (%d). Discarding this circuit.",
  2007. num_acceptable_routers);
  2008. return -1;
  2009. }
  2010. if (num_acceptable_routers < routelen) {
  2011. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2012. routelen, num_acceptable_routers);
  2013. routelen = num_acceptable_routers;
  2014. }
  2015. return routelen;
  2016. }
  2017. /** Return a newly allocated list of uint16_t * for each predicted port not
  2018. * handled by a current circuit. */
  2019. static smartlist_t *
  2020. circuit_get_unhandled_ports(time_t now)
  2021. {
  2022. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  2023. circuit_remove_handled_ports(dest);
  2024. return dest;
  2025. }
  2026. /** Return 1 if we already have circuits present or on the way for
  2027. * all anticipated ports. Return 0 if we should make more.
  2028. *
  2029. * If we're returning 0, set need_uptime and need_capacity to
  2030. * indicate any requirements that the unhandled ports have.
  2031. */
  2032. int
  2033. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2034. int *need_capacity)
  2035. {
  2036. int i, enough;
  2037. uint16_t *port;
  2038. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2039. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2040. tor_assert(need_uptime);
  2041. tor_assert(need_capacity);
  2042. // Always predict need_capacity
  2043. *need_capacity = 1;
  2044. enough = (smartlist_len(sl) == 0);
  2045. for (i = 0; i < smartlist_len(sl); ++i) {
  2046. port = smartlist_get(sl, i);
  2047. if (smartlist_string_num_isin(LongLivedServices, *port))
  2048. *need_uptime = 1;
  2049. tor_free(port);
  2050. }
  2051. smartlist_free(sl);
  2052. return enough;
  2053. }
  2054. /** Return 1 if <b>node</b> can handle one or more of the ports in
  2055. * <b>needed_ports</b>, else return 0.
  2056. */
  2057. static int
  2058. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  2059. { /* XXXX MOVE */
  2060. int i;
  2061. uint16_t port;
  2062. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2063. addr_policy_result_t r;
  2064. /* alignment issues aren't a worry for this dereference, since
  2065. needed_ports is explicitly a smartlist of uint16_t's */
  2066. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2067. tor_assert(port);
  2068. if (node)
  2069. r = compare_tor_addr_to_node_policy(NULL, port, node);
  2070. else
  2071. continue;
  2072. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2073. return 1;
  2074. }
  2075. return 0;
  2076. }
  2077. /** Return true iff <b>conn</b> needs another general circuit to be
  2078. * built. */
  2079. static int
  2080. ap_stream_wants_exit_attention(connection_t *conn)
  2081. {
  2082. entry_connection_t *entry;
  2083. if (conn->type != CONN_TYPE_AP)
  2084. return 0;
  2085. entry = TO_ENTRY_CONN(conn);
  2086. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2087. !conn->marked_for_close &&
  2088. !(entry->want_onehop) && /* ignore one-hop streams */
  2089. !(entry->use_begindir) && /* ignore targeted dir fetches */
  2090. !(entry->chosen_exit_name) && /* ignore defined streams */
  2091. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2092. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  2093. MIN_CIRCUITS_HANDLING_STREAM))
  2094. return 1;
  2095. return 0;
  2096. }
  2097. /** Return a pointer to a suitable router to be the exit node for the
  2098. * general-purpose circuit we're about to build.
  2099. *
  2100. * Look through the connection array, and choose a router that maximizes
  2101. * the number of pending streams that can exit from this router.
  2102. *
  2103. * Return NULL if we can't find any suitable routers.
  2104. */
  2105. static const node_t *
  2106. choose_good_exit_server_general(int need_uptime, int need_capacity)
  2107. {
  2108. int *n_supported;
  2109. int n_pending_connections = 0;
  2110. smartlist_t *connections;
  2111. int best_support = -1;
  2112. int n_best_support=0;
  2113. const or_options_t *options = get_options();
  2114. const smartlist_t *the_nodes;
  2115. const node_t *node=NULL;
  2116. connections = get_connection_array();
  2117. /* Count how many connections are waiting for a circuit to be built.
  2118. * We use this for log messages now, but in the future we may depend on it.
  2119. */
  2120. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2121. {
  2122. if (ap_stream_wants_exit_attention(conn))
  2123. ++n_pending_connections;
  2124. });
  2125. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2126. // n_pending_connections);
  2127. /* Now we count, for each of the routers in the directory, how many
  2128. * of the pending connections could possibly exit from that
  2129. * router (n_supported[i]). (We can't be sure about cases where we
  2130. * don't know the IP address of the pending connection.)
  2131. *
  2132. * -1 means "Don't use this router at all."
  2133. */
  2134. the_nodes = nodelist_get_list();
  2135. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  2136. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2137. const int i = node_sl_idx;
  2138. if (router_digest_is_me(node->identity)) {
  2139. n_supported[i] = -1;
  2140. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2141. /* XXX there's probably a reverse predecessor attack here, but
  2142. * it's slow. should we take this out? -RD
  2143. */
  2144. continue;
  2145. }
  2146. if (!node_has_descriptor(node)) {
  2147. n_supported[i] = -1;
  2148. continue;
  2149. }
  2150. if (!node->is_running || node->is_bad_exit) {
  2151. n_supported[i] = -1;
  2152. continue; /* skip routers that are known to be down or bad exits */
  2153. }
  2154. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2155. /* never pick a non-general node as a random exit. */
  2156. n_supported[i] = -1;
  2157. continue;
  2158. }
  2159. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  2160. n_supported[i] = -1;
  2161. continue; /* user asked us not to use it, no matter what */
  2162. }
  2163. if (options->ExitNodes &&
  2164. !routerset_contains_node(options->ExitNodes, node)) {
  2165. n_supported[i] = -1;
  2166. continue; /* not one of our chosen exit nodes */
  2167. }
  2168. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2169. n_supported[i] = -1;
  2170. continue; /* skip routers that are not suitable. Don't worry if
  2171. * this makes us reject all the possible routers: if so,
  2172. * we'll retry later in this function with need_update and
  2173. * need_capacity set to 0. */
  2174. }
  2175. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  2176. /* if it's invalid and we don't want it */
  2177. n_supported[i] = -1;
  2178. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2179. // router->nickname, i);
  2180. continue; /* skip invalid routers */
  2181. }
  2182. if (options->ExcludeSingleHopRelays &&
  2183. node_allows_single_hop_exits(node)) {
  2184. n_supported[i] = -1;
  2185. continue;
  2186. }
  2187. if (node_exit_policy_rejects_all(node)) {
  2188. n_supported[i] = -1;
  2189. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2190. // router->nickname, i);
  2191. continue; /* skip routers that reject all */
  2192. }
  2193. n_supported[i] = 0;
  2194. /* iterate over connections */
  2195. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  2196. if (!ap_stream_wants_exit_attention(conn))
  2197. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2198. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  2199. ++n_supported[i];
  2200. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2201. // router->nickname, i, n_supported[i]);
  2202. } else {
  2203. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2204. // router->nickname, i);
  2205. }
  2206. } SMARTLIST_FOREACH_END(conn);
  2207. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2208. /* Leave best_support at -1 if that's where it is, so we can
  2209. * distinguish it later. */
  2210. continue;
  2211. }
  2212. if (n_supported[i] > best_support) {
  2213. /* If this router is better than previous ones, remember its index
  2214. * and goodness, and start counting how many routers are this good. */
  2215. best_support = n_supported[i]; n_best_support=1;
  2216. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2217. // router->nickname);
  2218. } else if (n_supported[i] == best_support) {
  2219. /* If this router is _as good_ as the best one, just increment the
  2220. * count of equally good routers.*/
  2221. ++n_best_support;
  2222. }
  2223. } SMARTLIST_FOREACH_END(node);
  2224. log_info(LD_CIRC,
  2225. "Found %d servers that might support %d/%d pending connections.",
  2226. n_best_support, best_support >= 0 ? best_support : 0,
  2227. n_pending_connections);
  2228. /* If any routers definitely support any pending connections, choose one
  2229. * at random. */
  2230. if (best_support > 0) {
  2231. smartlist_t *supporting = smartlist_new();
  2232. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2233. if (n_supported[node_sl_idx] == best_support)
  2234. smartlist_add(supporting, (void*)node);
  2235. });
  2236. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2237. smartlist_free(supporting);
  2238. } else {
  2239. /* Either there are no pending connections, or no routers even seem to
  2240. * possibly support any of them. Choose a router at random that satisfies
  2241. * at least one predicted exit port. */
  2242. int attempt;
  2243. smartlist_t *needed_ports, *supporting;
  2244. if (best_support == -1) {
  2245. if (need_uptime || need_capacity) {
  2246. log_info(LD_CIRC,
  2247. "We couldn't find any live%s%s routers; falling back "
  2248. "to list of all routers.",
  2249. need_capacity?", fast":"",
  2250. need_uptime?", stable":"");
  2251. tor_free(n_supported);
  2252. return choose_good_exit_server_general(0, 0);
  2253. }
  2254. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2255. "choosing a doomed exit at random.",
  2256. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  2257. }
  2258. supporting = smartlist_new();
  2259. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2260. for (attempt = 0; attempt < 2; attempt++) {
  2261. /* try once to pick only from routers that satisfy a needed port,
  2262. * then if there are none, pick from any that support exiting. */
  2263. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2264. if (n_supported[node_sl_idx] != -1 &&
  2265. (attempt || node_handles_some_port(node, needed_ports))) {
  2266. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2267. // try, router->nickname);
  2268. smartlist_add(supporting, (void*)node);
  2269. }
  2270. } SMARTLIST_FOREACH_END(node);
  2271. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2272. if (node)
  2273. break;
  2274. smartlist_clear(supporting);
  2275. /* If we reach this point, we can't actually support any unhandled
  2276. * predicted ports, so clear all the remaining ones. */
  2277. if (smartlist_len(needed_ports))
  2278. rep_hist_remove_predicted_ports(needed_ports);
  2279. }
  2280. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2281. smartlist_free(needed_ports);
  2282. smartlist_free(supporting);
  2283. }
  2284. tor_free(n_supported);
  2285. if (node) {
  2286. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2287. return node;
  2288. }
  2289. if (options->ExitNodes) {
  2290. log_warn(LD_CIRC,
  2291. "No specified %sexit routers seem to be running: "
  2292. "can't choose an exit.",
  2293. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  2294. }
  2295. return NULL;
  2296. }
  2297. /** Return a pointer to a suitable router to be the exit node for the
  2298. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2299. * if no router is suitable).
  2300. *
  2301. * For general-purpose circuits, pass it off to
  2302. * choose_good_exit_server_general()
  2303. *
  2304. * For client-side rendezvous circuits, choose a random node, weighted
  2305. * toward the preferences in 'options'.
  2306. */
  2307. static const node_t *
  2308. choose_good_exit_server(uint8_t purpose,
  2309. int need_uptime, int need_capacity, int is_internal)
  2310. {
  2311. const or_options_t *options = get_options();
  2312. router_crn_flags_t flags = CRN_NEED_DESC;
  2313. if (need_uptime)
  2314. flags |= CRN_NEED_UPTIME;
  2315. if (need_capacity)
  2316. flags |= CRN_NEED_CAPACITY;
  2317. switch (purpose) {
  2318. case CIRCUIT_PURPOSE_C_GENERAL:
  2319. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2320. flags |= CRN_ALLOW_INVALID;
  2321. if (is_internal) /* pick it like a middle hop */
  2322. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2323. else
  2324. return choose_good_exit_server_general(need_uptime,need_capacity);
  2325. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2326. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  2327. flags |= CRN_ALLOW_INVALID;
  2328. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2329. }
  2330. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2331. tor_fragile_assert();
  2332. return NULL;
  2333. }
  2334. /** Log a warning if the user specified an exit for the circuit that
  2335. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2336. static void
  2337. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2338. {
  2339. const or_options_t *options = get_options();
  2340. routerset_t *rs = options->ExcludeNodes;
  2341. const char *description;
  2342. uint8_t purpose = circ->base_.purpose;
  2343. if (circ->build_state->onehop_tunnel)
  2344. return;
  2345. switch (purpose)
  2346. {
  2347. default:
  2348. case CIRCUIT_PURPOSE_OR:
  2349. case CIRCUIT_PURPOSE_INTRO_POINT:
  2350. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2351. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2352. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2353. (int)purpose,
  2354. circuit_purpose_to_string(purpose));
  2355. return;
  2356. case CIRCUIT_PURPOSE_C_GENERAL:
  2357. if (circ->build_state->is_internal)
  2358. return;
  2359. description = "requested exit node";
  2360. rs = options->ExcludeExitNodesUnion_;
  2361. break;
  2362. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2363. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2364. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2365. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2366. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2367. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2368. case CIRCUIT_PURPOSE_TESTING:
  2369. return;
  2370. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2371. case CIRCUIT_PURPOSE_C_REND_READY:
  2372. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2373. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2374. description = "chosen rendezvous point";
  2375. break;
  2376. case CIRCUIT_PURPOSE_CONTROLLER:
  2377. rs = options->ExcludeExitNodesUnion_;
  2378. description = "controller-selected circuit target";
  2379. break;
  2380. }
  2381. if (routerset_contains_extendinfo(rs, exit)) {
  2382. /* We should never get here if StrictNodes is set to 1. */
  2383. if (options->StrictNodes) {
  2384. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2385. "even though StrictNodes is set. Please report. "
  2386. "(Circuit purpose: %s)",
  2387. description, extend_info_describe(exit),
  2388. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2389. circuit_purpose_to_string(purpose));
  2390. } else {
  2391. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2392. "ExcludeNodes%s, because no better options were available. To "
  2393. "prevent this (and possibly break your Tor functionality), "
  2394. "set the StrictNodes configuration option. "
  2395. "(Circuit purpose: %s)",
  2396. description, extend_info_describe(exit),
  2397. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2398. circuit_purpose_to_string(purpose));
  2399. }
  2400. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2401. }
  2402. return;
  2403. }
  2404. /** Decide a suitable length for circ's cpath, and pick an exit
  2405. * router (or use <b>exit</b> if provided). Store these in the
  2406. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2407. static int
  2408. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2409. {
  2410. cpath_build_state_t *state = circ->build_state;
  2411. if (state->onehop_tunnel) {
  2412. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2413. state->desired_path_len = 1;
  2414. } else {
  2415. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  2416. if (r < 1) /* must be at least 1 */
  2417. return -1;
  2418. state->desired_path_len = r;
  2419. }
  2420. if (exit) { /* the circuit-builder pre-requested one */
  2421. warn_if_last_router_excluded(circ, exit);
  2422. log_info(LD_CIRC,"Using requested exit node '%s'",
  2423. extend_info_describe(exit));
  2424. exit = extend_info_dup(exit);
  2425. } else { /* we have to decide one */
  2426. const node_t *node =
  2427. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  2428. state->need_capacity, state->is_internal);
  2429. if (!node) {
  2430. log_warn(LD_CIRC,"failed to choose an exit server");
  2431. return -1;
  2432. }
  2433. exit = extend_info_from_node(node, 0);
  2434. tor_assert(exit);
  2435. }
  2436. state->chosen_exit = exit;
  2437. return 0;
  2438. }
  2439. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2440. * hop to the cpath reflecting this. Don't send the next extend cell --
  2441. * the caller will do this if it wants to.
  2442. */
  2443. int
  2444. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2445. {
  2446. cpath_build_state_t *state;
  2447. tor_assert(exit);
  2448. tor_assert(circ);
  2449. state = circ->build_state;
  2450. tor_assert(state);
  2451. extend_info_free(state->chosen_exit);
  2452. state->chosen_exit = extend_info_dup(exit);
  2453. ++circ->build_state->desired_path_len;
  2454. onion_append_hop(&circ->cpath, exit);
  2455. return 0;
  2456. }
  2457. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2458. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2459. * send the next extend cell to begin connecting to that hop.
  2460. */
  2461. int
  2462. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2463. {
  2464. int err_reason = 0;
  2465. warn_if_last_router_excluded(circ, exit);
  2466. tor_gettimeofday(&circ->base_.timestamp_began);
  2467. circuit_append_new_exit(circ, exit);
  2468. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2469. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2470. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2471. extend_info_describe(exit));
  2472. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2473. return -1;
  2474. }
  2475. /* Set timestamp_dirty, so we can check it for path use bias */
  2476. if (!circ->base_.timestamp_dirty)
  2477. circ->base_.timestamp_dirty = time(NULL);
  2478. return 0;
  2479. }
  2480. /** Return the number of routers in <b>routers</b> that are currently up
  2481. * and available for building circuits through.
  2482. */
  2483. static int
  2484. count_acceptable_nodes(smartlist_t *nodes)
  2485. {
  2486. int num=0;
  2487. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2488. // log_debug(LD_CIRC,
  2489. // "Contemplating whether router %d (%s) is a new option.",
  2490. // i, r->nickname);
  2491. if (! node->is_running)
  2492. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2493. continue;
  2494. if (! node->is_valid)
  2495. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2496. continue;
  2497. if (! node_has_descriptor(node))
  2498. continue;
  2499. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2500. * allows this node in some places, then we're getting an inaccurate
  2501. * count. For now, be conservative and don't count it. But later we
  2502. * should try to be smarter. */
  2503. ++num;
  2504. } SMARTLIST_FOREACH_END(node);
  2505. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2506. return num;
  2507. }
  2508. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2509. * This function is used to extend cpath by another hop.
  2510. */
  2511. void
  2512. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2513. {
  2514. if (*head_ptr) {
  2515. new_hop->next = (*head_ptr);
  2516. new_hop->prev = (*head_ptr)->prev;
  2517. (*head_ptr)->prev->next = new_hop;
  2518. (*head_ptr)->prev = new_hop;
  2519. } else {
  2520. *head_ptr = new_hop;
  2521. new_hop->prev = new_hop->next = new_hop;
  2522. }
  2523. }
  2524. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2525. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2526. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2527. * circuit. In particular, make sure we don't pick the exit node or its
  2528. * family, and make sure we don't duplicate any previous nodes or their
  2529. * families. */
  2530. static const node_t *
  2531. choose_good_middle_server(uint8_t purpose,
  2532. cpath_build_state_t *state,
  2533. crypt_path_t *head,
  2534. int cur_len)
  2535. {
  2536. int i;
  2537. const node_t *r, *choice;
  2538. crypt_path_t *cpath;
  2539. smartlist_t *excluded;
  2540. const or_options_t *options = get_options();
  2541. router_crn_flags_t flags = CRN_NEED_DESC;
  2542. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2543. purpose <= CIRCUIT_PURPOSE_MAX_);
  2544. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2545. excluded = smartlist_new();
  2546. if ((r = build_state_get_exit_node(state))) {
  2547. nodelist_add_node_and_family(excluded, r);
  2548. }
  2549. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2550. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2551. nodelist_add_node_and_family(excluded, r);
  2552. }
  2553. }
  2554. if (state->need_uptime)
  2555. flags |= CRN_NEED_UPTIME;
  2556. if (state->need_capacity)
  2557. flags |= CRN_NEED_CAPACITY;
  2558. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2559. flags |= CRN_ALLOW_INVALID;
  2560. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2561. smartlist_free(excluded);
  2562. return choice;
  2563. }
  2564. /** Pick a good entry server for the circuit to be built according to
  2565. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2566. * router (if we're an OR), and respect firewall settings; if we're
  2567. * configured to use entry guards, return one.
  2568. *
  2569. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2570. * guard, not for any particular circuit.
  2571. */
  2572. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2573. const node_t *
  2574. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2575. {
  2576. const node_t *choice;
  2577. smartlist_t *excluded;
  2578. const or_options_t *options = get_options();
  2579. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2580. const node_t *node;
  2581. if (state && options->UseEntryGuards &&
  2582. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2583. /* This request is for an entry server to use for a regular circuit,
  2584. * and we use entry guard nodes. Just return one of the guard nodes. */
  2585. return choose_random_entry(state);
  2586. }
  2587. excluded = smartlist_new();
  2588. if (state && (node = build_state_get_exit_node(state))) {
  2589. /* Exclude the exit node from the state, if we have one. Also exclude its
  2590. * family. */
  2591. nodelist_add_node_and_family(excluded, node);
  2592. }
  2593. if (firewall_is_fascist_or()) {
  2594. /* Exclude all ORs that we can't reach through our firewall */
  2595. smartlist_t *nodes = nodelist_get_list();
  2596. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2597. if (!fascist_firewall_allows_node(node))
  2598. smartlist_add(excluded, (void*)node);
  2599. });
  2600. }
  2601. /* and exclude current entry guards and their families, if applicable */
  2602. if (options->UseEntryGuards) {
  2603. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2604. {
  2605. if ((node = node_get_by_id(entry->identity))) {
  2606. nodelist_add_node_and_family(excluded, node);
  2607. }
  2608. });
  2609. }
  2610. if (state) {
  2611. if (state->need_uptime)
  2612. flags |= CRN_NEED_UPTIME;
  2613. if (state->need_capacity)
  2614. flags |= CRN_NEED_CAPACITY;
  2615. }
  2616. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  2617. flags |= CRN_ALLOW_INVALID;
  2618. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2619. smartlist_free(excluded);
  2620. return choice;
  2621. }
  2622. /** Return the first non-open hop in cpath, or return NULL if all
  2623. * hops are open. */
  2624. static crypt_path_t *
  2625. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2626. {
  2627. crypt_path_t *hop = cpath;
  2628. do {
  2629. if (hop->state != CPATH_STATE_OPEN)
  2630. return hop;
  2631. hop = hop->next;
  2632. } while (hop != cpath);
  2633. return NULL;
  2634. }
  2635. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2636. * based on <b>state</b>. Append the hop info to head_ptr.
  2637. */
  2638. static int
  2639. onion_extend_cpath(origin_circuit_t *circ)
  2640. {
  2641. uint8_t purpose = circ->base_.purpose;
  2642. cpath_build_state_t *state = circ->build_state;
  2643. int cur_len = circuit_get_cpath_len(circ);
  2644. extend_info_t *info = NULL;
  2645. if (cur_len >= state->desired_path_len) {
  2646. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2647. state->desired_path_len);
  2648. return 1;
  2649. }
  2650. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2651. state->desired_path_len);
  2652. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2653. info = extend_info_dup(state->chosen_exit);
  2654. } else if (cur_len == 0) { /* picking first node */
  2655. const node_t *r = choose_good_entry_server(purpose, state);
  2656. if (r) {
  2657. /* If we're a client, use the preferred address rather than the
  2658. primary address, for potentially connecting to an IPv6 OR
  2659. port. */
  2660. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  2661. tor_assert(info);
  2662. }
  2663. } else {
  2664. const node_t *r =
  2665. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2666. if (r) {
  2667. info = extend_info_from_node(r, 0);
  2668. tor_assert(info);
  2669. }
  2670. }
  2671. if (!info) {
  2672. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2673. "this circuit.", cur_len);
  2674. return -1;
  2675. }
  2676. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2677. extend_info_describe(info),
  2678. cur_len+1, build_state_get_exit_nickname(state));
  2679. onion_append_hop(&circ->cpath, info);
  2680. extend_info_free(info);
  2681. return 0;
  2682. }
  2683. /** Create a new hop, annotate it with information about its
  2684. * corresponding router <b>choice</b>, and append it to the
  2685. * end of the cpath <b>head_ptr</b>. */
  2686. static int
  2687. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2688. {
  2689. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2690. /* link hop into the cpath, at the end. */
  2691. onion_append_to_cpath(head_ptr, hop);
  2692. hop->magic = CRYPT_PATH_MAGIC;
  2693. hop->state = CPATH_STATE_CLOSED;
  2694. hop->extend_info = extend_info_dup(choice);
  2695. hop->package_window = circuit_initial_package_window();
  2696. hop->deliver_window = CIRCWINDOW_START;
  2697. return 0;
  2698. }
  2699. /** Allocate a new extend_info object based on the various arguments. */
  2700. extend_info_t *
  2701. extend_info_new(const char *nickname, const char *digest,
  2702. crypto_pk_t *onion_key,
  2703. const curve25519_public_key_t *curve25519_key,
  2704. const tor_addr_t *addr, uint16_t port)
  2705. {
  2706. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2707. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2708. if (nickname)
  2709. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2710. if (onion_key)
  2711. info->onion_key = crypto_pk_dup_key(onion_key);
  2712. #ifdef CURVE25519_ENABLED
  2713. if (curve25519_key)
  2714. memcpy(&info->curve25519_onion_key, curve25519_key,
  2715. sizeof(curve25519_public_key_t));
  2716. #else
  2717. (void)curve25519_key;
  2718. #endif
  2719. tor_addr_copy(&info->addr, addr);
  2720. info->port = port;
  2721. return info;
  2722. }
  2723. /** Allocate and return a new extend_info that can be used to build a
  2724. * circuit to or through the node <b>node</b>. Use the primary address
  2725. * of the node (i.e. its IPv4 address) unless
  2726. * <b>for_direct_connect</b> is true, in which case the preferred
  2727. * address is used instead. May return NULL if there is not enough
  2728. * info about <b>node</b> to extend to it--for example, if there is no
  2729. * routerinfo_t or microdesc_t.
  2730. **/
  2731. extend_info_t *
  2732. extend_info_from_node(const node_t *node, int for_direct_connect)
  2733. {
  2734. tor_addr_port_t ap;
  2735. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2736. return NULL;
  2737. if (for_direct_connect)
  2738. node_get_pref_orport(node, &ap);
  2739. else
  2740. node_get_prim_orport(node, &ap);
  2741. log_debug(LD_CIRC, "using %s for %s",
  2742. fmt_addrport(&ap.addr, ap.port),
  2743. node->ri ? node->ri->nickname : node->rs->nickname);
  2744. if (node->ri)
  2745. return extend_info_new(node->ri->nickname,
  2746. node->identity,
  2747. node->ri->onion_pkey,
  2748. node->ri->onion_curve25519_pkey,
  2749. &ap.addr,
  2750. ap.port);
  2751. else if (node->rs && node->md)
  2752. return extend_info_new(node->rs->nickname,
  2753. node->identity,
  2754. node->md->onion_pkey,
  2755. node->md->onion_curve25519_pkey,
  2756. &ap.addr,
  2757. ap.port);
  2758. else
  2759. return NULL;
  2760. }
  2761. /** Release storage held by an extend_info_t struct. */
  2762. void
  2763. extend_info_free(extend_info_t *info)
  2764. {
  2765. if (!info)
  2766. return;
  2767. crypto_pk_free(info->onion_key);
  2768. tor_free(info);
  2769. }
  2770. /** Allocate and return a new extend_info_t with the same contents as
  2771. * <b>info</b>. */
  2772. extend_info_t *
  2773. extend_info_dup(extend_info_t *info)
  2774. {
  2775. extend_info_t *newinfo;
  2776. tor_assert(info);
  2777. newinfo = tor_malloc(sizeof(extend_info_t));
  2778. memcpy(newinfo, info, sizeof(extend_info_t));
  2779. if (info->onion_key)
  2780. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2781. else
  2782. newinfo->onion_key = NULL;
  2783. return newinfo;
  2784. }
  2785. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2786. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2787. * the chosen exit, return NULL.
  2788. */
  2789. const node_t *
  2790. build_state_get_exit_node(cpath_build_state_t *state)
  2791. {
  2792. if (!state || !state->chosen_exit)
  2793. return NULL;
  2794. return node_get_by_id(state->chosen_exit->identity_digest);
  2795. }
  2796. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2797. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2798. * chosen exit, return NULL.
  2799. */
  2800. const char *
  2801. build_state_get_exit_nickname(cpath_build_state_t *state)
  2802. {
  2803. if (!state || !state->chosen_exit)
  2804. return NULL;
  2805. return state->chosen_exit->nickname;
  2806. }