circuitbuild.c 119 KB

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