circuitbuild.c 124 KB

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