circuitbuild.c 124 KB

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