connection_edge.c 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. *
  10. * An edge_connection_t is a subtype of a connection_t, and represents two
  11. * critical concepts in Tor: a stream, and an edge connection. From the Tor
  12. * protocol's point of view, a stream is a bi-directional channel that is
  13. * multiplexed on a single circuit. Each stream on a circuit is identified
  14. * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
  15. * Streams are created in response to client requests.
  16. *
  17. * An edge connection is one thing that can implement a stream: it is either a
  18. * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
  19. * exit connection.
  20. *
  21. * Not every instance of edge_connection_t truly represents an edge connction,
  22. * however. (Sorry!) We also create edge_connection_t objects for streams that
  23. * we will not be handling with TCP. The types of these streams are:
  24. * <ul>
  25. * <li>DNS lookup streams, created on the client side in response to
  26. * a UDP DNS request received on a DNSPort, or a RESOLVE command
  27. * on a controller.
  28. * <li>DNS lookup streams, created on the exit side in response to
  29. * a RELAY_RESOLVE cell from a client.
  30. * <li>Tunneled directory streams, created on the directory cache side
  31. * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
  32. * to a dir_connection_t object without ever using TCP.
  33. * </ul>
  34. *
  35. * This module handles general-purpose functionality having to do with
  36. * edge_connection_t. On the client side, it accepts various types of
  37. * application requests on SocksPorts, TransPorts, and NATDPorts, and
  38. * creates streams appropriately.
  39. *
  40. * This module is also responsible for implementing stream isolation:
  41. * ensuring that streams that should not be linkable to one another are
  42. * kept to different circuits.
  43. *
  44. * On the exit side, this module handles the various stream-creating
  45. * type of RELAY cells by launching appropriate outgoing connections,
  46. * DNS requests, or directory connection objects.
  47. *
  48. * And for all edge connections, this module is responsible for handling
  49. * incoming and outdoing data as it arrives or leaves in the relay.c
  50. * module. (Outgoing data will be packaged in
  51. * connection_edge_process_inbuf() as it calls
  52. * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
  53. * cells is applied in connection_edge_process_relay_cell().)
  54. **/
  55. #define CONNECTION_EDGE_PRIVATE
  56. #include "core/or/or.h"
  57. #include "lib/err/backtrace.h"
  58. #include "feature/client/addressmap.h"
  59. #include "lib/container/buffers.h"
  60. #include "core/or/channel.h"
  61. #include "feature/client/circpathbias.h"
  62. #include "core/or/circuitlist.h"
  63. #include "core/or/circuituse.h"
  64. #include "app/config/config.h"
  65. #include "core/mainloop/connection.h"
  66. #include "core/or/connection_edge.h"
  67. #include "core/or/connection_or.h"
  68. #include "feature/control/control.h"
  69. #include "lib/crypt_ops/crypto_util.h"
  70. #include "feature/relay/dns.h"
  71. #include "feature/client/dnsserv.h"
  72. #include "feature/dircache/directory.h"
  73. #include "feature/dircache/dirserv.h"
  74. #include "feature/hibernate/hibernate.h"
  75. #include "feature/hs/hs_common.h"
  76. #include "feature/hs/hs_cache.h"
  77. #include "feature/hs/hs_client.h"
  78. #include "feature/hs/hs_circuit.h"
  79. #include "core/mainloop/main.h"
  80. #include "feature/nodelist/networkstatus.h"
  81. #include "feature/nodelist/nodelist.h"
  82. #include "core/or/policies.h"
  83. #include "core/proto/proto_http.h"
  84. #include "core/proto/proto_socks.h"
  85. #include "core/or/reasons.h"
  86. #include "core/or/relay.h"
  87. #include "feature/rend/rendclient.h"
  88. #include "feature/rend/rendcommon.h"
  89. #include "feature/rend/rendservice.h"
  90. #include "feature/stats/rephist.h"
  91. #include "feature/relay/router.h"
  92. #include "feature/nodelist/routerlist.h"
  93. #include "feature/nodelist/routerset.h"
  94. #include "core/or/circuitbuild.h"
  95. #include "core/or/cell_st.h"
  96. #include "core/or/cpath_build_state_st.h"
  97. #include "feature/dircommon/dir_connection_st.h"
  98. #include "core/or/entry_connection_st.h"
  99. #include "core/or/extend_info_st.h"
  100. #include "feature/nodelist/node_st.h"
  101. #include "core/or/or_circuit_st.h"
  102. #include "core/or/origin_circuit_st.h"
  103. #include "core/or/half_edge_st.h"
  104. #include "core/or/socks_request_st.h"
  105. #include "lib/evloop/compat_libevent.h"
  106. #ifdef HAVE_LINUX_TYPES_H
  107. #include <linux/types.h>
  108. #endif
  109. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  110. #include <linux/netfilter_ipv4.h>
  111. #define TRANS_NETFILTER
  112. #define TRANS_NETFILTER_IPV4
  113. #endif
  114. #ifdef HAVE_LINUX_IF_H
  115. #include <linux/if.h>
  116. #endif
  117. #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
  118. #include <linux/netfilter_ipv6/ip6_tables.h>
  119. #if defined(IP6T_SO_ORIGINAL_DST)
  120. #define TRANS_NETFILTER
  121. #define TRANS_NETFILTER_IPV6
  122. #endif
  123. #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
  124. #ifdef HAVE_FCNTL_H
  125. #include <fcntl.h>
  126. #endif
  127. #ifdef HAVE_SYS_IOCTL_H
  128. #include <sys/ioctl.h>
  129. #endif
  130. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  131. #include <net/if.h>
  132. #include <net/pfvar.h>
  133. #define TRANS_PF
  134. #endif
  135. #ifdef IP_TRANSPARENT
  136. #define TRANS_TPROXY
  137. #endif
  138. #define SOCKS4_GRANTED 90
  139. #define SOCKS4_REJECT 91
  140. static int connection_ap_handshake_process_socks(entry_connection_t *conn);
  141. static int connection_ap_process_natd(entry_connection_t *conn);
  142. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  143. static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
  144. static int connection_ap_supports_optimistic_data(const entry_connection_t *);
  145. /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
  146. * invalid. */
  147. edge_connection_t *
  148. TO_EDGE_CONN(connection_t *c)
  149. {
  150. tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
  151. c->magic == ENTRY_CONNECTION_MAGIC);
  152. return DOWNCAST(edge_connection_t, c);
  153. }
  154. entry_connection_t *
  155. TO_ENTRY_CONN(connection_t *c)
  156. {
  157. tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
  158. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
  159. }
  160. entry_connection_t *
  161. EDGE_TO_ENTRY_CONN(edge_connection_t *c)
  162. {
  163. tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
  164. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
  165. }
  166. /** An AP stream has failed/finished. If it hasn't already sent back
  167. * a socks reply, send one now (based on endreason). Also set
  168. * has_sent_end to 1, and mark the conn.
  169. */
  170. MOCK_IMPL(void,
  171. connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
  172. int line, const char *file))
  173. {
  174. connection_t *base_conn = ENTRY_TO_CONN(conn);
  175. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  176. tor_assert(base_conn->type == CONN_TYPE_AP);
  177. ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
  178. /* If this is a rendezvous stream and it is failing without ever
  179. * being attached to a circuit, assume that an attempt to connect to
  180. * the destination hidden service has just ended.
  181. *
  182. * XXXX This condition doesn't limit to only streams failing
  183. * without ever being attached. That sloppiness should be harmless,
  184. * but we should fix it someday anyway. */
  185. if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
  186. connection_edge_is_rendezvous_stream(edge_conn)) {
  187. if (edge_conn->rend_data) {
  188. rend_client_note_connection_attempt_ended(edge_conn->rend_data);
  189. }
  190. }
  191. if (base_conn->marked_for_close) {
  192. /* This call will warn as appropriate. */
  193. connection_mark_for_close_(base_conn, line, file);
  194. return;
  195. }
  196. if (!conn->socks_request->has_finished) {
  197. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  198. log_warn(LD_BUG,
  199. "stream (marked at %s:%d) sending two socks replies?",
  200. file, line);
  201. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  202. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  203. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  204. connection_ap_handshake_socks_resolved(conn,
  205. RESOLVED_TYPE_ERROR_TRANSIENT,
  206. 0, NULL, -1, -1);
  207. else /* unknown or no handshake at all. send no response. */
  208. conn->socks_request->has_finished = 1;
  209. }
  210. connection_mark_and_flush_(base_conn, line, file);
  211. ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
  212. }
  213. /** There was an EOF. Send an end and mark the connection for close.
  214. */
  215. int
  216. connection_edge_reached_eof(edge_connection_t *conn)
  217. {
  218. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  219. connection_state_is_open(TO_CONN(conn))) {
  220. /* it still has stuff to process. don't let it die yet. */
  221. return 0;
  222. }
  223. log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
  224. conn->base_.s);
  225. if (!conn->base_.marked_for_close) {
  226. /* only mark it if not already marked. it's possible to
  227. * get the 'end' right around when the client hangs up on us. */
  228. connection_edge_end(conn, END_STREAM_REASON_DONE);
  229. if (conn->base_.type == CONN_TYPE_AP) {
  230. /* eof, so don't send a socks reply back */
  231. if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
  232. EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  233. }
  234. connection_mark_for_close(TO_CONN(conn));
  235. }
  236. return 0;
  237. }
  238. /** Handle new bytes on conn->inbuf based on state:
  239. * - If it's waiting for socks info, try to read another step of the
  240. * socks handshake out of conn->inbuf.
  241. * - If it's waiting for the original destination, fetch it.
  242. * - If it's open, then package more relay cells from the stream.
  243. * - Else, leave the bytes on inbuf alone for now.
  244. *
  245. * Mark and return -1 if there was an unexpected error with the conn,
  246. * else return 0.
  247. */
  248. int
  249. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  250. {
  251. tor_assert(conn);
  252. switch (conn->base_.state) {
  253. case AP_CONN_STATE_SOCKS_WAIT:
  254. if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
  255. /* already marked */
  256. return -1;
  257. }
  258. return 0;
  259. case AP_CONN_STATE_NATD_WAIT:
  260. if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  261. /* already marked */
  262. return -1;
  263. }
  264. return 0;
  265. case AP_CONN_STATE_HTTP_CONNECT_WAIT:
  266. if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  267. return -1;
  268. }
  269. return 0;
  270. case AP_CONN_STATE_OPEN:
  271. case EXIT_CONN_STATE_OPEN:
  272. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  273. /* (We already sent an end cell if possible) */
  274. connection_mark_for_close(TO_CONN(conn));
  275. return -1;
  276. }
  277. return 0;
  278. case AP_CONN_STATE_CONNECT_WAIT:
  279. if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
  280. log_info(LD_EDGE,
  281. "data from edge while in '%s' state. Sending it anyway. "
  282. "package_partial=%d, buflen=%ld",
  283. conn_state_to_string(conn->base_.type, conn->base_.state),
  284. package_partial,
  285. (long)connection_get_inbuf_len(TO_CONN(conn)));
  286. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
  287. /* (We already sent an end cell if possible) */
  288. connection_mark_for_close(TO_CONN(conn));
  289. return -1;
  290. }
  291. return 0;
  292. }
  293. /* Fall through if the connection is on a circuit without optimistic
  294. * data support. */
  295. /* Falls through. */
  296. case EXIT_CONN_STATE_CONNECTING:
  297. case AP_CONN_STATE_RENDDESC_WAIT:
  298. case AP_CONN_STATE_CIRCUIT_WAIT:
  299. case AP_CONN_STATE_RESOLVE_WAIT:
  300. case AP_CONN_STATE_CONTROLLER_WAIT:
  301. log_info(LD_EDGE,
  302. "data from edge while in '%s' state. Leaving it on buffer.",
  303. conn_state_to_string(conn->base_.type, conn->base_.state));
  304. return 0;
  305. }
  306. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
  307. tor_fragile_assert();
  308. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  309. connection_mark_for_close(TO_CONN(conn));
  310. return -1;
  311. }
  312. /** This edge needs to be closed, because its circuit has closed.
  313. * Mark it for close and return 0.
  314. */
  315. int
  316. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  317. {
  318. if (!conn->base_.marked_for_close) {
  319. log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
  320. (unsigned) circ_id);
  321. if (conn->base_.type == CONN_TYPE_AP) {
  322. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  323. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
  324. control_event_stream_bandwidth(conn);
  325. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  326. END_STREAM_REASON_DESTROY);
  327. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  328. } else {
  329. /* closing the circuit, nothing to send an END to */
  330. conn->edge_has_sent_end = 1;
  331. conn->end_reason = END_STREAM_REASON_DESTROY;
  332. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  333. connection_mark_and_flush(TO_CONN(conn));
  334. }
  335. }
  336. conn->cpath_layer = NULL;
  337. conn->on_circuit = NULL;
  338. return 0;
  339. }
  340. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  341. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  342. * is not a client connection, set the relay end cell's reason for closing
  343. * as <b>reason</b> */
  344. static int
  345. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  346. uint8_t reason, crypt_path_t *cpath_layer)
  347. {
  348. char payload[1];
  349. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  350. /* Never send the server an informative reason code; it doesn't need to
  351. * know why the client stream is failing. */
  352. reason = END_STREAM_REASON_MISC;
  353. }
  354. payload[0] = (char) reason;
  355. /* Note: we have to use relay_send_command_from_edge here, not
  356. * connection_edge_end or connection_edge_send_command, since those require
  357. * that we have a stream connected to a circuit, and we don't connect to a
  358. * circuit until we have a pending/successful resolve. */
  359. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  360. payload, 1, cpath_layer);
  361. }
  362. /* If the connection <b>conn</b> is attempting to connect to an external
  363. * destination that is an hidden service and the reason is a connection
  364. * refused or timeout, log it so the operator can take appropriate actions.
  365. * The log statement is a rate limited warning. */
  366. static void
  367. warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
  368. {
  369. tor_assert(conn);
  370. if (conn->base_.type == CONN_TYPE_EXIT &&
  371. connection_edge_is_rendezvous_stream(conn) &&
  372. (reason == END_STREAM_REASON_CONNECTREFUSED ||
  373. reason == END_STREAM_REASON_TIMEOUT)) {
  374. #define WARN_FAILED_HS_CONNECTION 300
  375. static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
  376. char *m;
  377. if ((m = rate_limit_log(&warn_limit, approx_time()))) {
  378. log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
  379. (conn->base_.socket_family == AF_UNIX) ?
  380. safe_str(conn->base_.address) :
  381. safe_str(fmt_addrport(&conn->base_.addr, conn->base_.port)),
  382. stream_end_reason_to_string(reason));
  383. tor_free(m);
  384. }
  385. }
  386. }
  387. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  388. * remember that we've done so. If this is not a client connection, set the
  389. * relay end cell's reason for closing as <b>reason</b>.
  390. *
  391. * Return -1 if this function has already been called on this conn,
  392. * else return 0.
  393. */
  394. int
  395. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  396. {
  397. char payload[RELAY_PAYLOAD_SIZE];
  398. size_t payload_len=1;
  399. circuit_t *circ;
  400. uint8_t control_reason = reason;
  401. if (conn->edge_has_sent_end) {
  402. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  403. "on an already ended stream?", reason);
  404. tor_fragile_assert();
  405. return -1;
  406. }
  407. if (conn->base_.marked_for_close) {
  408. log_warn(LD_BUG,
  409. "called on conn that's already marked for close at %s:%d.",
  410. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  411. return 0;
  412. }
  413. circ = circuit_get_by_edge_conn(conn);
  414. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  415. /* If this is a client circuit, don't send the server an informative
  416. * reason code; it doesn't need to know why the client stream is
  417. * failing. */
  418. reason = END_STREAM_REASON_MISC;
  419. }
  420. payload[0] = (char)reason;
  421. if (reason == END_STREAM_REASON_EXITPOLICY &&
  422. !connection_edge_is_rendezvous_stream(conn)) {
  423. int addrlen;
  424. if (tor_addr_family(&conn->base_.addr) == AF_INET) {
  425. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
  426. addrlen = 4;
  427. } else {
  428. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
  429. addrlen = 16;
  430. }
  431. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  432. payload_len += 4+addrlen;
  433. }
  434. if (circ && !circ->marked_for_close) {
  435. log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
  436. conn->base_.s);
  437. if (CIRCUIT_IS_ORIGIN(circ)) {
  438. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  439. connection_half_edge_add(conn, origin_circ);
  440. }
  441. connection_edge_send_command(conn, RELAY_COMMAND_END,
  442. payload, payload_len);
  443. /* We'll log warn if the connection was an hidden service and couldn't be
  444. * made because the service wasn't available. */
  445. warn_if_hs_unreachable(conn, control_reason);
  446. } else {
  447. log_debug(LD_EDGE,"No circ to send end on conn "
  448. "(fd "TOR_SOCKET_T_FORMAT").",
  449. conn->base_.s);
  450. }
  451. conn->edge_has_sent_end = 1;
  452. conn->end_reason = control_reason;
  453. return 0;
  454. }
  455. /**
  456. * Helper function for bsearch.
  457. *
  458. * As per smartlist_bsearch, return < 0 if key preceeds member,
  459. * > 0 if member preceeds key, and 0 if they are equal.
  460. *
  461. * This is equivalent to subtraction of the values of key - member
  462. * (why does no one ever say that explicitly?).
  463. */
  464. static int
  465. connection_half_edge_compare_bsearch(const void *key, const void **member)
  466. {
  467. const half_edge_t *e2;
  468. tor_assert(key);
  469. tor_assert(member && *(half_edge_t**)member);
  470. e2 = *(const half_edge_t **)member;
  471. return *(const streamid_t*)key - e2->stream_id;
  472. }
  473. /**
  474. * Add a half-closed connection to the list, to watch for activity.
  475. *
  476. * These connections are removed from the list upon receiving an end
  477. * cell.
  478. */
  479. STATIC void
  480. connection_half_edge_add(const edge_connection_t *conn,
  481. origin_circuit_t *circ)
  482. {
  483. half_edge_t *half_conn = NULL;
  484. int insert_at = 0;
  485. int ignored;
  486. /* Double-check for re-insertion. This should not happen,
  487. * but this check is cheap compared to the sort anyway */
  488. if (connection_half_edge_find_stream_id(circ->half_streams,
  489. conn->stream_id)) {
  490. log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
  491. conn->stream_id, circ->global_identifier);
  492. return;
  493. }
  494. half_conn = tor_malloc_zero(sizeof(half_edge_t));
  495. if (!circ->half_streams) {
  496. circ->half_streams = smartlist_new();
  497. }
  498. half_conn->stream_id = conn->stream_id;
  499. // How many sendme's should I expect?
  500. half_conn->sendmes_pending =
  501. (STREAMWINDOW_START-conn->package_window)/STREAMWINDOW_INCREMENT;
  502. // Is there a connected cell pending?
  503. half_conn->connected_pending = conn->base_.state ==
  504. AP_CONN_STATE_CONNECT_WAIT;
  505. /* Data should only arrive if we're not waiting on a resolved cell.
  506. * It can arrive after waiting on connected, because of optimistic
  507. * data. */
  508. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  509. // How many more data cells can arrive on this id?
  510. half_conn->data_pending = conn->deliver_window;
  511. }
  512. insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
  513. connection_half_edge_compare_bsearch,
  514. &ignored);
  515. smartlist_insert(circ->half_streams, insert_at, half_conn);
  516. }
  517. /**
  518. * Find a stream_id_t in the list in O(lg(n)).
  519. *
  520. * Returns NULL if the list is empty or element is not found.
  521. * Returns a pointer to the element if found.
  522. */
  523. STATIC half_edge_t *
  524. connection_half_edge_find_stream_id(const smartlist_t *half_conns,
  525. streamid_t stream_id)
  526. {
  527. if (!half_conns)
  528. return NULL;
  529. return smartlist_bsearch(half_conns, &stream_id,
  530. connection_half_edge_compare_bsearch);
  531. }
  532. /**
  533. * Check if this stream_id is in a half-closed state. If so,
  534. * check if it still has data cells pending, and decrement that
  535. * window if so.
  536. *
  537. * Return 1 if the data window was not empty.
  538. * Return 0 otherwise.
  539. */
  540. int
  541. connection_half_edge_is_valid_data(const smartlist_t *half_conns,
  542. streamid_t stream_id)
  543. {
  544. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  545. stream_id);
  546. if (!half)
  547. return 0;
  548. if (half->data_pending > 0) {
  549. half->data_pending--;
  550. return 1;
  551. }
  552. return 0;
  553. }
  554. /**
  555. * Check if this stream_id is in a half-closed state. If so,
  556. * check if it still has a connected cell pending, and decrement
  557. * that window if so.
  558. *
  559. * Return 1 if the connected window was not empty.
  560. * Return 0 otherwise.
  561. */
  562. int
  563. connection_half_edge_is_valid_connected(const smartlist_t *half_conns,
  564. streamid_t stream_id)
  565. {
  566. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  567. stream_id);
  568. if (!half)
  569. return 0;
  570. if (half->connected_pending) {
  571. half->connected_pending = 0;
  572. return 1;
  573. }
  574. return 0;
  575. }
  576. /**
  577. * Check if this stream_id is in a half-closed state. If so,
  578. * check if it still has sendme cells pending, and decrement that
  579. * window if so.
  580. *
  581. * Return 1 if the sendme window was not empty.
  582. * Return 0 otherwise.
  583. */
  584. int
  585. connection_half_edge_is_valid_sendme(const smartlist_t *half_conns,
  586. streamid_t stream_id)
  587. {
  588. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  589. stream_id);
  590. if (!half)
  591. return 0;
  592. if (half->sendmes_pending > 0) {
  593. half->sendmes_pending--;
  594. return 1;
  595. }
  596. return 0;
  597. }
  598. /**
  599. * Check if this stream_id is in a half-closed state. If so, remove
  600. * it from the list. No other data should come after the END cell.
  601. *
  602. * Return 1 if stream_id was in half-closed state.
  603. * Return 0 otherwise.
  604. */
  605. int
  606. connection_half_edge_is_valid_end(smartlist_t *half_conns,
  607. streamid_t stream_id)
  608. {
  609. half_edge_t *half;
  610. int found, remove_idx;
  611. if (!half_conns)
  612. return 0;
  613. remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
  614. connection_half_edge_compare_bsearch,
  615. &found);
  616. if (!found)
  617. return 0;
  618. half = smartlist_get(half_conns, remove_idx);
  619. smartlist_del_keeporder(half_conns, remove_idx);
  620. tor_free(half);
  621. return 1;
  622. }
  623. /**
  624. * Streams that were used to send a RESOLVE cell are closed
  625. * when they get the RESOLVED, without an end. So treat
  626. * a RESOLVED just like an end, and remove from the list.
  627. */
  628. int
  629. connection_half_edge_is_valid_resolved(smartlist_t *half_conns,
  630. streamid_t stream_id)
  631. {
  632. return connection_half_edge_is_valid_end(half_conns, stream_id);
  633. }
  634. /** An error has just occurred on an operation on an edge connection
  635. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  636. * appropriate relay end cell to the other end of the connection's circuit.
  637. **/
  638. int
  639. connection_edge_end_errno(edge_connection_t *conn)
  640. {
  641. uint8_t reason;
  642. tor_assert(conn);
  643. reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
  644. return connection_edge_end(conn, reason);
  645. }
  646. /** We just wrote some data to <b>conn</b>; act appropriately.
  647. *
  648. * (That is, if it's open, consider sending a stream-level sendme cell if we
  649. * have just flushed enough.)
  650. */
  651. int
  652. connection_edge_flushed_some(edge_connection_t *conn)
  653. {
  654. switch (conn->base_.state) {
  655. case AP_CONN_STATE_OPEN:
  656. case EXIT_CONN_STATE_OPEN:
  657. connection_edge_consider_sending_sendme(conn);
  658. break;
  659. }
  660. return 0;
  661. }
  662. /** Connection <b>conn</b> has finished writing and has no bytes left on
  663. * its outbuf.
  664. *
  665. * If it's in state 'open', stop writing, consider responding with a
  666. * sendme, and return.
  667. * Otherwise, stop writing and return.
  668. *
  669. * If <b>conn</b> is broken, mark it for close and return -1, else
  670. * return 0.
  671. */
  672. int
  673. connection_edge_finished_flushing(edge_connection_t *conn)
  674. {
  675. tor_assert(conn);
  676. switch (conn->base_.state) {
  677. case AP_CONN_STATE_OPEN:
  678. case EXIT_CONN_STATE_OPEN:
  679. connection_edge_consider_sending_sendme(conn);
  680. return 0;
  681. case AP_CONN_STATE_SOCKS_WAIT:
  682. case AP_CONN_STATE_NATD_WAIT:
  683. case AP_CONN_STATE_RENDDESC_WAIT:
  684. case AP_CONN_STATE_CIRCUIT_WAIT:
  685. case AP_CONN_STATE_CONNECT_WAIT:
  686. case AP_CONN_STATE_CONTROLLER_WAIT:
  687. case AP_CONN_STATE_RESOLVE_WAIT:
  688. case AP_CONN_STATE_HTTP_CONNECT_WAIT:
  689. return 0;
  690. default:
  691. log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
  692. tor_fragile_assert();
  693. return -1;
  694. }
  695. return 0;
  696. }
  697. /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
  698. * able to generate. */
  699. /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
  700. #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
  701. /** Set the buffer at <b>payload_out</b> -- which must have at least
  702. * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
  703. * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
  704. * that the name resolution that led us to <b>addr</b> will be valid for
  705. * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
  706. * success. */
  707. STATIC int
  708. connected_cell_format_payload(uint8_t *payload_out,
  709. const tor_addr_t *addr,
  710. uint32_t ttl)
  711. {
  712. const sa_family_t family = tor_addr_family(addr);
  713. int connected_payload_len;
  714. /* should be needless */
  715. memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
  716. if (family == AF_INET) {
  717. set_uint32(payload_out, tor_addr_to_ipv4n(addr));
  718. connected_payload_len = 4;
  719. } else if (family == AF_INET6) {
  720. set_uint32(payload_out, 0);
  721. set_uint8(payload_out + 4, 6);
  722. memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
  723. connected_payload_len = 21;
  724. } else {
  725. return -1;
  726. }
  727. set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
  728. connected_payload_len += 4;
  729. tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
  730. return connected_payload_len;
  731. }
  732. /** Connected handler for exit connections: start writing pending
  733. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  734. * any pending data that may have been received. */
  735. int
  736. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  737. {
  738. connection_t *conn;
  739. tor_assert(edge_conn);
  740. tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
  741. conn = TO_CONN(edge_conn);
  742. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  743. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  744. escaped_safe_str(conn->address), conn->port,
  745. safe_str(fmt_and_decorate_addr(&conn->addr)));
  746. rep_hist_note_exit_stream_opened(conn->port);
  747. conn->state = EXIT_CONN_STATE_OPEN;
  748. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  749. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  750. * cells */
  751. connection_start_writing(conn);
  752. /* deliver a 'connected' relay cell back through the circuit. */
  753. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  754. if (connection_edge_send_command(edge_conn,
  755. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  756. return 0; /* circuit is closed, don't continue */
  757. } else {
  758. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  759. int connected_payload_len =
  760. connected_cell_format_payload(connected_payload, &conn->addr,
  761. edge_conn->address_ttl);
  762. if (connected_payload_len < 0)
  763. return -1;
  764. if (connection_edge_send_command(edge_conn,
  765. RELAY_COMMAND_CONNECTED,
  766. (char*)connected_payload, connected_payload_len) < 0)
  767. return 0; /* circuit is closed, don't continue */
  768. }
  769. tor_assert(edge_conn->package_window > 0);
  770. /* in case the server has written anything */
  771. return connection_edge_process_inbuf(edge_conn, 1);
  772. }
  773. /** A list of all the entry_connection_t * objects that are not marked
  774. * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
  775. *
  776. * (Right now, we check in several places to make sure that this list is
  777. * correct. When it's incorrect, we'll fix it, and log a BUG message.)
  778. */
  779. static smartlist_t *pending_entry_connections = NULL;
  780. static int untried_pending_connections = 0;
  781. /**
  782. * Mainloop event to tell us to scan for pending connections that can
  783. * be attached.
  784. */
  785. static mainloop_event_t *attach_pending_entry_connections_ev = NULL;
  786. /** Common code to connection_(ap|exit)_about_to_close. */
  787. static void
  788. connection_edge_about_to_close(edge_connection_t *edge_conn)
  789. {
  790. if (!edge_conn->edge_has_sent_end) {
  791. connection_t *conn = TO_CONN(edge_conn);
  792. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  793. "hasn't sent end yet?",
  794. conn->marked_for_close_file, conn->marked_for_close);
  795. tor_fragile_assert();
  796. }
  797. }
  798. /** Called when we're about to finally unlink and free an AP (client)
  799. * connection: perform necessary accounting and cleanup */
  800. void
  801. connection_ap_about_to_close(entry_connection_t *entry_conn)
  802. {
  803. circuit_t *circ;
  804. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  805. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  806. connection_edge_about_to_close(edge_conn);
  807. if (entry_conn->socks_request->has_finished == 0) {
  808. /* since conn gets removed right after this function finishes,
  809. * there's no point trying to send back a reply at this point. */
  810. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  811. " back a socks reply.",
  812. conn->marked_for_close_file, conn->marked_for_close);
  813. }
  814. if (!edge_conn->end_reason) {
  815. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  816. " set end_reason.",
  817. conn->marked_for_close_file, conn->marked_for_close);
  818. }
  819. if (entry_conn->dns_server_request) {
  820. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  821. " replied to DNS request.",
  822. conn->marked_for_close_file, conn->marked_for_close);
  823. dnsserv_reject_request(entry_conn);
  824. }
  825. if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  826. smartlist_remove(pending_entry_connections, entry_conn);
  827. }
  828. #if 1
  829. /* Check to make sure that this isn't in pending_entry_connections if it
  830. * didn't actually belong there. */
  831. if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
  832. connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
  833. "about_to_close");
  834. }
  835. #endif /* 1 */
  836. control_event_stream_bandwidth(edge_conn);
  837. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  838. edge_conn->end_reason);
  839. circ = circuit_get_by_edge_conn(edge_conn);
  840. if (circ)
  841. circuit_detach_stream(circ, edge_conn);
  842. }
  843. /** Called when we're about to finally unlink and free an exit
  844. * connection: perform necessary accounting and cleanup */
  845. void
  846. connection_exit_about_to_close(edge_connection_t *edge_conn)
  847. {
  848. circuit_t *circ;
  849. connection_t *conn = TO_CONN(edge_conn);
  850. connection_edge_about_to_close(edge_conn);
  851. circ = circuit_get_by_edge_conn(edge_conn);
  852. if (circ)
  853. circuit_detach_stream(circ, edge_conn);
  854. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  855. connection_dns_remove(edge_conn);
  856. }
  857. }
  858. /** Define a schedule for how long to wait between retrying
  859. * application connections. Rather than waiting a fixed amount of
  860. * time between each retry, we wait 10 seconds each for the first
  861. * two tries, and 15 seconds for each retry after
  862. * that. Hopefully this will improve the expected user experience. */
  863. static int
  864. compute_retry_timeout(entry_connection_t *conn)
  865. {
  866. int timeout = get_options()->CircuitStreamTimeout;
  867. if (timeout) /* if our config options override the default, use them */
  868. return timeout;
  869. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  870. return 10;
  871. return 15;
  872. }
  873. /** Find all general-purpose AP streams waiting for a response that sent their
  874. * begin/resolve cell too long ago. Detach from their current circuit, and
  875. * mark their current circuit as unsuitable for new streams. Then call
  876. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  877. * available) or launch a new one.
  878. *
  879. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  880. * retry attempt).
  881. */
  882. void
  883. connection_ap_expire_beginning(void)
  884. {
  885. edge_connection_t *conn;
  886. entry_connection_t *entry_conn;
  887. circuit_t *circ;
  888. time_t now = time(NULL);
  889. const or_options_t *options = get_options();
  890. int severity;
  891. int cutoff;
  892. int seconds_idle, seconds_since_born;
  893. smartlist_t *conns = get_connection_array();
  894. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  895. if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
  896. continue;
  897. entry_conn = TO_ENTRY_CONN(base_conn);
  898. conn = ENTRY_TO_EDGE_CONN(entry_conn);
  899. /* if it's an internal linked connection, don't yell its status. */
  900. severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
  901. ? LOG_INFO : LOG_NOTICE;
  902. seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
  903. seconds_since_born = (int)( now - base_conn->timestamp_created );
  904. if (base_conn->state == AP_CONN_STATE_OPEN)
  905. continue;
  906. /* We already consider SocksTimeout in
  907. * connection_ap_handshake_attach_circuit(), but we need to consider
  908. * it here too because controllers that put streams in controller_wait
  909. * state never ask Tor to attach the circuit. */
  910. if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
  911. if (seconds_since_born >= options->SocksTimeout) {
  912. log_fn(severity, LD_APP,
  913. "Tried for %d seconds to get a connection to %s:%d. "
  914. "Giving up. (%s)",
  915. seconds_since_born,
  916. safe_str_client(entry_conn->socks_request->address),
  917. entry_conn->socks_request->port,
  918. conn_state_to_string(CONN_TYPE_AP, base_conn->state));
  919. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  920. }
  921. continue;
  922. }
  923. /* We're in state connect_wait or resolve_wait now -- waiting for a
  924. * reply to our relay cell. See if we want to retry/give up. */
  925. cutoff = compute_retry_timeout(entry_conn);
  926. if (seconds_idle < cutoff)
  927. continue;
  928. circ = circuit_get_by_edge_conn(conn);
  929. if (!circ) { /* it's vanished? */
  930. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  931. safe_str_client(entry_conn->socks_request->address));
  932. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  933. continue;
  934. }
  935. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  936. if (seconds_idle >= options->SocksTimeout) {
  937. log_fn(severity, LD_REND,
  938. "Rend stream is %d seconds late. Giving up on address"
  939. " '%s.onion'.",
  940. seconds_idle,
  941. safe_str_client(entry_conn->socks_request->address));
  942. /* Roll back path bias use state so that we probe the circuit
  943. * if nothing else succeeds on it */
  944. pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
  945. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  946. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  947. }
  948. continue;
  949. }
  950. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  951. circ->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
  952. circ->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
  953. circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  954. circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  955. log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
  956. "The purpose on the circuit was %s; it was in state %s, "
  957. "path_state %s.",
  958. circuit_purpose_to_string(circ->purpose),
  959. circuit_state_to_string(circ->state),
  960. CIRCUIT_IS_ORIGIN(circ) ?
  961. pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
  962. "none");
  963. }
  964. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  965. "We tried for %d seconds to connect to '%s' using exit %s."
  966. " Retrying on a new circuit.",
  967. seconds_idle,
  968. safe_str_client(entry_conn->socks_request->address),
  969. conn->cpath_layer ?
  970. extend_info_describe(conn->cpath_layer->extend_info):
  971. "*unnamed*");
  972. /* send an end down the circuit */
  973. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  974. /* un-mark it as ending, since we're going to reuse it */
  975. conn->edge_has_sent_end = 0;
  976. conn->end_reason = 0;
  977. /* make us not try this circuit again, but allow
  978. * current streams on it to survive if they can */
  979. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  980. /* give our stream another 'cutoff' seconds to try */
  981. conn->base_.timestamp_last_read_allowed += cutoff;
  982. if (entry_conn->num_socks_retries < 250) /* avoid overflow */
  983. entry_conn->num_socks_retries++;
  984. /* move it back into 'pending' state, and try to attach. */
  985. if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
  986. END_STREAM_REASON_TIMEOUT)<0) {
  987. if (!base_conn->marked_for_close)
  988. connection_mark_unattached_ap(entry_conn,
  989. END_STREAM_REASON_CANT_ATTACH);
  990. }
  991. } SMARTLIST_FOREACH_END(base_conn);
  992. }
  993. /**
  994. * As connection_ap_attach_pending, but first scans the entire connection
  995. * array to see if any elements are missing.
  996. */
  997. void
  998. connection_ap_rescan_and_attach_pending(void)
  999. {
  1000. entry_connection_t *entry_conn;
  1001. smartlist_t *conns = get_connection_array();
  1002. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  1003. pending_entry_connections = smartlist_new();
  1004. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1005. if (conn->marked_for_close ||
  1006. conn->type != CONN_TYPE_AP ||
  1007. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1008. continue;
  1009. entry_conn = TO_ENTRY_CONN(conn);
  1010. tor_assert(entry_conn);
  1011. if (! smartlist_contains(pending_entry_connections, entry_conn)) {
  1012. log_warn(LD_BUG, "Found a connection %p that was supposed to be "
  1013. "in pending_entry_connections, but wasn't. No worries; "
  1014. "adding it.",
  1015. pending_entry_connections);
  1016. untried_pending_connections = 1;
  1017. connection_ap_mark_as_pending_circuit(entry_conn);
  1018. }
  1019. } SMARTLIST_FOREACH_END(conn);
  1020. connection_ap_attach_pending(1);
  1021. }
  1022. #ifdef DEBUGGING_17659
  1023. #define UNMARK() do { \
  1024. entry_conn->marked_pending_circ_line = 0; \
  1025. entry_conn->marked_pending_circ_file = 0; \
  1026. } while (0)
  1027. #else /* !(defined(DEBUGGING_17659)) */
  1028. #define UNMARK() do { } while (0)
  1029. #endif /* defined(DEBUGGING_17659) */
  1030. /** Tell any AP streams that are listed as waiting for a new circuit to try
  1031. * again. If there is an available circuit for a stream, attach it. Otherwise,
  1032. * launch a new circuit.
  1033. *
  1034. * If <b>retry</b> is false, only check the list if it contains at least one
  1035. * streams that we have not yet tried to attach to a circuit.
  1036. */
  1037. void
  1038. connection_ap_attach_pending(int retry)
  1039. {
  1040. if (PREDICT_UNLIKELY(!pending_entry_connections)) {
  1041. return;
  1042. }
  1043. if (untried_pending_connections == 0 && !retry)
  1044. return;
  1045. /* Don't allow any modifications to list while we are iterating over
  1046. * it. We'll put streams back on this list if we can't attach them
  1047. * immediately. */
  1048. smartlist_t *pending = pending_entry_connections;
  1049. pending_entry_connections = smartlist_new();
  1050. SMARTLIST_FOREACH_BEGIN(pending,
  1051. entry_connection_t *, entry_conn) {
  1052. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  1053. tor_assert(conn && entry_conn);
  1054. if (conn->marked_for_close) {
  1055. UNMARK();
  1056. continue;
  1057. }
  1058. if (conn->magic != ENTRY_CONNECTION_MAGIC) {
  1059. log_warn(LD_BUG, "%p has impossible magic value %u.",
  1060. entry_conn, (unsigned)conn->magic);
  1061. UNMARK();
  1062. continue;
  1063. }
  1064. if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  1065. log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
  1066. "is %s. Why is it on pending_entry_connections?",
  1067. entry_conn,
  1068. conn_state_to_string(conn->type, conn->state));
  1069. UNMARK();
  1070. continue;
  1071. }
  1072. /* Okay, we're through the sanity checks. Try to handle this stream. */
  1073. if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
  1074. if (!conn->marked_for_close)
  1075. connection_mark_unattached_ap(entry_conn,
  1076. END_STREAM_REASON_CANT_ATTACH);
  1077. }
  1078. if (! conn->marked_for_close &&
  1079. conn->type == CONN_TYPE_AP &&
  1080. conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  1081. /* Is it still waiting for a circuit? If so, we didn't attach it,
  1082. * so it's still pending. Put it back on the list.
  1083. */
  1084. if (!smartlist_contains(pending_entry_connections, entry_conn)) {
  1085. smartlist_add(pending_entry_connections, entry_conn);
  1086. continue;
  1087. }
  1088. }
  1089. /* If we got here, then we either closed the connection, or
  1090. * we attached it. */
  1091. UNMARK();
  1092. } SMARTLIST_FOREACH_END(entry_conn);
  1093. smartlist_free(pending);
  1094. untried_pending_connections = 0;
  1095. }
  1096. static void
  1097. attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
  1098. {
  1099. (void)ev;
  1100. (void)arg;
  1101. connection_ap_attach_pending(0);
  1102. }
  1103. /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
  1104. *
  1105. * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
  1106. * should not already be pending a circuit. The circuit will get
  1107. * launched or the connection will get attached the next time we
  1108. * call connection_ap_attach_pending().
  1109. */
  1110. void
  1111. connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
  1112. const char *fname, int lineno)
  1113. {
  1114. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  1115. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1116. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  1117. if (conn->marked_for_close)
  1118. return;
  1119. if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
  1120. pending_entry_connections = smartlist_new();
  1121. }
  1122. if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
  1123. attach_pending_entry_connections_ev = mainloop_event_postloop_new(
  1124. attach_pending_entry_connections_cb, NULL);
  1125. }
  1126. if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
  1127. entry_conn))) {
  1128. log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
  1129. "(Called from %s:%d.)",
  1130. entry_conn, fname, lineno);
  1131. #ifdef DEBUGGING_17659
  1132. const char *f2 = entry_conn->marked_pending_circ_file;
  1133. log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
  1134. f2 ? f2 : "<NULL>",
  1135. entry_conn->marked_pending_circ_line);
  1136. #endif /* defined(DEBUGGING_17659) */
  1137. log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
  1138. return;
  1139. }
  1140. #ifdef DEBUGGING_17659
  1141. entry_conn->marked_pending_circ_line = (uint16_t) lineno;
  1142. entry_conn->marked_pending_circ_file = fname;
  1143. #endif
  1144. untried_pending_connections = 1;
  1145. smartlist_add(pending_entry_connections, entry_conn);
  1146. mainloop_event_activate(attach_pending_entry_connections_ev);
  1147. }
  1148. /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
  1149. void
  1150. connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
  1151. {
  1152. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  1153. return;
  1154. UNMARK();
  1155. smartlist_remove(pending_entry_connections, entry_conn);
  1156. }
  1157. /* DOCDOC */
  1158. void
  1159. connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
  1160. const char *where)
  1161. {
  1162. if (pending_entry_connections &&
  1163. smartlist_contains(pending_entry_connections, entry_conn)) {
  1164. log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
  1165. entry_conn, where);
  1166. connection_ap_mark_as_non_pending_circuit(entry_conn);
  1167. }
  1168. }
  1169. /** Tell any AP streams that are waiting for a one-hop tunnel to
  1170. * <b>failed_digest</b> that they are going to fail. */
  1171. /* XXXX We should get rid of this function, and instead attach
  1172. * one-hop streams to circ->p_streams so they get marked in
  1173. * circuit_mark_for_close like normal p_streams. */
  1174. void
  1175. connection_ap_fail_onehop(const char *failed_digest,
  1176. cpath_build_state_t *build_state)
  1177. {
  1178. entry_connection_t *entry_conn;
  1179. char digest[DIGEST_LEN];
  1180. smartlist_t *conns = get_connection_array();
  1181. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1182. if (conn->marked_for_close ||
  1183. conn->type != CONN_TYPE_AP ||
  1184. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1185. continue;
  1186. entry_conn = TO_ENTRY_CONN(conn);
  1187. if (!entry_conn->want_onehop)
  1188. continue;
  1189. if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
  1190. tor_memneq(digest, failed_digest, DIGEST_LEN))
  1191. continue;
  1192. if (tor_digest_is_zero(digest)) {
  1193. /* we don't know the digest; have to compare addr:port */
  1194. tor_addr_t addr;
  1195. if (!build_state || !build_state->chosen_exit ||
  1196. !entry_conn->socks_request) {
  1197. continue;
  1198. }
  1199. if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
  1200. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  1201. build_state->chosen_exit->port != entry_conn->socks_request->port)
  1202. continue;
  1203. }
  1204. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  1205. "just failed.", entry_conn->chosen_exit_name,
  1206. entry_conn->socks_request->address);
  1207. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  1208. } SMARTLIST_FOREACH_END(conn);
  1209. }
  1210. /** A circuit failed to finish on its last hop <b>info</b>. If there
  1211. * are any streams waiting with this exit node in mind, but they
  1212. * don't absolutely require it, make them give up on it.
  1213. */
  1214. void
  1215. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  1216. {
  1217. entry_connection_t *entry_conn;
  1218. const node_t *r1, *r2;
  1219. smartlist_t *conns = get_connection_array();
  1220. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1221. if (conn->marked_for_close ||
  1222. conn->type != CONN_TYPE_AP ||
  1223. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1224. continue;
  1225. entry_conn = TO_ENTRY_CONN(conn);
  1226. if (!entry_conn->chosen_exit_optional &&
  1227. !entry_conn->chosen_exit_retries)
  1228. continue;
  1229. r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
  1230. NNF_NO_WARN_UNNAMED);
  1231. r2 = node_get_by_id(info->identity_digest);
  1232. if (!r1 || !r2 || r1 != r2)
  1233. continue;
  1234. tor_assert(entry_conn->socks_request);
  1235. if (entry_conn->chosen_exit_optional) {
  1236. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  1237. safe_str_client(entry_conn->chosen_exit_name),
  1238. escaped_safe_str_client(entry_conn->socks_request->address));
  1239. entry_conn->chosen_exit_optional = 0;
  1240. tor_free(entry_conn->chosen_exit_name); /* clears it */
  1241. /* if this port is dangerous, warn or reject it now that we don't
  1242. * think it'll be using an enclave. */
  1243. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  1244. }
  1245. if (entry_conn->chosen_exit_retries) {
  1246. if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
  1247. clear_trackexithost_mappings(entry_conn->chosen_exit_name);
  1248. tor_free(entry_conn->chosen_exit_name); /* clears it */
  1249. /* if this port is dangerous, warn or reject it now that we don't
  1250. * think it'll be using an enclave. */
  1251. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  1252. }
  1253. }
  1254. } SMARTLIST_FOREACH_END(conn);
  1255. }
  1256. /** The AP connection <b>conn</b> has just failed while attaching or
  1257. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  1258. * might work. Detach the circuit, and either reattach it, launch a
  1259. * new circuit, tell the controller, or give up as appropriate.
  1260. *
  1261. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  1262. */
  1263. int
  1264. connection_ap_detach_retriable(entry_connection_t *conn,
  1265. origin_circuit_t *circ,
  1266. int reason)
  1267. {
  1268. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  1269. ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
  1270. /* Roll back path bias use state so that we probe the circuit
  1271. * if nothing else succeeds on it */
  1272. pathbias_mark_use_rollback(circ);
  1273. if (conn->pending_optimistic_data) {
  1274. buf_set_to_copy(&conn->sending_optimistic_data,
  1275. conn->pending_optimistic_data);
  1276. }
  1277. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  1278. /* If we're attaching streams ourself, or if this connection is
  1279. * a tunneled directory connection, then just attach it. */
  1280. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1281. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1282. connection_ap_mark_as_pending_circuit(conn);
  1283. } else {
  1284. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1285. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1286. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1287. }
  1288. return 0;
  1289. }
  1290. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  1291. * reject depending on our config options. */
  1292. static int
  1293. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  1294. {
  1295. const or_options_t *options = get_options();
  1296. int reject = smartlist_contains_int_as_string(
  1297. options->RejectPlaintextPorts, port);
  1298. if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
  1299. log_warn(LD_APP, "Application request to port %d: this port is "
  1300. "commonly used for unencrypted protocols. Please make sure "
  1301. "you don't send anything you would mind the rest of the "
  1302. "Internet reading!%s", port, reject ? " Closing." : "");
  1303. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  1304. port, reject ? "REJECT" : "WARN");
  1305. }
  1306. if (reject) {
  1307. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  1308. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1309. return -1;
  1310. }
  1311. return 0;
  1312. }
  1313. /** How many times do we try connecting with an exit configured via
  1314. * TrackHostExits before concluding that it won't work any more and trying a
  1315. * different one? */
  1316. #define TRACKHOSTEXITS_RETRIES 5
  1317. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  1318. * asked us to leave streams unattached. Return 0 in that case.
  1319. *
  1320. * See connection_ap_handshake_rewrite_and_attach()'s
  1321. * documentation for arguments and return value.
  1322. */
  1323. MOCK_IMPL(int,
  1324. connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
  1325. origin_circuit_t *circ,
  1326. crypt_path_t *cpath))
  1327. {
  1328. const or_options_t *options = get_options();
  1329. if (options->LeaveStreamsUnattached) {
  1330. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1331. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1332. return 0;
  1333. }
  1334. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  1335. }
  1336. /* Try to perform any map-based rewriting of the target address in
  1337. * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
  1338. * conn->socks_request.address as appropriate.
  1339. */
  1340. STATIC void
  1341. connection_ap_handshake_rewrite(entry_connection_t *conn,
  1342. rewrite_result_t *out)
  1343. {
  1344. socks_request_t *socks = conn->socks_request;
  1345. const or_options_t *options = get_options();
  1346. tor_addr_t addr_tmp;
  1347. /* Initialize all the fields of 'out' to reasonable defaults */
  1348. out->automap = 0;
  1349. out->exit_source = ADDRMAPSRC_NONE;
  1350. out->map_expires = TIME_MAX;
  1351. out->end_reason = 0;
  1352. out->should_close = 0;
  1353. out->orig_address[0] = 0;
  1354. /* We convert all incoming addresses to lowercase. */
  1355. tor_strlower(socks->address);
  1356. /* Remember the original address. */
  1357. strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
  1358. log_debug(LD_APP,"Client asked for %s:%d",
  1359. safe_str_client(socks->address),
  1360. socks->port);
  1361. /* Check for whether this is a .exit address. By default, those are
  1362. * disallowed when they're coming straight from the client, but you're
  1363. * allowed to have them in MapAddress commands and so forth. */
  1364. if (!strcmpend(socks->address, ".exit")) {
  1365. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  1366. "security risks.");
  1367. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1368. escaped(socks->address));
  1369. out->end_reason = END_STREAM_REASON_TORPROTOCOL;
  1370. out->should_close = 1;
  1371. return;
  1372. }
  1373. /* Remember the original address so we can tell the user about what
  1374. * they actually said, not just what it turned into. */
  1375. /* XXX yes, this is the same as out->orig_address above. One is
  1376. * in the output, and one is in the connection. */
  1377. if (! conn->original_dest_address) {
  1378. /* Is the 'if' necessary here? XXXX */
  1379. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  1380. }
  1381. /* First, apply MapAddress and MAPADDRESS mappings. We need to do
  1382. * these only for non-reverse lookups, since they don't exist for those.
  1383. * We also need to do this before we consider automapping, since we might
  1384. * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
  1385. * we'd need to automap it. */
  1386. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1387. const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
  1388. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1389. rewrite_flags, &out->map_expires, &out->exit_source)) {
  1390. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1391. REMAP_STREAM_SOURCE_CACHE);
  1392. }
  1393. }
  1394. /* Now see if we need to create or return an existing Hostname->IP
  1395. * automapping. Automapping happens when we're asked to resolve a
  1396. * hostname, and AutomapHostsOnResolve is set, and the hostname has a
  1397. * suffix listed in AutomapHostsSuffixes. It's a handy feature
  1398. * that lets you have Tor assign e.g. IPv6 addresses for .onion
  1399. * names, and return them safely from DNSPort.
  1400. */
  1401. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1402. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  1403. options->AutomapHostsOnResolve) {
  1404. /* Check the suffix... */
  1405. out->automap = addressmap_address_should_automap(socks->address, options);
  1406. if (out->automap) {
  1407. /* If we get here, then we should apply an automapping for this. */
  1408. const char *new_addr;
  1409. /* We return an IPv4 address by default, or an IPv6 address if we
  1410. * are allowed to do so. */
  1411. int addr_type = RESOLVED_TYPE_IPV4;
  1412. if (conn->socks_request->socks_version != 4) {
  1413. if (!conn->entry_cfg.ipv4_traffic ||
  1414. (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
  1415. conn->entry_cfg.prefer_ipv6_virtaddr)
  1416. addr_type = RESOLVED_TYPE_IPV6;
  1417. }
  1418. /* Okay, register the target address as automapped, and find the new
  1419. * address we're supposed to give as a resolve answer. (Return a cached
  1420. * value if we've looked up this address before.
  1421. */
  1422. new_addr = addressmap_register_virtual_address(
  1423. addr_type, tor_strdup(socks->address));
  1424. if (! new_addr) {
  1425. log_warn(LD_APP, "Unable to automap address %s",
  1426. escaped_safe_str(socks->address));
  1427. out->end_reason = END_STREAM_REASON_INTERNAL;
  1428. out->should_close = 1;
  1429. return;
  1430. }
  1431. log_info(LD_APP, "Automapping %s to %s",
  1432. escaped_safe_str_client(socks->address),
  1433. safe_str_client(new_addr));
  1434. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1435. }
  1436. }
  1437. /* Now handle reverse lookups, if they're in the cache. This doesn't
  1438. * happen too often, since client-side DNS caching is off by default,
  1439. * and very deprecated. */
  1440. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1441. unsigned rewrite_flags = 0;
  1442. if (conn->entry_cfg.use_cached_ipv4_answers)
  1443. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1444. if (conn->entry_cfg.use_cached_ipv6_answers)
  1445. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1446. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1447. rewrite_flags, &out->map_expires)) {
  1448. char *result = tor_strdup(socks->address);
  1449. /* remember _what_ is supposed to have been resolved. */
  1450. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1451. out->orig_address);
  1452. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1453. strlen(result), (uint8_t*)result,
  1454. -1,
  1455. out->map_expires);
  1456. tor_free(result);
  1457. out->end_reason = END_STREAM_REASON_DONE |
  1458. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1459. out->should_close = 1;
  1460. return;
  1461. }
  1462. /* Hang on, did we find an answer saying that this is a reverse lookup for
  1463. * an internal address? If so, we should reject it if we're configured to
  1464. * do so. */
  1465. if (options->ClientDNSRejectInternalAddresses) {
  1466. /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
  1467. tor_addr_t addr;
  1468. int ok;
  1469. ok = tor_addr_parse_PTR_name(
  1470. &addr, socks->address, AF_UNSPEC, 1);
  1471. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1472. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1473. 0, NULL, -1, TIME_MAX);
  1474. out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
  1475. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1476. out->should_close = 1;
  1477. return;
  1478. }
  1479. }
  1480. }
  1481. /* If we didn't automap it before, then this is still the address that
  1482. * came straight from the user, mapped according to any
  1483. * MapAddress/MAPADDRESS commands. Now apply other mappings,
  1484. * including previously registered Automap entries (IP back to
  1485. * hostname), TrackHostExits entries, and client-side DNS cache
  1486. * entries (if they're turned on).
  1487. */
  1488. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1489. !out->automap) {
  1490. unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
  1491. addressmap_entry_source_t exit_source2;
  1492. if (conn->entry_cfg.use_cached_ipv4_answers)
  1493. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1494. if (conn->entry_cfg.use_cached_ipv6_answers)
  1495. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1496. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1497. rewrite_flags, &out->map_expires, &exit_source2)) {
  1498. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1499. REMAP_STREAM_SOURCE_CACHE);
  1500. }
  1501. if (out->exit_source == ADDRMAPSRC_NONE) {
  1502. /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
  1503. * the original source of a .exit. */
  1504. out->exit_source = exit_source2;
  1505. }
  1506. }
  1507. /* Check to see whether we're about to use an address in the virtual
  1508. * range without actually having gotten it from an Automap. */
  1509. if (!out->automap && address_is_in_virtual_range(socks->address)) {
  1510. /* This address was probably handed out by
  1511. * client_dns_get_unmapped_address, but the mapping was discarded for some
  1512. * reason. Or the user typed in a virtual address range manually. We
  1513. * *don't* want to send the address through Tor; that's likely to fail,
  1514. * and may leak information.
  1515. */
  1516. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1517. safe_str_client(socks->address));
  1518. out->end_reason = END_STREAM_REASON_INTERNAL;
  1519. out->should_close = 1;
  1520. return;
  1521. }
  1522. }
  1523. /** We just received a SOCKS request in <b>conn</b> to an onion address of type
  1524. * <b>addresstype</b>. Start connecting to the onion service. */
  1525. static int
  1526. connection_ap_handle_onion(entry_connection_t *conn,
  1527. socks_request_t *socks,
  1528. origin_circuit_t *circ,
  1529. hostname_type_t addresstype)
  1530. {
  1531. time_t now = approx_time();
  1532. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1533. /* If .onion address requests are disabled, refuse the request */
  1534. if (!conn->entry_cfg.onion_traffic) {
  1535. log_warn(LD_APP, "Onion address %s requested from a port with .onion "
  1536. "disabled", safe_str_client(socks->address));
  1537. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1538. return -1;
  1539. }
  1540. /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
  1541. * for hidden service addresses. */
  1542. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1543. /* if it's a resolve request, fail it right now, rather than
  1544. * building all the circuits and then realizing it won't work. */
  1545. log_warn(LD_APP,
  1546. "Resolve requests to hidden services not allowed. Failing.");
  1547. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1548. 0,NULL,-1,TIME_MAX);
  1549. connection_mark_unattached_ap(conn,
  1550. END_STREAM_REASON_SOCKSPROTOCOL |
  1551. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1552. return -1;
  1553. }
  1554. /* If we were passed a circuit, then we need to fail. .onion addresses
  1555. * only work when we launch our own circuits for now. */
  1556. if (circ) {
  1557. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1558. "supported for .onion addresses currently. Failing.");
  1559. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1560. return -1;
  1561. }
  1562. /* Interface: Regardless of HS version after the block below we should have
  1563. set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
  1564. const char *onion_address = NULL;
  1565. int rend_cache_lookup_result = -ENOENT;
  1566. int descriptor_is_usable = 0;
  1567. if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
  1568. rend_cache_entry_t *entry = NULL;
  1569. /* Look up if we have client authorization configured for this hidden
  1570. * service. If we do, associate it with the rend_data. */
  1571. rend_service_authorization_t *client_auth =
  1572. rend_client_lookup_service_authorization(socks->address);
  1573. const uint8_t *cookie = NULL;
  1574. rend_auth_type_t auth_type = REND_NO_AUTH;
  1575. if (client_auth) {
  1576. log_info(LD_REND, "Using previously configured client authorization "
  1577. "for hidden service request.");
  1578. auth_type = client_auth->auth_type;
  1579. cookie = client_auth->descriptor_cookie;
  1580. }
  1581. /* Fill in the rend_data field so we can start doing a connection to
  1582. * a hidden service. */
  1583. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
  1584. rend_data_client_create(socks->address, NULL, (char *) cookie,
  1585. auth_type);
  1586. if (rend_data == NULL) {
  1587. return -1;
  1588. }
  1589. onion_address = rend_data_get_address(rend_data);
  1590. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1591. safe_str_client(onion_address));
  1592. rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
  1593. &entry);
  1594. if (!rend_cache_lookup_result && entry) {
  1595. descriptor_is_usable = rend_client_any_intro_points_usable(entry);
  1596. }
  1597. } else { /* it's a v3 hidden service */
  1598. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1599. const hs_descriptor_t *cached_desc = NULL;
  1600. int retval;
  1601. /* Create HS conn identifier with HS pubkey */
  1602. hs_ident_edge_conn_t *hs_conn_ident =
  1603. tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
  1604. retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
  1605. NULL, NULL);
  1606. if (retval < 0) {
  1607. log_warn(LD_GENERAL, "failed to parse hs address");
  1608. tor_free(hs_conn_ident);
  1609. return -1;
  1610. }
  1611. ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
  1612. onion_address = socks->address;
  1613. /* Check the v3 desc cache */
  1614. cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
  1615. if (cached_desc) {
  1616. rend_cache_lookup_result = 0;
  1617. descriptor_is_usable =
  1618. hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
  1619. cached_desc);
  1620. log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
  1621. (descriptor_is_usable) ? "usable" : "unusable",
  1622. safe_str_client(onion_address),
  1623. (descriptor_is_usable) ? "Not fetching." : "Refecting.");
  1624. } else {
  1625. rend_cache_lookup_result = -ENOENT;
  1626. }
  1627. }
  1628. /* Lookup the given onion address. If invalid, stop right now.
  1629. * Otherwise, we might have it in the cache or not. */
  1630. unsigned int refetch_desc = 0;
  1631. if (rend_cache_lookup_result < 0) {
  1632. switch (-rend_cache_lookup_result) {
  1633. case EINVAL:
  1634. /* We should already have rejected this address! */
  1635. log_warn(LD_BUG,"Invalid service name '%s'",
  1636. safe_str_client(onion_address));
  1637. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1638. return -1;
  1639. case ENOENT:
  1640. /* We didn't have this; we should look it up. */
  1641. log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
  1642. safe_str_client(onion_address));
  1643. refetch_desc = 1;
  1644. break;
  1645. default:
  1646. log_warn(LD_BUG, "Unknown cache lookup error %d",
  1647. rend_cache_lookup_result);
  1648. return -1;
  1649. }
  1650. }
  1651. /* Help predict that we'll want to do hidden service circuits in the
  1652. * future. We're not sure if it will need a stable circuit yet, but
  1653. * we know we'll need *something*. */
  1654. rep_hist_note_used_internal(now, 0, 1);
  1655. /* Now we have a descriptor but is it usable or not? If not, refetch.
  1656. * Also, a fetch could have been requested if the onion address was not
  1657. * found in the cache previously. */
  1658. if (refetch_desc || !descriptor_is_usable) {
  1659. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  1660. connection_ap_mark_as_non_pending_circuit(conn);
  1661. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1662. if (addresstype == ONION_V2_HOSTNAME) {
  1663. tor_assert(edge_conn->rend_data);
  1664. rend_client_refetch_v2_renddesc(edge_conn->rend_data);
  1665. /* Whatever the result of the refetch, we don't go further. */
  1666. return 0;
  1667. } else {
  1668. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1669. tor_assert(edge_conn->hs_ident);
  1670. /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
  1671. * went and act accordingly. */
  1672. int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
  1673. switch (ret) {
  1674. case HS_CLIENT_FETCH_MISSING_INFO:
  1675. /* Keeping the connection in descriptor wait state is fine because
  1676. * once we get enough dirinfo or a new live consensus, the HS client
  1677. * subsystem is notified and every connection in that state will
  1678. * trigger a fetch for the service key. */
  1679. case HS_CLIENT_FETCH_LAUNCHED:
  1680. case HS_CLIENT_FETCH_PENDING:
  1681. case HS_CLIENT_FETCH_HAVE_DESC:
  1682. return 0;
  1683. case HS_CLIENT_FETCH_ERROR:
  1684. case HS_CLIENT_FETCH_NO_HSDIRS:
  1685. case HS_CLIENT_FETCH_NOT_ALLOWED:
  1686. /* Can't proceed further and better close the SOCKS request. */
  1687. return -1;
  1688. }
  1689. }
  1690. }
  1691. /* We have the descriptor! So launch a connection to the HS. */
  1692. log_info(LD_REND, "Descriptor is here. Great.");
  1693. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1694. /* We'll try to attach it at the next event loop, or whenever
  1695. * we call connection_ap_attach_pending() */
  1696. connection_ap_mark_as_pending_circuit(conn);
  1697. return 0;
  1698. }
  1699. /** Connection <b>conn</b> just finished its socks handshake, or the
  1700. * controller asked us to take care of it. If <b>circ</b> is defined,
  1701. * then that's where we'll want to attach it. Otherwise we have to
  1702. * figure it out ourselves.
  1703. *
  1704. * First, parse whether it's a .exit address, remap it, and so on. Then
  1705. * if it's for a general circuit, try to attach it to a circuit (or launch
  1706. * one as needed), else if it's for a rendezvous circuit, fetch a
  1707. * rendezvous descriptor first (or attach/launch a circuit if the
  1708. * rendezvous descriptor is already here and fresh enough).
  1709. *
  1710. * The stream will exit from the hop
  1711. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1712. * <b>cpath</b> is NULL.
  1713. */
  1714. int
  1715. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1716. origin_circuit_t *circ,
  1717. crypt_path_t *cpath)
  1718. {
  1719. socks_request_t *socks = conn->socks_request;
  1720. const or_options_t *options = get_options();
  1721. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1722. time_t now = time(NULL);
  1723. rewrite_result_t rr;
  1724. /* First we'll do the rewrite part. Let's see if we get a reasonable
  1725. * answer.
  1726. */
  1727. memset(&rr, 0, sizeof(rr));
  1728. connection_ap_handshake_rewrite(conn,&rr);
  1729. if (rr.should_close) {
  1730. /* connection_ap_handshake_rewrite told us to close the connection:
  1731. * either because it sent back an answer, or because it sent back an
  1732. * error */
  1733. connection_mark_unattached_ap(conn, rr.end_reason);
  1734. if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
  1735. return 0;
  1736. else
  1737. return -1;
  1738. }
  1739. const time_t map_expires = rr.map_expires;
  1740. const int automap = rr.automap;
  1741. const addressmap_entry_source_t exit_source = rr.exit_source;
  1742. /* Now, we parse the address to see if it's an .onion or .exit or
  1743. * other special address.
  1744. */
  1745. const hostname_type_t addresstype = parse_extended_hostname(socks->address);
  1746. /* Now see whether the hostname is bogus. This could happen because of an
  1747. * onion hostname whose format we don't recognize. */
  1748. if (addresstype == BAD_HOSTNAME) {
  1749. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1750. escaped(socks->address));
  1751. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1752. return -1;
  1753. }
  1754. /* If this is a .exit hostname, strip off the .name.exit part, and
  1755. * see whether we're willing to connect there, and and otherwise handle the
  1756. * .exit address.
  1757. *
  1758. * We'll set chosen_exit_name and/or close the connection as appropriate.
  1759. */
  1760. if (addresstype == EXIT_HOSTNAME) {
  1761. /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
  1762. * not ExcludeExitNodes. */
  1763. routerset_t *excludeset = options->StrictNodes ?
  1764. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  1765. const node_t *node = NULL;
  1766. /* If this .exit was added by an AUTOMAP, then it came straight from
  1767. * a user. That's not safe. */
  1768. if (exit_source == ADDRMAPSRC_AUTOMAP) {
  1769. /* Whoops; this one is stale. It must have gotten added earlier?
  1770. * (Probably this is not possible, since AllowDotExit no longer
  1771. * exists.) */
  1772. log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
  1773. safe_str_client(socks->address));
  1774. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1775. escaped(socks->address));
  1776. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1777. tor_assert_nonfatal_unreached();
  1778. return -1;
  1779. }
  1780. /* Double-check to make sure there are no .exits coming from
  1781. * impossible/weird sources. */
  1782. if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
  1783. /* It shouldn't be possible to get a .exit address from any of these
  1784. * sources. */
  1785. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  1786. ".exit part. Refusing.",
  1787. safe_str_client(socks->address));
  1788. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1789. escaped(socks->address));
  1790. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1791. return -1;
  1792. }
  1793. tor_assert(!automap);
  1794. /* Now, find the character before the .(name) part.
  1795. * (The ".exit" part got stripped off by "parse_extended_hostname").
  1796. *
  1797. * We're going to put the exit name into conn->chosen_exit_name, and
  1798. * look up a node correspondingly. */
  1799. char *s = strrchr(socks->address,'.');
  1800. if (s) {
  1801. /* The address was of the form "(stuff).(name).exit */
  1802. if (s[1] != '\0') {
  1803. /* Looks like a real .exit one. */
  1804. conn->chosen_exit_name = tor_strdup(s+1);
  1805. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1806. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1807. /* We 5 tries before it expires the addressmap */
  1808. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1809. }
  1810. *s = 0;
  1811. } else {
  1812. /* Oops, the address was (stuff)..exit. That's not okay. */
  1813. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1814. safe_str_client(socks->address));
  1815. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1816. escaped(socks->address));
  1817. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1818. return -1;
  1819. }
  1820. } else {
  1821. /* It looks like they just asked for "foo.exit". That's a special
  1822. * form that means (foo's address).foo.exit. */
  1823. conn->chosen_exit_name = tor_strdup(socks->address);
  1824. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1825. if (node) {
  1826. *socks->address = 0;
  1827. node_get_address_string(node, socks->address, sizeof(socks->address));
  1828. }
  1829. }
  1830. /* Now make sure that the chosen exit exists... */
  1831. if (!node) {
  1832. log_warn(LD_APP,
  1833. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1834. safe_str_client(socks->address));
  1835. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1836. return -1;
  1837. }
  1838. /* ...and make sure that it isn't excluded. */
  1839. if (routerset_contains_node(excludeset, node)) {
  1840. log_warn(LD_APP,
  1841. "Excluded relay in exit address '%s.exit'. Refusing.",
  1842. safe_str_client(socks->address));
  1843. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1844. return -1;
  1845. }
  1846. /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1847. Bar is not listed in it? I say yes, but our revised manpage branch
  1848. implies no. */
  1849. }
  1850. /* Now, we handle everything that isn't a .onion address. */
  1851. if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
  1852. /* Not a hidden-service request. It's either a hostname or an IP,
  1853. * possibly with a .exit that we stripped off. We're going to check
  1854. * if we're allowed to connect/resolve there, and then launch the
  1855. * appropriate request. */
  1856. /* Check for funny characters in the address. */
  1857. if (address_is_invalid_destination(socks->address, 1)) {
  1858. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1859. escaped(socks->address));
  1860. log_warn(LD_APP,
  1861. "Destination '%s' seems to be an invalid hostname. Failing.",
  1862. safe_str_client(socks->address));
  1863. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1864. return -1;
  1865. }
  1866. /* socks->address is a non-onion hostname or IP address.
  1867. * If we can't do any non-onion requests, refuse the connection.
  1868. * If we have a hostname but can't do DNS, refuse the connection.
  1869. * If we have an IP address, but we can't use that address family,
  1870. * refuse the connection.
  1871. *
  1872. * If we can do DNS requests, and we can use at least one address family,
  1873. * then we have to resolve the address first. Then we'll know if it
  1874. * resolves to a usable address family. */
  1875. /* First, check if all non-onion traffic is disabled */
  1876. if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
  1877. && !conn->entry_cfg.ipv6_traffic) {
  1878. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
  1879. "or IP address %s because Port has OnionTrafficOnly set (or "
  1880. "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
  1881. safe_str_client(socks->address));
  1882. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1883. return -1;
  1884. }
  1885. /* Then check if we have a hostname or IP address, and whether DNS or
  1886. * the IP address family are permitted. Reject if not. */
  1887. tor_addr_t dummy_addr;
  1888. int socks_family = tor_addr_parse(&dummy_addr, socks->address);
  1889. /* family will be -1 for a non-onion hostname that's not an IP */
  1890. if (socks_family == -1) {
  1891. if (!conn->entry_cfg.dns_request) {
  1892. log_warn(LD_APP, "Refusing to connect to hostname %s "
  1893. "because Port has NoDNSRequest set.",
  1894. safe_str_client(socks->address));
  1895. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1896. return -1;
  1897. }
  1898. } else if (socks_family == AF_INET) {
  1899. if (!conn->entry_cfg.ipv4_traffic) {
  1900. log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
  1901. "Port has NoIPv4Traffic set.",
  1902. safe_str_client(socks->address));
  1903. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1904. return -1;
  1905. }
  1906. } else if (socks_family == AF_INET6) {
  1907. if (!conn->entry_cfg.ipv6_traffic) {
  1908. log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
  1909. "Port has NoIPv6Traffic set.",
  1910. safe_str_client(socks->address));
  1911. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1912. return -1;
  1913. }
  1914. } else {
  1915. tor_assert_nonfatal_unreached_once();
  1916. }
  1917. /* See if this is a hostname lookup that we can answer immediately.
  1918. * (For example, an attempt to look up the IP address for an IP address.)
  1919. */
  1920. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1921. tor_addr_t answer;
  1922. /* Reply to resolves immediately if we can. */
  1923. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  1924. /* remember _what_ is supposed to have been resolved. */
  1925. strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
  1926. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  1927. map_expires);
  1928. connection_mark_unattached_ap(conn,
  1929. END_STREAM_REASON_DONE |
  1930. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1931. return 0;
  1932. }
  1933. tor_assert(!automap);
  1934. rep_hist_note_used_resolve(now); /* help predict this next time */
  1935. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1936. /* Now see if this is a connect request that we can reject immediately */
  1937. tor_assert(!automap);
  1938. /* Don't allow connections to port 0. */
  1939. if (socks->port == 0) {
  1940. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1941. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1942. return -1;
  1943. }
  1944. /* You can't make connections to internal addresses, by default.
  1945. * Exceptions are begindir requests (where the address is meaningless),
  1946. * or cases where you've hand-configured a particular exit, thereby
  1947. * making the local address meaningful. */
  1948. if (options->ClientRejectInternalAddresses &&
  1949. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1950. /* If we reach this point then we don't want to allow internal
  1951. * addresses. Check if we got one. */
  1952. tor_addr_t addr;
  1953. if (tor_addr_hostname_is_local(socks->address) ||
  1954. (tor_addr_parse(&addr, socks->address) >= 0 &&
  1955. tor_addr_is_internal(&addr, 0))) {
  1956. /* If this is an explicit private address with no chosen exit node,
  1957. * then we really don't want to try to connect to it. That's
  1958. * probably an error. */
  1959. if (conn->is_transparent_ap) {
  1960. #define WARN_INTRVL_LOOP 300
  1961. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  1962. char *m;
  1963. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  1964. log_warn(LD_NET,
  1965. "Rejecting request for anonymous connection to private "
  1966. "address %s on a TransPort or NATDPort. Possible loop "
  1967. "in your NAT rules?%s", safe_str_client(socks->address),
  1968. m);
  1969. tor_free(m);
  1970. }
  1971. } else {
  1972. #define WARN_INTRVL_PRIV 300
  1973. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  1974. char *m;
  1975. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  1976. log_warn(LD_NET,
  1977. "Rejecting SOCKS request for anonymous connection to "
  1978. "private address %s.%s",
  1979. safe_str_client(socks->address),m);
  1980. tor_free(m);
  1981. }
  1982. }
  1983. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  1984. return -1;
  1985. }
  1986. } /* end "if we should check for internal addresses" */
  1987. /* Okay. We're still doing a CONNECT, and it wasn't a private
  1988. * address. Here we do special handling for literal IP addresses,
  1989. * to see if we should reject this preemptively, and to set up
  1990. * fields in conn->entry_cfg to tell the exit what AF we want. */
  1991. {
  1992. tor_addr_t addr;
  1993. /* XXX Duplicate call to tor_addr_parse. */
  1994. if (tor_addr_parse(&addr, socks->address) >= 0) {
  1995. /* If we reach this point, it's an IPv4 or an IPv6 address. */
  1996. sa_family_t family = tor_addr_family(&addr);
  1997. if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
  1998. (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
  1999. /* You can't do an IPv4 address on a v6-only socks listener,
  2000. * or vice versa. */
  2001. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  2002. "family that this listener does not support.");
  2003. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2004. return -1;
  2005. } else if (family == AF_INET6 && socks->socks_version == 4) {
  2006. /* You can't make a socks4 request to an IPv6 address. Socks4
  2007. * doesn't support that. */
  2008. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  2009. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2010. return -1;
  2011. } else if (socks->socks_version == 4 &&
  2012. !conn->entry_cfg.ipv4_traffic) {
  2013. /* You can't do any kind of Socks4 request when IPv4 is forbidden.
  2014. *
  2015. * XXX raise this check outside the enclosing block? */
  2016. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  2017. "no IPv4 traffic supported.");
  2018. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2019. return -1;
  2020. } else if (family == AF_INET6) {
  2021. /* Tell the exit: we won't accept any ipv4 connection to an IPv6
  2022. * address. */
  2023. conn->entry_cfg.ipv4_traffic = 0;
  2024. } else if (family == AF_INET) {
  2025. /* Tell the exit: we won't accept any ipv6 connection to an IPv4
  2026. * address. */
  2027. conn->entry_cfg.ipv6_traffic = 0;
  2028. }
  2029. }
  2030. }
  2031. /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
  2032. if (socks->socks_version == 4)
  2033. conn->entry_cfg.ipv6_traffic = 0;
  2034. /* Still handling CONNECT. Now, check for exit enclaves. (Which we
  2035. * don't do on BEGIN_DIR, or when there is a chosen exit.)
  2036. *
  2037. * TODO: Should we remove this? Exit enclaves are nutty and don't
  2038. * work very well
  2039. */
  2040. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  2041. /* see if we can find a suitable enclave exit */
  2042. const node_t *r =
  2043. router_find_exact_exit_enclave(socks->address, socks->port);
  2044. if (r) {
  2045. log_info(LD_APP,
  2046. "Redirecting address %s to exit at enclave router %s",
  2047. safe_str_client(socks->address), node_describe(r));
  2048. /* use the hex digest, not nickname, in case there are two
  2049. routers with this nickname */
  2050. conn->chosen_exit_name =
  2051. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  2052. conn->chosen_exit_optional = 1;
  2053. }
  2054. }
  2055. /* Still handling CONNECT: warn or reject if it's using a dangerous
  2056. * port. */
  2057. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  2058. if (consider_plaintext_ports(conn, socks->port) < 0)
  2059. return -1;
  2060. /* Remember the port so that we will predict that more requests
  2061. there will happen in the future. */
  2062. if (!conn->use_begindir) {
  2063. /* help predict this next time */
  2064. rep_hist_note_used_port(now, socks->port);
  2065. }
  2066. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  2067. rep_hist_note_used_resolve(now); /* help predict this next time */
  2068. /* no extra processing needed */
  2069. } else {
  2070. /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
  2071. tor_fragile_assert();
  2072. }
  2073. /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
  2074. * address, and decided not to reject it for any number of reasons. Now
  2075. * mark the connection as waiting for a circuit, and try to attach it!
  2076. */
  2077. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2078. /* If we were given a circuit to attach to, try to attach. Otherwise,
  2079. * try to find a good one and attach to that. */
  2080. int rv;
  2081. if (circ) {
  2082. rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
  2083. } else {
  2084. /* We'll try to attach it at the next event loop, or whenever
  2085. * we call connection_ap_attach_pending() */
  2086. connection_ap_mark_as_pending_circuit(conn);
  2087. rv = 0;
  2088. }
  2089. /* If the above function returned 0 then we're waiting for a circuit.
  2090. * if it returned 1, we're attached. Both are okay. But if it returned
  2091. * -1, there was an error, so make sure the connection is marked, and
  2092. * return -1. */
  2093. if (rv < 0) {
  2094. if (!base_conn->marked_for_close)
  2095. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2096. return -1;
  2097. }
  2098. return 0;
  2099. } else {
  2100. /* If we get here, it's a request for a .onion address! */
  2101. tor_assert(addresstype == ONION_V2_HOSTNAME ||
  2102. addresstype == ONION_V3_HOSTNAME);
  2103. tor_assert(!automap);
  2104. return connection_ap_handle_onion(conn, socks, circ, addresstype);
  2105. }
  2106. return 0; /* unreached but keeps the compiler happy */
  2107. }
  2108. #ifdef TRANS_PF
  2109. static int pf_socket = -1;
  2110. int
  2111. get_pf_socket(void)
  2112. {
  2113. int pf;
  2114. /* This should be opened before dropping privileges. */
  2115. if (pf_socket >= 0)
  2116. return pf_socket;
  2117. #if defined(OpenBSD)
  2118. /* only works on OpenBSD */
  2119. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  2120. #else
  2121. /* works on NetBSD and FreeBSD */
  2122. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  2123. #endif /* defined(OpenBSD) */
  2124. if (pf < 0) {
  2125. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  2126. return -1;
  2127. }
  2128. pf_socket = pf;
  2129. return pf_socket;
  2130. }
  2131. #endif /* defined(TRANS_PF) */
  2132. #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
  2133. defined(TRANS_TPROXY)
  2134. /** Try fill in the address of <b>req</b> from the socket configured
  2135. * with <b>conn</b>. */
  2136. static int
  2137. destination_from_socket(entry_connection_t *conn, socks_request_t *req)
  2138. {
  2139. struct sockaddr_storage orig_dst;
  2140. socklen_t orig_dst_len = sizeof(orig_dst);
  2141. tor_addr_t addr;
  2142. #ifdef TRANS_TPROXY
  2143. if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
  2144. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2145. &orig_dst_len) < 0) {
  2146. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2147. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2148. return -1;
  2149. }
  2150. goto done;
  2151. }
  2152. #endif /* defined(TRANS_TPROXY) */
  2153. #ifdef TRANS_NETFILTER
  2154. int rv = -1;
  2155. switch (ENTRY_TO_CONN(conn)->socket_family) {
  2156. #ifdef TRANS_NETFILTER_IPV4
  2157. case AF_INET:
  2158. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  2159. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2160. break;
  2161. #endif /* defined(TRANS_NETFILTER_IPV4) */
  2162. #ifdef TRANS_NETFILTER_IPV6
  2163. case AF_INET6:
  2164. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
  2165. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2166. break;
  2167. #endif /* defined(TRANS_NETFILTER_IPV6) */
  2168. default:
  2169. log_warn(LD_BUG,
  2170. "Received transparent data from an unsuported socket family %d",
  2171. ENTRY_TO_CONN(conn)->socket_family);
  2172. return -1;
  2173. }
  2174. if (rv < 0) {
  2175. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2176. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  2177. return -1;
  2178. }
  2179. goto done;
  2180. #elif defined(TRANS_PF)
  2181. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2182. &orig_dst_len) < 0) {
  2183. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2184. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2185. return -1;
  2186. }
  2187. goto done;
  2188. #else
  2189. (void)conn;
  2190. (void)req;
  2191. log_warn(LD_BUG, "Unable to determine destination from socket.");
  2192. return -1;
  2193. #endif /* defined(TRANS_NETFILTER) || ... */
  2194. done:
  2195. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  2196. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2197. return 0;
  2198. }
  2199. #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
  2200. #ifdef TRANS_PF
  2201. static int
  2202. destination_from_pf(entry_connection_t *conn, socks_request_t *req)
  2203. {
  2204. struct sockaddr_storage proxy_addr;
  2205. socklen_t proxy_addr_len = sizeof(proxy_addr);
  2206. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  2207. struct pfioc_natlook pnl;
  2208. tor_addr_t addr;
  2209. int pf = -1;
  2210. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  2211. &proxy_addr_len) < 0) {
  2212. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2213. log_warn(LD_NET, "getsockname() to determine transocks destination "
  2214. "failed: %s", tor_socket_strerror(e));
  2215. return -1;
  2216. }
  2217. #ifdef __FreeBSD__
  2218. if (get_options()->TransProxyType_parsed == TPT_IPFW) {
  2219. /* ipfw(8) is used and in this case getsockname returned the original
  2220. destination */
  2221. if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
  2222. tor_fragile_assert();
  2223. return -1;
  2224. }
  2225. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  2226. return 0;
  2227. }
  2228. #endif /* defined(__FreeBSD__) */
  2229. memset(&pnl, 0, sizeof(pnl));
  2230. pnl.proto = IPPROTO_TCP;
  2231. pnl.direction = PF_OUT;
  2232. if (proxy_sa->sa_family == AF_INET) {
  2233. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  2234. pnl.af = AF_INET;
  2235. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  2236. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2237. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  2238. pnl.dport = sin->sin_port;
  2239. } else if (proxy_sa->sa_family == AF_INET6) {
  2240. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  2241. pnl.af = AF_INET6;
  2242. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
  2243. sizeof(struct in6_addr));
  2244. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2245. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  2246. pnl.dport = sin6->sin6_port;
  2247. } else {
  2248. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  2249. (int)proxy_sa->sa_family);
  2250. return -1;
  2251. }
  2252. pf = get_pf_socket();
  2253. if (pf<0)
  2254. return -1;
  2255. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  2256. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  2257. return -1;
  2258. }
  2259. if (pnl.af == AF_INET) {
  2260. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  2261. } else if (pnl.af == AF_INET6) {
  2262. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  2263. } else {
  2264. tor_fragile_assert();
  2265. return -1;
  2266. }
  2267. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2268. req->port = ntohs(pnl.rdport);
  2269. return 0;
  2270. }
  2271. #endif /* defined(TRANS_PF) */
  2272. /** Fetch the original destination address and port from a
  2273. * system-specific interface and put them into a
  2274. * socks_request_t as if they came from a socks request.
  2275. *
  2276. * Return -1 if an error prevents fetching the destination,
  2277. * else return 0.
  2278. */
  2279. static int
  2280. connection_ap_get_original_destination(entry_connection_t *conn,
  2281. socks_request_t *req)
  2282. {
  2283. #ifdef TRANS_NETFILTER
  2284. return destination_from_socket(conn, req);
  2285. #elif defined(TRANS_PF)
  2286. const or_options_t *options = get_options();
  2287. if (options->TransProxyType_parsed == TPT_PF_DIVERT)
  2288. return destination_from_socket(conn, req);
  2289. if (options->TransProxyType_parsed == TPT_DEFAULT ||
  2290. options->TransProxyType_parsed == TPT_IPFW)
  2291. return destination_from_pf(conn, req);
  2292. (void)conn;
  2293. (void)req;
  2294. log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
  2295. options->TransProxyType);
  2296. return -1;
  2297. #else
  2298. (void)conn;
  2299. (void)req;
  2300. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  2301. "transparent proxy method was configured.");
  2302. return -1;
  2303. #endif /* defined(TRANS_NETFILTER) || ... */
  2304. }
  2305. /** connection_edge_process_inbuf() found a conn in state
  2306. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  2307. * the socks handshake.
  2308. *
  2309. * If the handshake is complete, send it to
  2310. * connection_ap_handshake_rewrite_and_attach().
  2311. *
  2312. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  2313. * else return 0.
  2314. */
  2315. static int
  2316. connection_ap_handshake_process_socks(entry_connection_t *conn)
  2317. {
  2318. socks_request_t *socks;
  2319. int sockshere;
  2320. const or_options_t *options = get_options();
  2321. int had_reply = 0;
  2322. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2323. tor_assert(conn);
  2324. tor_assert(base_conn->type == CONN_TYPE_AP);
  2325. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  2326. tor_assert(conn->socks_request);
  2327. socks = conn->socks_request;
  2328. log_debug(LD_APP,"entered.");
  2329. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  2330. options->TestSocks, options->SafeSocks);
  2331. if (socks->replylen) {
  2332. had_reply = 1;
  2333. connection_buf_add((const char*)socks->reply, socks->replylen,
  2334. base_conn);
  2335. socks->replylen = 0;
  2336. if (sockshere == -1) {
  2337. /* An invalid request just got a reply, no additional
  2338. * one is necessary. */
  2339. socks->has_finished = 1;
  2340. }
  2341. }
  2342. if (sockshere == 0) {
  2343. log_debug(LD_APP,"socks handshake not all here yet.");
  2344. return 0;
  2345. } else if (sockshere == -1) {
  2346. if (!had_reply) {
  2347. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  2348. connection_ap_handshake_socks_reply(conn, NULL, 0,
  2349. END_STREAM_REASON_SOCKSPROTOCOL);
  2350. }
  2351. connection_mark_unattached_ap(conn,
  2352. END_STREAM_REASON_SOCKSPROTOCOL |
  2353. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2354. return -1;
  2355. } /* else socks handshake is done, continue processing */
  2356. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  2357. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2358. else
  2359. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  2360. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2361. }
  2362. /** connection_init_accepted_conn() found a new trans AP conn.
  2363. * Get the original destination and send it to
  2364. * connection_ap_handshake_rewrite_and_attach().
  2365. *
  2366. * Return -1 if an unexpected error with conn (and it should be marked
  2367. * for close), else return 0.
  2368. */
  2369. int
  2370. connection_ap_process_transparent(entry_connection_t *conn)
  2371. {
  2372. socks_request_t *socks;
  2373. tor_assert(conn);
  2374. tor_assert(conn->socks_request);
  2375. socks = conn->socks_request;
  2376. /* pretend that a socks handshake completed so we don't try to
  2377. * send a socks reply down a transparent conn */
  2378. socks->command = SOCKS_COMMAND_CONNECT;
  2379. socks->has_finished = 1;
  2380. log_debug(LD_APP,"entered.");
  2381. if (connection_ap_get_original_destination(conn, socks) < 0) {
  2382. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  2383. connection_mark_unattached_ap(conn,
  2384. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  2385. return -1;
  2386. }
  2387. /* we have the original destination */
  2388. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2389. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2390. }
  2391. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  2392. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  2393. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  2394. * form of the original destination.
  2395. *
  2396. * If the original destination is complete, send it to
  2397. * connection_ap_handshake_rewrite_and_attach().
  2398. *
  2399. * Return -1 if an unexpected error with conn (and it should be marked
  2400. * for close), else return 0.
  2401. */
  2402. static int
  2403. connection_ap_process_natd(entry_connection_t *conn)
  2404. {
  2405. char tmp_buf[36], *tbuf, *daddr;
  2406. size_t tlen = 30;
  2407. int err, port_ok;
  2408. socks_request_t *socks;
  2409. tor_assert(conn);
  2410. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  2411. tor_assert(conn->socks_request);
  2412. socks = conn->socks_request;
  2413. log_debug(LD_APP,"entered.");
  2414. /* look for LF-terminated "[DEST ip_addr port]"
  2415. * where ip_addr is a dotted-quad and port is in string form */
  2416. err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  2417. if (err == 0)
  2418. return 0;
  2419. if (err < 0) {
  2420. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  2421. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2422. return -1;
  2423. }
  2424. if (strcmpstart(tmp_buf, "[DEST ")) {
  2425. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2426. "said: %s",
  2427. escaped(tmp_buf));
  2428. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2429. return -1;
  2430. }
  2431. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  2432. if (!(tbuf = strchr(tbuf, ' '))) {
  2433. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2434. "said: %s",
  2435. escaped(tmp_buf));
  2436. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2437. return -1;
  2438. }
  2439. *tbuf++ = '\0';
  2440. /* pretend that a socks handshake completed so we don't try to
  2441. * send a socks reply down a natd conn */
  2442. strlcpy(socks->address, daddr, sizeof(socks->address));
  2443. socks->port = (uint16_t)
  2444. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  2445. if (!port_ok) {
  2446. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  2447. "of range.", escaped(tbuf));
  2448. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2449. return -1;
  2450. }
  2451. socks->command = SOCKS_COMMAND_CONNECT;
  2452. socks->has_finished = 1;
  2453. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2454. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2455. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2456. }
  2457. /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
  2458. * but we have not yet received a full HTTP CONNECT request. Try to parse an
  2459. * HTTP CONNECT request from the connection's inbuf. On success, set up the
  2460. * connection's socks_request field and try to attach the connection. On
  2461. * failure, send an HTTP reply, and mark the connection.
  2462. */
  2463. STATIC int
  2464. connection_ap_process_http_connect(entry_connection_t *conn)
  2465. {
  2466. if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
  2467. return -1;
  2468. char *headers = NULL, *body = NULL;
  2469. char *command = NULL, *addrport = NULL;
  2470. char *addr = NULL;
  2471. size_t bodylen = 0;
  2472. const char *errmsg = NULL;
  2473. int rv = 0;
  2474. const int http_status =
  2475. fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
  2476. &body, &bodylen, 1024, 0);
  2477. if (http_status < 0) {
  2478. /* Bad http status */
  2479. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2480. goto err;
  2481. } else if (http_status == 0) {
  2482. /* no HTTP request yet. */
  2483. goto done;
  2484. }
  2485. const int cmd_status = parse_http_command(headers, &command, &addrport);
  2486. if (cmd_status < 0) {
  2487. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2488. goto err;
  2489. }
  2490. tor_assert(command);
  2491. tor_assert(addrport);
  2492. if (strcasecmp(command, "connect")) {
  2493. errmsg = "HTTP/1.0 405 Method Not Allowed\r\n\r\n";
  2494. goto err;
  2495. }
  2496. tor_assert(conn->socks_request);
  2497. socks_request_t *socks = conn->socks_request;
  2498. uint16_t port;
  2499. if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
  2500. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2501. goto err;
  2502. }
  2503. if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
  2504. errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
  2505. goto err;
  2506. }
  2507. /* Abuse the 'username' and 'password' fields here. They are already an
  2508. * abuse. */
  2509. {
  2510. char *authorization = http_get_header(headers, "Proxy-Authorization: ");
  2511. if (authorization) {
  2512. socks->username = authorization; // steal reference
  2513. socks->usernamelen = strlen(authorization);
  2514. }
  2515. char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
  2516. if (isolation) {
  2517. socks->password = isolation; // steal reference
  2518. socks->passwordlen = strlen(isolation);
  2519. }
  2520. }
  2521. socks->command = SOCKS_COMMAND_CONNECT;
  2522. socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
  2523. strlcpy(socks->address, addr, sizeof(socks->address));
  2524. socks->port = port;
  2525. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2526. rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2527. // XXXX send a "100 Continue" message?
  2528. goto done;
  2529. err:
  2530. if (BUG(errmsg == NULL))
  2531. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2532. log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
  2533. connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
  2534. /* Mark it as "has_finished" so that we don't try to send an extra socks
  2535. * reply. */
  2536. conn->socks_request->has_finished = 1;
  2537. connection_mark_unattached_ap(conn,
  2538. END_STREAM_REASON_HTTPPROTOCOL|
  2539. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2540. done:
  2541. tor_free(headers);
  2542. tor_free(body);
  2543. tor_free(command);
  2544. tor_free(addrport);
  2545. tor_free(addr);
  2546. return rv;
  2547. }
  2548. /** Iterate over the two bytes of stream_id until we get one that is not
  2549. * already in use; return it. Return 0 if can't get a unique stream_id.
  2550. */
  2551. streamid_t
  2552. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  2553. {
  2554. edge_connection_t *tmpconn;
  2555. streamid_t test_stream_id;
  2556. uint32_t attempts=0;
  2557. again:
  2558. test_stream_id = circ->next_stream_id++;
  2559. if (++attempts > 1<<16) {
  2560. /* Make sure we don't loop forever if all stream_id's are used. */
  2561. log_warn(LD_APP,"No unused stream IDs. Failing.");
  2562. return 0;
  2563. }
  2564. if (test_stream_id == 0)
  2565. goto again;
  2566. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  2567. if (tmpconn->stream_id == test_stream_id)
  2568. goto again;
  2569. if (connection_half_edge_find_stream_id(circ->half_streams,
  2570. test_stream_id))
  2571. goto again;
  2572. return test_stream_id;
  2573. }
  2574. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  2575. * an exit that supports optimistic data. */
  2576. static int
  2577. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  2578. {
  2579. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2580. /* We can only send optimistic data if we're connected to an open
  2581. general circuit. */
  2582. if (edge_conn->on_circuit == NULL ||
  2583. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  2584. (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  2585. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
  2586. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
  2587. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
  2588. return 0;
  2589. return conn->may_use_optimistic_data;
  2590. }
  2591. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  2592. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  2593. static uint32_t
  2594. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  2595. {
  2596. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2597. const node_t *exitnode = NULL;
  2598. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  2599. uint32_t flags = 0;
  2600. /* No flags for begindir */
  2601. if (ap_conn->use_begindir)
  2602. return 0;
  2603. /* No flags for hidden services. */
  2604. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2605. return 0;
  2606. /* If only IPv4 is supported, no flags */
  2607. if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
  2608. return 0;
  2609. if (! cpath_layer ||
  2610. ! cpath_layer->extend_info)
  2611. return 0;
  2612. if (!ap_conn->entry_cfg.ipv4_traffic)
  2613. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  2614. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  2615. if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
  2616. tor_addr_t a;
  2617. tor_addr_make_null(&a, AF_INET6);
  2618. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  2619. exitnode)
  2620. != ADDR_POLICY_REJECTED) {
  2621. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  2622. * no point. */
  2623. flags |= BEGIN_FLAG_IPV6_OK;
  2624. }
  2625. }
  2626. if (flags == BEGIN_FLAG_IPV6_OK) {
  2627. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  2628. * prefer IPv6. Otherwise there's no point in declaring a preference */
  2629. if (ap_conn->entry_cfg.prefer_ipv6)
  2630. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  2631. }
  2632. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  2633. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  2634. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  2635. "not going to work. Did you perhaps ask for an IPv6 address "
  2636. "on an IPv4Only port, or vice versa?");
  2637. }
  2638. return flags;
  2639. }
  2640. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  2641. * socks_request field, and send it down circ.
  2642. *
  2643. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2644. */
  2645. MOCK_IMPL(int,
  2646. connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
  2647. {
  2648. char payload[CELL_PAYLOAD_SIZE];
  2649. int payload_len;
  2650. int begin_type;
  2651. const or_options_t *options = get_options();
  2652. origin_circuit_t *circ;
  2653. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2654. connection_t *base_conn = TO_CONN(edge_conn);
  2655. tor_assert(edge_conn->on_circuit);
  2656. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2657. tor_assert(base_conn->type == CONN_TYPE_AP);
  2658. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2659. tor_assert(ap_conn->socks_request);
  2660. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  2661. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2662. if (edge_conn->stream_id==0) {
  2663. /* XXXX+ Instead of closing this stream, we should make it get
  2664. * retried on another circuit. */
  2665. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2666. /* Mark this circuit "unusable for new streams". */
  2667. mark_circuit_unusable_for_new_conns(circ);
  2668. return -1;
  2669. }
  2670. /* Set up begin cell flags. */
  2671. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  2672. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  2673. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  2674. ap_conn->socks_request->address : "",
  2675. ap_conn->socks_request->port);
  2676. payload_len = (int)strlen(payload)+1;
  2677. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  2678. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  2679. payload_len += 4;
  2680. }
  2681. log_info(LD_APP,
  2682. "Sending relay cell %d on circ %u to begin stream %d.",
  2683. (int)ap_conn->use_begindir,
  2684. (unsigned)circ->base_.n_circ_id,
  2685. edge_conn->stream_id);
  2686. begin_type = ap_conn->use_begindir ?
  2687. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  2688. /* Check that circuits are anonymised, based on their type. */
  2689. if (begin_type == RELAY_COMMAND_BEGIN) {
  2690. /* This connection is a standard OR connection.
  2691. * Make sure its path length is anonymous, or that we're in a
  2692. * non-anonymous mode. */
  2693. assert_circ_anonymity_ok(circ, options);
  2694. } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
  2695. /* This connection is a begindir directory connection.
  2696. * Look at the linked directory connection to access the directory purpose.
  2697. * If a BEGINDIR connection is ever not linked, that's a bug. */
  2698. if (BUG(!base_conn->linked)) {
  2699. return -1;
  2700. }
  2701. connection_t *linked_dir_conn_base = base_conn->linked_conn;
  2702. /* If the linked connection has been unlinked by other code, we can't send
  2703. * a begin cell on it. */
  2704. if (!linked_dir_conn_base) {
  2705. return -1;
  2706. }
  2707. /* Sensitive directory connections must have an anonymous path length.
  2708. * Otherwise, directory connections are typically one-hop.
  2709. * This matches the earlier check for directory connection path anonymity
  2710. * in directory_initiate_request(). */
  2711. if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
  2712. TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
  2713. TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
  2714. assert_circ_anonymity_ok(circ, options);
  2715. }
  2716. } else {
  2717. /* This code was written for the two connection types BEGIN and BEGIN_DIR
  2718. */
  2719. tor_assert_unreached();
  2720. }
  2721. if (connection_edge_send_command(edge_conn, begin_type,
  2722. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  2723. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  2724. return -1; /* circuit is closed, don't continue */
  2725. edge_conn->package_window = STREAMWINDOW_START;
  2726. edge_conn->deliver_window = STREAMWINDOW_START;
  2727. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  2728. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  2729. ", n_circ_id %u",
  2730. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2731. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  2732. /* If there's queued-up data, send it now */
  2733. if ((connection_get_inbuf_len(base_conn) ||
  2734. ap_conn->sending_optimistic_data) &&
  2735. connection_ap_supports_optimistic_data(ap_conn)) {
  2736. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  2737. (long)connection_get_inbuf_len(base_conn),
  2738. ap_conn->sending_optimistic_data ?
  2739. (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
  2740. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  2741. connection_mark_for_close(base_conn);
  2742. }
  2743. }
  2744. return 0;
  2745. }
  2746. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  2747. * socks_request field, and send it down circ.
  2748. *
  2749. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2750. */
  2751. int
  2752. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  2753. {
  2754. int payload_len, command;
  2755. const char *string_addr;
  2756. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  2757. origin_circuit_t *circ;
  2758. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2759. connection_t *base_conn = TO_CONN(edge_conn);
  2760. tor_assert(edge_conn->on_circuit);
  2761. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2762. tor_assert(base_conn->type == CONN_TYPE_AP);
  2763. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2764. tor_assert(ap_conn->socks_request);
  2765. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  2766. command = ap_conn->socks_request->command;
  2767. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  2768. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2769. if (edge_conn->stream_id==0) {
  2770. /* XXXX+ Instead of closing this stream, we should make it get
  2771. * retried on another circuit. */
  2772. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2773. /* Mark this circuit "unusable for new streams". */
  2774. mark_circuit_unusable_for_new_conns(circ);
  2775. return -1;
  2776. }
  2777. if (command == SOCKS_COMMAND_RESOLVE) {
  2778. string_addr = ap_conn->socks_request->address;
  2779. payload_len = (int)strlen(string_addr)+1;
  2780. } else {
  2781. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2782. const char *a = ap_conn->socks_request->address;
  2783. tor_addr_t addr;
  2784. int r;
  2785. /* We're doing a reverse lookup. The input could be an IP address, or
  2786. * could be an .in-addr.arpa or .ip6.arpa address */
  2787. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  2788. if (r <= 0) {
  2789. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2790. safe_str_client(a));
  2791. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2792. return -1;
  2793. }
  2794. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2795. if (r < 0) {
  2796. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2797. safe_str_client(a));
  2798. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2799. return -1;
  2800. }
  2801. string_addr = inaddr_buf;
  2802. payload_len = (int)strlen(inaddr_buf)+1;
  2803. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2804. }
  2805. log_debug(LD_APP,
  2806. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2807. if (connection_edge_send_command(edge_conn,
  2808. RELAY_COMMAND_RESOLVE,
  2809. string_addr, payload_len) < 0)
  2810. return -1; /* circuit is closed, don't continue */
  2811. if (!base_conn->address) {
  2812. /* This might be unnecessary. XXXX */
  2813. base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
  2814. }
  2815. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2816. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  2817. ", n_circ_id %u",
  2818. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2819. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2820. return 0;
  2821. }
  2822. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  2823. * new linked connection pair, and attach one side to the conn, connection_add
  2824. * it, initialize it to circuit_wait, and call
  2825. * connection_ap_handshake_attach_circuit(conn) on it.
  2826. *
  2827. * Return the newly created end of the linked connection pair, or -1 if error.
  2828. */
  2829. entry_connection_t *
  2830. connection_ap_make_link(connection_t *partner,
  2831. char *address, uint16_t port,
  2832. const char *digest,
  2833. int session_group, int isolation_flags,
  2834. int use_begindir, int want_onehop)
  2835. {
  2836. entry_connection_t *conn;
  2837. connection_t *base_conn;
  2838. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2839. want_onehop ? "direct" : "anonymized",
  2840. safe_str_client(address), port);
  2841. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  2842. base_conn = ENTRY_TO_CONN(conn);
  2843. base_conn->linked = 1; /* so that we can add it safely below. */
  2844. /* populate conn->socks_request */
  2845. /* leave version at zero, so the socks_reply is empty */
  2846. conn->socks_request->socks_version = 0;
  2847. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2848. strlcpy(conn->socks_request->address, address,
  2849. sizeof(conn->socks_request->address));
  2850. conn->socks_request->port = port;
  2851. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2852. conn->want_onehop = want_onehop;
  2853. conn->use_begindir = use_begindir;
  2854. if (use_begindir) {
  2855. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2856. conn->chosen_exit_name[0] = '$';
  2857. tor_assert(digest);
  2858. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2859. digest, DIGEST_LEN);
  2860. }
  2861. /* Populate isolation fields. */
  2862. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2863. conn->original_dest_address = tor_strdup(address);
  2864. conn->entry_cfg.session_group = session_group;
  2865. conn->entry_cfg.isolation_flags = isolation_flags;
  2866. base_conn->address = tor_strdup("(Tor_internal)");
  2867. tor_addr_make_unspec(&base_conn->addr);
  2868. base_conn->port = 0;
  2869. connection_link_connections(partner, base_conn);
  2870. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2871. connection_free(base_conn);
  2872. return NULL;
  2873. }
  2874. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2875. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2876. /* attaching to a dirty circuit is fine */
  2877. connection_ap_mark_as_pending_circuit(conn);
  2878. log_info(LD_APP,"... application connection created and linked.");
  2879. return conn;
  2880. }
  2881. /** Notify any interested controller connections about a new hostname resolve
  2882. * or resolve error. Takes the same arguments as does
  2883. * connection_ap_handshake_socks_resolved(). */
  2884. static void
  2885. tell_controller_about_resolved_result(entry_connection_t *conn,
  2886. int answer_type,
  2887. size_t answer_len,
  2888. const char *answer,
  2889. int ttl,
  2890. time_t expires)
  2891. {
  2892. expires = time(NULL) + ttl;
  2893. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  2894. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  2895. control_event_address_mapped(conn->socks_request->address,
  2896. cp, expires, NULL, 0);
  2897. tor_free(cp);
  2898. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2899. char *cp = tor_strndup(answer, answer_len);
  2900. control_event_address_mapped(conn->socks_request->address,
  2901. cp, expires, NULL, 0);
  2902. tor_free(cp);
  2903. } else {
  2904. control_event_address_mapped(conn->socks_request->address,
  2905. "<error>", time(NULL)+ttl,
  2906. "error=yes", 0);
  2907. }
  2908. }
  2909. /**
  2910. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  2911. * as the answer.
  2912. */
  2913. void
  2914. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  2915. const tor_addr_t *answer,
  2916. int ttl,
  2917. time_t expires)
  2918. {
  2919. if (tor_addr_family(answer) == AF_INET) {
  2920. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  2921. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  2922. (uint8_t*)&a,
  2923. ttl, expires);
  2924. } else if (tor_addr_family(answer) == AF_INET6) {
  2925. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  2926. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  2927. a,
  2928. ttl, expires);
  2929. } else {
  2930. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  2931. tor_addr_family(answer));
  2932. connection_ap_handshake_socks_resolved(conn,
  2933. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  2934. }
  2935. }
  2936. /** Send an answer to an AP connection that has requested a DNS lookup via
  2937. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  2938. * for unreachable; the answer should be in the format specified in the socks
  2939. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  2940. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  2941. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  2942. **/
  2943. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  2944. * interface and those that use it less ugly. */
  2945. MOCK_IMPL(void,
  2946. connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
  2947. int answer_type,
  2948. size_t answer_len,
  2949. const uint8_t *answer,
  2950. int ttl,
  2951. time_t expires))
  2952. {
  2953. char buf[384];
  2954. size_t replylen;
  2955. if (ttl >= 0) {
  2956. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2957. tor_addr_t a;
  2958. tor_addr_from_ipv4n(&a, get_uint32(answer));
  2959. if (! tor_addr_is_null(&a)) {
  2960. client_dns_set_addressmap(conn,
  2961. conn->socks_request->address, &a,
  2962. conn->chosen_exit_name, ttl);
  2963. }
  2964. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2965. tor_addr_t a;
  2966. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  2967. if (! tor_addr_is_null(&a)) {
  2968. client_dns_set_addressmap(conn,
  2969. conn->socks_request->address, &a,
  2970. conn->chosen_exit_name, ttl);
  2971. }
  2972. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2973. char *cp = tor_strndup((char*)answer, answer_len);
  2974. client_dns_set_reverse_addressmap(conn,
  2975. conn->socks_request->address,
  2976. cp,
  2977. conn->chosen_exit_name, ttl);
  2978. tor_free(cp);
  2979. }
  2980. }
  2981. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  2982. if (conn->dns_server_request) {
  2983. /* We had a request on our DNS port: answer it. */
  2984. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  2985. conn->socks_request->has_finished = 1;
  2986. return;
  2987. } else {
  2988. /* This must be a request from the controller. Since answers to those
  2989. * requests are not cached, they do not generate an ADDRMAP event on
  2990. * their own. */
  2991. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  2992. (char*)answer, ttl, expires);
  2993. conn->socks_request->has_finished = 1;
  2994. return;
  2995. }
  2996. /* We shouldn't need to free conn here; it gets marked by the caller. */
  2997. }
  2998. if (conn->socks_request->socks_version == 4) {
  2999. buf[0] = 0x00; /* version */
  3000. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3001. buf[1] = SOCKS4_GRANTED;
  3002. set_uint16(buf+2, 0);
  3003. memcpy(buf+4, answer, 4); /* address */
  3004. replylen = SOCKS4_NETWORK_LEN;
  3005. } else { /* "error" */
  3006. buf[1] = SOCKS4_REJECT;
  3007. memset(buf+2, 0, 6);
  3008. replylen = SOCKS4_NETWORK_LEN;
  3009. }
  3010. } else if (conn->socks_request->socks_version == 5) {
  3011. /* SOCKS5 */
  3012. buf[0] = 0x05; /* version */
  3013. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3014. buf[1] = SOCKS5_SUCCEEDED;
  3015. buf[2] = 0; /* reserved */
  3016. buf[3] = 0x01; /* IPv4 address type */
  3017. memcpy(buf+4, answer, 4); /* address */
  3018. set_uint16(buf+8, 0); /* port == 0. */
  3019. replylen = 10;
  3020. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  3021. buf[1] = SOCKS5_SUCCEEDED;
  3022. buf[2] = 0; /* reserved */
  3023. buf[3] = 0x04; /* IPv6 address type */
  3024. memcpy(buf+4, answer, 16); /* address */
  3025. set_uint16(buf+20, 0); /* port == 0. */
  3026. replylen = 22;
  3027. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3028. buf[1] = SOCKS5_SUCCEEDED;
  3029. buf[2] = 0; /* reserved */
  3030. buf[3] = 0x03; /* Domainname address type */
  3031. buf[4] = (char)answer_len;
  3032. memcpy(buf+5, answer, answer_len); /* address */
  3033. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  3034. replylen = 5+answer_len+2;
  3035. } else {
  3036. buf[1] = SOCKS5_HOST_UNREACHABLE;
  3037. memset(buf+2, 0, 8);
  3038. replylen = 10;
  3039. }
  3040. } else {
  3041. /* no socks version info; don't send anything back */
  3042. return;
  3043. }
  3044. connection_ap_handshake_socks_reply(conn, buf, replylen,
  3045. (answer_type == RESOLVED_TYPE_IPV4 ||
  3046. answer_type == RESOLVED_TYPE_IPV6 ||
  3047. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  3048. 0 : END_STREAM_REASON_RESOLVEFAILED);
  3049. }
  3050. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  3051. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  3052. * handshaking.
  3053. *
  3054. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  3055. * and return, else reply based on <b>endreason</b> (one of
  3056. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  3057. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  3058. */
  3059. void
  3060. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  3061. size_t replylen, int endreason)
  3062. {
  3063. char buf[256];
  3064. socks5_reply_status_t status =
  3065. stream_end_reason_to_socks5_response(endreason);
  3066. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  3067. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3068. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  3069. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  3070. endreason);
  3071. }
  3072. /* Flag this stream's circuit as having completed a stream successfully
  3073. * (for path bias) */
  3074. if (status == SOCKS5_SUCCEEDED ||
  3075. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  3076. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  3077. endreason == END_STREAM_REASON_CONNRESET ||
  3078. endreason == END_STREAM_REASON_NOROUTE ||
  3079. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  3080. if (!conn->edge_.on_circuit ||
  3081. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  3082. if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
  3083. log_info(LD_BUG,
  3084. "No origin circuit for successful SOCKS stream %"PRIu64
  3085. ". Reason: %d",
  3086. (ENTRY_TO_CONN(conn)->global_identifier),
  3087. endreason);
  3088. }
  3089. /*
  3090. * Else DNS remaps and failed hidden service lookups can send us
  3091. * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
  3092. *
  3093. * Perhaps we could make the test more precise; we can tell hidden
  3094. * services by conn->edge_.renddata != NULL; anything analogous for
  3095. * the DNS remap case?
  3096. */
  3097. } else {
  3098. // XXX: Hrmm. It looks like optimistic data can't go through this
  3099. // codepath, but someone should probably test it and make sure.
  3100. // We don't want to mark optimistically opened streams as successful.
  3101. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  3102. }
  3103. }
  3104. if (conn->socks_request->has_finished) {
  3105. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  3106. "connection_ap_handshake_socks_reply.");
  3107. return;
  3108. }
  3109. if (replylen) { /* we already have a reply in mind */
  3110. connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
  3111. conn->socks_request->has_finished = 1;
  3112. return;
  3113. }
  3114. if (conn->socks_request->listener_type ==
  3115. CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
  3116. const char *response = end_reason_to_http_connect_response_line(endreason);
  3117. if (!response) {
  3118. response = "HTTP/1.0 400 Bad Request\r\n\r\n";
  3119. }
  3120. connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
  3121. } else if (conn->socks_request->socks_version == 4) {
  3122. memset(buf,0,SOCKS4_NETWORK_LEN);
  3123. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  3124. /* leave version, destport, destip zero */
  3125. connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  3126. } else if (conn->socks_request->socks_version == 5) {
  3127. size_t buf_len;
  3128. memset(buf,0,sizeof(buf));
  3129. if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
  3130. buf[0] = 5; /* version 5 */
  3131. buf[1] = (char)status;
  3132. buf[2] = 0;
  3133. buf[3] = 1; /* ipv4 addr */
  3134. /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
  3135. buf_len = 10;
  3136. } else { /* AF_INET6. */
  3137. buf[0] = 5; /* version 5 */
  3138. buf[1] = (char)status;
  3139. buf[2] = 0;
  3140. buf[3] = 4; /* ipv6 addr */
  3141. /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
  3142. buf_len = 22;
  3143. }
  3144. connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
  3145. }
  3146. /* If socks_version isn't 4 or 5, don't send anything.
  3147. * This can happen in the case of AP bridges. */
  3148. conn->socks_request->has_finished = 1;
  3149. return;
  3150. }
  3151. /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
  3152. * place the result in <b>bcell</b>. On success return 0; on failure return
  3153. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  3154. * the client.
  3155. *
  3156. * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
  3157. * we don't.
  3158. **/
  3159. STATIC int
  3160. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  3161. uint8_t *end_reason_out)
  3162. {
  3163. relay_header_t rh;
  3164. const uint8_t *body, *nul;
  3165. memset(bcell, 0, sizeof(*bcell));
  3166. *end_reason_out = END_STREAM_REASON_MISC;
  3167. relay_header_unpack(&rh, cell->payload);
  3168. if (rh.length > RELAY_PAYLOAD_SIZE) {
  3169. return -2; /*XXXX why not TORPROTOCOL? */
  3170. }
  3171. bcell->stream_id = rh.stream_id;
  3172. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3173. bcell->is_begindir = 1;
  3174. return 0;
  3175. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  3176. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3177. *end_reason_out = END_STREAM_REASON_INTERNAL;
  3178. return -1;
  3179. }
  3180. body = cell->payload + RELAY_HEADER_SIZE;
  3181. nul = memchr(body, 0, rh.length);
  3182. if (! nul) {
  3183. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3184. "Relay begin cell has no \\0. Closing.");
  3185. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3186. return -1;
  3187. }
  3188. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  3189. (char*)(body),
  3190. &bcell->address,&bcell->port)<0) {
  3191. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3192. "Unable to parse addr:port in relay begin cell. Closing.");
  3193. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3194. return -1;
  3195. }
  3196. if (bcell->port == 0) {
  3197. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3198. "Missing port in relay begin cell. Closing.");
  3199. tor_free(bcell->address);
  3200. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3201. return -1;
  3202. }
  3203. if (body + rh.length >= nul + 4)
  3204. bcell->flags = ntohl(get_uint32(nul+1));
  3205. return 0;
  3206. }
  3207. /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
  3208. * connection, attach it to the circ and connect it. Return 0 on success
  3209. * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
  3210. * where the caller should close the circuit. */
  3211. static int
  3212. handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
  3213. {
  3214. int ret;
  3215. origin_circuit_t *origin_circ;
  3216. assert_circuit_ok(circ);
  3217. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3218. tor_assert(conn);
  3219. log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
  3220. "to the service destination.");
  3221. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3222. conn->base_.address = tor_strdup("(rendezvous)");
  3223. conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  3224. /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
  3225. * service. */
  3226. if (origin_circ->rend_data) {
  3227. conn->rend_data = rend_data_dup(origin_circ->rend_data);
  3228. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3229. ret = rend_service_set_connection_addr_port(conn, origin_circ);
  3230. } else if (origin_circ->hs_ident) {
  3231. /* Setup the identifier to be the one for the circuit service. */
  3232. conn->hs_ident =
  3233. hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
  3234. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3235. ret = hs_service_set_conn_addr_port(origin_circ, conn);
  3236. } else {
  3237. /* We should never get here if the circuit's purpose is rendezvous. */
  3238. tor_assert_nonfatal_unreached();
  3239. return -1;
  3240. }
  3241. if (ret < 0) {
  3242. log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
  3243. fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
  3244. /* Send back reason DONE because we want to make hidden service port
  3245. * scanning harder thus instead of returning that the exit policy
  3246. * didn't match, which makes it obvious that the port is closed,
  3247. * return DONE and kill the circuit. That way, a user (malicious or
  3248. * not) needs one circuit per bad port unless it matches the policy of
  3249. * the hidden service. */
  3250. relay_send_end_cell_from_edge(conn->stream_id, circ,
  3251. END_STREAM_REASON_DONE,
  3252. origin_circ->cpath->prev);
  3253. connection_free_(TO_CONN(conn));
  3254. /* Drop the circuit here since it might be someone deliberately
  3255. * scanning the hidden service ports. Note that this mitigates port
  3256. * scanning by adding more work on the attacker side to successfully
  3257. * scan but does not fully solve it. */
  3258. if (ret < -1) {
  3259. return END_CIRC_AT_ORIGIN;
  3260. } else {
  3261. return 0;
  3262. }
  3263. }
  3264. /* Link the circuit and the connection crypt path. */
  3265. conn->cpath_layer = origin_circ->cpath->prev;
  3266. /* Add it into the linked list of p_streams on this circuit */
  3267. conn->next_stream = origin_circ->p_streams;
  3268. origin_circ->p_streams = conn;
  3269. conn->on_circuit = circ;
  3270. assert_circuit_ok(circ);
  3271. hs_inc_rdv_stream_counter(origin_circ);
  3272. /* Connect tor to the hidden service destination. */
  3273. connection_exit_connect(conn);
  3274. /* For path bias: This circuit was used successfully */
  3275. pathbias_mark_use_success(origin_circ);
  3276. return 0;
  3277. }
  3278. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  3279. * an exit hop for the circuit, or we are the origin and it is a
  3280. * rendezvous begin.
  3281. *
  3282. * Launch a new exit connection and initialize things appropriately.
  3283. *
  3284. * If it's a rendezvous stream, call connection_exit_connect() on
  3285. * it.
  3286. *
  3287. * For general streams, call dns_resolve() on it first, and only call
  3288. * connection_exit_connect() if the dns answer is already known.
  3289. *
  3290. * Note that we don't call connection_add() on the new stream! We wait
  3291. * for connection_exit_connect() to do that.
  3292. *
  3293. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  3294. * Else return 0.
  3295. */
  3296. int
  3297. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  3298. {
  3299. edge_connection_t *n_stream;
  3300. relay_header_t rh;
  3301. char *address = NULL;
  3302. uint16_t port = 0;
  3303. or_circuit_t *or_circ = NULL;
  3304. origin_circuit_t *origin_circ = NULL;
  3305. crypt_path_t *layer_hint = NULL;
  3306. const or_options_t *options = get_options();
  3307. begin_cell_t bcell;
  3308. int rv;
  3309. uint8_t end_reason=0;
  3310. assert_circuit_ok(circ);
  3311. if (!CIRCUIT_IS_ORIGIN(circ)) {
  3312. or_circ = TO_OR_CIRCUIT(circ);
  3313. } else {
  3314. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3315. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3316. layer_hint = origin_circ->cpath->prev;
  3317. }
  3318. relay_header_unpack(&rh, cell->payload);
  3319. if (rh.length > RELAY_PAYLOAD_SIZE)
  3320. return -END_CIRC_REASON_TORPROTOCOL;
  3321. if (!server_mode(options) &&
  3322. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  3323. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3324. "Relay begin cell at non-server. Closing.");
  3325. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3326. END_STREAM_REASON_EXITPOLICY, NULL);
  3327. return 0;
  3328. }
  3329. rv = begin_cell_parse(cell, &bcell, &end_reason);
  3330. if (rv < -1) {
  3331. return -END_CIRC_REASON_TORPROTOCOL;
  3332. } else if (rv == -1) {
  3333. tor_free(bcell.address);
  3334. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
  3335. return 0;
  3336. }
  3337. if (! bcell.is_begindir) {
  3338. /* Steal reference */
  3339. address = bcell.address;
  3340. port = bcell.port;
  3341. if (or_circ && or_circ->p_chan) {
  3342. const int client_chan = channel_is_client(or_circ->p_chan);
  3343. if ((client_chan ||
  3344. (!connection_or_digest_is_known_relay(
  3345. or_circ->p_chan->identity_digest) &&
  3346. should_refuse_unknown_exits(options)))) {
  3347. /* Don't let clients use us as a single-hop proxy. It attracts
  3348. * attackers and users who'd be better off with, well, single-hop
  3349. * proxies. */
  3350. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3351. "Attempt by %s to open a stream %s. Closing.",
  3352. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  3353. client_chan ? "on first hop of circuit" :
  3354. "from unknown relay");
  3355. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3356. client_chan ?
  3357. END_STREAM_REASON_TORPROTOCOL :
  3358. END_STREAM_REASON_MISC,
  3359. NULL);
  3360. tor_free(address);
  3361. return 0;
  3362. }
  3363. }
  3364. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3365. if (!directory_permits_begindir_requests(options) ||
  3366. circ->purpose != CIRCUIT_PURPOSE_OR) {
  3367. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3368. END_STREAM_REASON_NOTDIRECTORY, layer_hint);
  3369. return 0;
  3370. }
  3371. /* Make sure to get the 'real' address of the previous hop: the
  3372. * caller might want to know whether the remote IP address has changed,
  3373. * and we might already have corrected base_.addr[ess] for the relay's
  3374. * canonical IP address. */
  3375. if (or_circ && or_circ->p_chan)
  3376. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  3377. else
  3378. address = tor_strdup("127.0.0.1");
  3379. port = 1; /* XXXX This value is never actually used anywhere, and there
  3380. * isn't "really" a connection here. But we
  3381. * need to set it to something nonzero. */
  3382. } else {
  3383. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3384. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3385. END_STREAM_REASON_INTERNAL, layer_hint);
  3386. return 0;
  3387. }
  3388. if (! options->IPv6Exit) {
  3389. /* I don't care if you prefer IPv6; I can't give you any. */
  3390. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  3391. /* If you don't want IPv4, I can't help. */
  3392. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  3393. tor_free(address);
  3394. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3395. END_STREAM_REASON_EXITPOLICY, layer_hint);
  3396. return 0;
  3397. }
  3398. }
  3399. log_debug(LD_EXIT,"Creating new exit connection.");
  3400. /* The 'AF_INET' here is temporary; we might need to change it later in
  3401. * connection_exit_connect(). */
  3402. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3403. /* Remember the tunneled request ID in the new edge connection, so that
  3404. * we can measure download times. */
  3405. n_stream->dirreq_id = circ->dirreq_id;
  3406. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  3407. n_stream->begincell_flags = bcell.flags;
  3408. n_stream->stream_id = rh.stream_id;
  3409. n_stream->base_.port = port;
  3410. /* leave n_stream->s at -1, because it's not yet valid */
  3411. n_stream->package_window = STREAMWINDOW_START;
  3412. n_stream->deliver_window = STREAMWINDOW_START;
  3413. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  3414. int ret;
  3415. tor_free(address);
  3416. /* We handle this circuit and stream in this function for all supported
  3417. * hidden service version. */
  3418. ret = handle_hs_exit_conn(circ, n_stream);
  3419. if (ret == 0) {
  3420. /* This was a valid cell. Count it as delivered + overhead. */
  3421. circuit_read_valid_data(origin_circ, rh.length);
  3422. }
  3423. return ret;
  3424. }
  3425. tor_strlower(address);
  3426. n_stream->base_.address = address;
  3427. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3428. /* default to failed, change in dns_resolve if it turns out not to fail */
  3429. /* If we're hibernating or shutting down, we refuse to open new streams. */
  3430. if (we_are_hibernating()) {
  3431. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3432. END_STREAM_REASON_HIBERNATING, NULL);
  3433. connection_free_(TO_CONN(n_stream));
  3434. return 0;
  3435. }
  3436. n_stream->on_circuit = circ;
  3437. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3438. tor_addr_t tmp_addr;
  3439. tor_assert(or_circ);
  3440. if (or_circ->p_chan &&
  3441. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  3442. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  3443. }
  3444. return connection_exit_connect_dir(n_stream);
  3445. }
  3446. log_debug(LD_EXIT,"about to start the dns_resolve().");
  3447. /* send it off to the gethostbyname farm */
  3448. switch (dns_resolve(n_stream)) {
  3449. case 1: /* resolve worked; now n_stream is attached to circ. */
  3450. assert_circuit_ok(circ);
  3451. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  3452. connection_exit_connect(n_stream);
  3453. return 0;
  3454. case -1: /* resolve failed */
  3455. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3456. END_STREAM_REASON_RESOLVEFAILED, NULL);
  3457. /* n_stream got freed. don't touch it. */
  3458. break;
  3459. case 0: /* resolve added to pending list */
  3460. assert_circuit_ok(circ);
  3461. break;
  3462. }
  3463. return 0;
  3464. }
  3465. /**
  3466. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  3467. * circuit <b>circ</b>;
  3468. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  3469. */
  3470. int
  3471. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  3472. {
  3473. edge_connection_t *dummy_conn;
  3474. relay_header_t rh;
  3475. assert_circuit_ok(TO_CIRCUIT(circ));
  3476. relay_header_unpack(&rh, cell->payload);
  3477. if (rh.length > RELAY_PAYLOAD_SIZE)
  3478. return -1;
  3479. /* This 'dummy_conn' only exists to remember the stream ID
  3480. * associated with the resolve request; and to make the
  3481. * implementation of dns.c more uniform. (We really only need to
  3482. * remember the circuit, the stream ID, and the hostname to be
  3483. * resolved; but if we didn't store them in a connection like this,
  3484. * the housekeeping in dns.c would get way more complicated.)
  3485. */
  3486. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3487. dummy_conn->stream_id = rh.stream_id;
  3488. dummy_conn->base_.address = tor_strndup(
  3489. (char*)cell->payload+RELAY_HEADER_SIZE,
  3490. rh.length);
  3491. dummy_conn->base_.port = 0;
  3492. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3493. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  3494. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  3495. /* send it off to the gethostbyname farm */
  3496. switch (dns_resolve(dummy_conn)) {
  3497. case -1: /* Impossible to resolve; a resolved cell was sent. */
  3498. /* Connection freed; don't touch it. */
  3499. return 0;
  3500. case 1: /* The result was cached; a resolved cell was sent. */
  3501. if (!dummy_conn->base_.marked_for_close)
  3502. connection_free_(TO_CONN(dummy_conn));
  3503. return 0;
  3504. case 0: /* resolve added to pending list */
  3505. assert_circuit_ok(TO_CIRCUIT(circ));
  3506. break;
  3507. }
  3508. return 0;
  3509. }
  3510. /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
  3511. * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
  3512. */
  3513. static int
  3514. my_exit_policy_rejects(const tor_addr_t *addr,
  3515. uint16_t port,
  3516. const char **why_rejected)
  3517. {
  3518. if (router_compare_to_my_exit_policy(addr, port)) {
  3519. *why_rejected = "";
  3520. return 1;
  3521. } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
  3522. *why_rejected = " (IPv6 address without IPv6Exit configured)";
  3523. return 1;
  3524. }
  3525. return 0;
  3526. }
  3527. /** Connect to conn's specified addr and port. If it worked, conn
  3528. * has now been added to the connection_array.
  3529. *
  3530. * Send back a connected cell. Include the resolved IP of the destination
  3531. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  3532. * streams must not reveal what IP they connected to.)
  3533. */
  3534. void
  3535. connection_exit_connect(edge_connection_t *edge_conn)
  3536. {
  3537. const tor_addr_t *addr;
  3538. uint16_t port;
  3539. connection_t *conn = TO_CONN(edge_conn);
  3540. int socket_error = 0, result;
  3541. const char *why_failed_exit_policy = NULL;
  3542. /* Apply exit policy to non-rendezvous connections. */
  3543. if (! connection_edge_is_rendezvous_stream(edge_conn) &&
  3544. my_exit_policy_rejects(&edge_conn->base_.addr,
  3545. edge_conn->base_.port,
  3546. &why_failed_exit_policy)) {
  3547. if (BUG(!why_failed_exit_policy))
  3548. why_failed_exit_policy = "";
  3549. log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
  3550. escaped_safe_str_client(conn->address), conn->port,
  3551. why_failed_exit_policy);
  3552. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  3553. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3554. connection_free(conn);
  3555. return;
  3556. }
  3557. #ifdef HAVE_SYS_UN_H
  3558. if (conn->socket_family != AF_UNIX) {
  3559. #else
  3560. {
  3561. #endif /* defined(HAVE_SYS_UN_H) */
  3562. addr = &conn->addr;
  3563. port = conn->port;
  3564. if (tor_addr_family(addr) == AF_INET6)
  3565. conn->socket_family = AF_INET6;
  3566. log_debug(LD_EXIT, "about to try connecting");
  3567. result = connection_connect(conn, conn->address,
  3568. addr, port, &socket_error);
  3569. #ifdef HAVE_SYS_UN_H
  3570. } else {
  3571. /*
  3572. * In the AF_UNIX case, we expect to have already had conn->port = 1,
  3573. * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
  3574. * case in connection_handle_listener_read()), and conn->address should
  3575. * have the socket path to connect to.
  3576. */
  3577. tor_assert(conn->address && strlen(conn->address) > 0);
  3578. log_debug(LD_EXIT, "about to try connecting");
  3579. result = connection_connect_unix(conn, conn->address, &socket_error);
  3580. #endif /* defined(HAVE_SYS_UN_H) */
  3581. }
  3582. switch (result) {
  3583. case -1: {
  3584. int reason = errno_to_stream_end_reason(socket_error);
  3585. connection_edge_end(edge_conn, reason);
  3586. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3587. connection_free(conn);
  3588. return;
  3589. }
  3590. case 0:
  3591. conn->state = EXIT_CONN_STATE_CONNECTING;
  3592. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  3593. /* writable indicates finish;
  3594. * readable/error indicates broken link in windows-land. */
  3595. return;
  3596. /* case 1: fall through */
  3597. }
  3598. conn->state = EXIT_CONN_STATE_OPEN;
  3599. if (connection_get_outbuf_len(conn)) {
  3600. /* in case there are any queued data cells, from e.g. optimistic data */
  3601. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  3602. } else {
  3603. connection_watch_events(conn, READ_EVENT);
  3604. }
  3605. /* also, deliver a 'connected' cell back through the circuit. */
  3606. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  3607. /* don't send an address back! */
  3608. connection_edge_send_command(edge_conn,
  3609. RELAY_COMMAND_CONNECTED,
  3610. NULL, 0);
  3611. } else { /* normal stream */
  3612. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  3613. int connected_payload_len =
  3614. connected_cell_format_payload(connected_payload, &conn->addr,
  3615. edge_conn->address_ttl);
  3616. if (connected_payload_len < 0) {
  3617. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  3618. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3619. connection_free(conn);
  3620. return;
  3621. }
  3622. connection_edge_send_command(edge_conn,
  3623. RELAY_COMMAND_CONNECTED,
  3624. (char*)connected_payload,
  3625. connected_payload_len);
  3626. }
  3627. }
  3628. /** Given an exit conn that should attach to us as a directory server, open a
  3629. * bridge connection with a linked connection pair, create a new directory
  3630. * conn, and join them together. Return 0 on success (or if there was an
  3631. * error we could send back an end cell for). Return -(some circuit end
  3632. * reason) if the circuit needs to be torn down. Either connects
  3633. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  3634. */
  3635. static int
  3636. connection_exit_connect_dir(edge_connection_t *exitconn)
  3637. {
  3638. dir_connection_t *dirconn = NULL;
  3639. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  3640. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  3641. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  3642. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  3643. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  3644. dirconn->base_.port = 0;
  3645. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  3646. dirconn->base_.type = CONN_TYPE_DIR;
  3647. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  3648. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  3649. /* Note that the new dir conn belongs to the same tunneled request as
  3650. * the edge conn, so that we can measure download times. */
  3651. dirconn->dirreq_id = exitconn->dirreq_id;
  3652. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  3653. if (connection_add(TO_CONN(exitconn))<0) {
  3654. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3655. connection_free_(TO_CONN(exitconn));
  3656. connection_free_(TO_CONN(dirconn));
  3657. return 0;
  3658. }
  3659. /* link exitconn to circ, now that we know we can use it. */
  3660. exitconn->next_stream = circ->n_streams;
  3661. circ->n_streams = exitconn;
  3662. if (connection_add(TO_CONN(dirconn))<0) {
  3663. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3664. connection_close_immediate(TO_CONN(exitconn));
  3665. connection_mark_for_close(TO_CONN(exitconn));
  3666. connection_free_(TO_CONN(dirconn));
  3667. return 0;
  3668. }
  3669. connection_start_reading(TO_CONN(dirconn));
  3670. connection_start_reading(TO_CONN(exitconn));
  3671. if (connection_edge_send_command(exitconn,
  3672. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  3673. connection_mark_for_close(TO_CONN(exitconn));
  3674. connection_mark_for_close(TO_CONN(dirconn));
  3675. return 0;
  3676. }
  3677. return 0;
  3678. }
  3679. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  3680. * it is a general stream.
  3681. */
  3682. int
  3683. connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
  3684. {
  3685. tor_assert(conn);
  3686. /* It should not be possible to set both of these structs */
  3687. tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
  3688. if (conn->rend_data || conn->hs_ident) {
  3689. return 1;
  3690. }
  3691. return 0;
  3692. }
  3693. /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
  3694. * to exit from it, or 0 if it probably will not allow it.
  3695. * (We might be uncertain if conn's destination address has not yet been
  3696. * resolved.)
  3697. */
  3698. int
  3699. connection_ap_can_use_exit(const entry_connection_t *conn,
  3700. const node_t *exit_node)
  3701. {
  3702. const or_options_t *options = get_options();
  3703. tor_assert(conn);
  3704. tor_assert(conn->socks_request);
  3705. tor_assert(exit_node);
  3706. /* If a particular exit node has been requested for the new connection,
  3707. * make sure the exit node of the existing circuit matches exactly.
  3708. */
  3709. if (conn->chosen_exit_name) {
  3710. const node_t *chosen_exit =
  3711. node_get_by_nickname(conn->chosen_exit_name, 0);
  3712. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  3713. exit_node->identity, DIGEST_LEN)) {
  3714. /* doesn't match */
  3715. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  3716. // conn->chosen_exit_name, exit->nickname);
  3717. return 0;
  3718. }
  3719. }
  3720. if (conn->use_begindir) {
  3721. /* Internal directory fetches do not count as exiting. */
  3722. return 1;
  3723. }
  3724. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  3725. tor_addr_t addr, *addrp = NULL;
  3726. addr_policy_result_t r;
  3727. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  3728. addrp = &addr;
  3729. } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
  3730. tor_addr_make_null(&addr, AF_INET6);
  3731. addrp = &addr;
  3732. } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
  3733. tor_addr_make_null(&addr, AF_INET);
  3734. addrp = &addr;
  3735. }
  3736. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
  3737. exit_node);
  3738. if (r == ADDR_POLICY_REJECTED)
  3739. return 0; /* We know the address, and the exit policy rejects it. */
  3740. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  3741. return 0; /* We don't know the addr, but the exit policy rejects most
  3742. * addresses with this port. Since the user didn't ask for
  3743. * this node, err on the side of caution. */
  3744. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3745. /* Don't send DNS requests to non-exit servers by default. */
  3746. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
  3747. return 0;
  3748. }
  3749. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
  3750. /* Not a suitable exit. Refuse it. */
  3751. return 0;
  3752. }
  3753. return 1;
  3754. }
  3755. /** If address is of the form "y.onion" with a well-formed handle y:
  3756. * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
  3757. * ONION_V3_HOSTNAME depending on the HS version.
  3758. *
  3759. * If address is of the form "x.y.onion" with a well-formed handle x:
  3760. * Drop "x.", put a NUL after y, lower-case it, and return
  3761. * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
  3762. *
  3763. * If address is of the form "y.onion" with a badly-formed handle y:
  3764. * Return BAD_HOSTNAME and log a message.
  3765. *
  3766. * If address is of the form "y.exit":
  3767. * Put a NUL after y and return EXIT_HOSTNAME.
  3768. *
  3769. * Otherwise:
  3770. * Return NORMAL_HOSTNAME and change nothing.
  3771. */
  3772. hostname_type_t
  3773. parse_extended_hostname(char *address)
  3774. {
  3775. char *s;
  3776. char *q;
  3777. char query[HS_SERVICE_ADDR_LEN_BASE32+1];
  3778. s = strrchr(address,'.');
  3779. if (!s)
  3780. return NORMAL_HOSTNAME; /* no dot, thus normal */
  3781. if (!strcmp(s+1,"exit")) {
  3782. *s = 0; /* NUL-terminate it */
  3783. return EXIT_HOSTNAME; /* .exit */
  3784. }
  3785. if (strcmp(s+1,"onion"))
  3786. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  3787. /* so it is .onion */
  3788. *s = 0; /* NUL-terminate it */
  3789. /* locate a 'sub-domain' component, in order to remove it */
  3790. q = strrchr(address, '.');
  3791. if (q == address) {
  3792. goto failed; /* reject sub-domain, as DNS does */
  3793. }
  3794. q = (NULL == q) ? address : q + 1;
  3795. if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
  3796. HS_SERVICE_ADDR_LEN_BASE32+1)
  3797. goto failed;
  3798. if (q != address) {
  3799. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  3800. }
  3801. if (rend_valid_v2_service_id(query)) {
  3802. return ONION_V2_HOSTNAME; /* success */
  3803. }
  3804. if (hs_address_is_valid(query)) {
  3805. return ONION_V3_HOSTNAME;
  3806. }
  3807. failed:
  3808. /* otherwise, return to previous state and return 0 */
  3809. *s = '.';
  3810. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  3811. safe_str_client(address));
  3812. return BAD_HOSTNAME;
  3813. }
  3814. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  3815. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  3816. * at <b>b</b>. */
  3817. static int
  3818. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  3819. {
  3820. if (a == NULL) {
  3821. return (b == NULL);
  3822. } else if (b == NULL) {
  3823. return 0;
  3824. } else if (alen != blen) {
  3825. return 0;
  3826. } else {
  3827. return tor_memeq(a, b, alen);
  3828. }
  3829. }
  3830. /**
  3831. * Return true iff none of the isolation flags and fields in <b>conn</b>
  3832. * should prevent it from being attached to <b>circ</b>.
  3833. */
  3834. int
  3835. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  3836. const origin_circuit_t *circ)
  3837. {
  3838. const uint8_t iso = conn->entry_cfg.isolation_flags;
  3839. const socks_request_t *sr = conn->socks_request;
  3840. /* If circ has never been used for an isolated connection, we can
  3841. * totally use it for this one. */
  3842. if (!circ->isolation_values_set)
  3843. return 1;
  3844. /* If circ has been used for connections having more than one value
  3845. * for some field f, it will have the corresponding bit set in
  3846. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  3847. * in common with iso, then conn must be isolated from at least
  3848. * one stream that has been attached to circ. */
  3849. if ((iso & circ->isolation_flags_mixed) != 0) {
  3850. /* For at least one field where conn is isolated, the circuit
  3851. * already has mixed streams. */
  3852. return 0;
  3853. }
  3854. if (! conn->original_dest_address) {
  3855. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  3856. "having set conn->original_dest_address");
  3857. ((entry_connection_t*)conn)->original_dest_address =
  3858. tor_strdup(conn->socks_request->address);
  3859. }
  3860. if ((iso & ISO_STREAM) &&
  3861. (circ->associated_isolated_stream_global_id !=
  3862. ENTRY_TO_CONN(conn)->global_identifier))
  3863. return 0;
  3864. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  3865. return 0;
  3866. if ((iso & ISO_DESTADDR) &&
  3867. strcasecmp(conn->original_dest_address, circ->dest_address))
  3868. return 0;
  3869. if ((iso & ISO_SOCKSAUTH) &&
  3870. (! memeq_opt(sr->username, sr->usernamelen,
  3871. circ->socks_username, circ->socks_username_len) ||
  3872. ! memeq_opt(sr->password, sr->passwordlen,
  3873. circ->socks_password, circ->socks_password_len)))
  3874. return 0;
  3875. if ((iso & ISO_CLIENTPROTO) &&
  3876. (conn->socks_request->listener_type != circ->client_proto_type ||
  3877. conn->socks_request->socks_version != circ->client_proto_socksver))
  3878. return 0;
  3879. if ((iso & ISO_CLIENTADDR) &&
  3880. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3881. return 0;
  3882. if ((iso & ISO_SESSIONGRP) &&
  3883. conn->entry_cfg.session_group != circ->session_group)
  3884. return 0;
  3885. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  3886. return 0;
  3887. return 1;
  3888. }
  3889. /**
  3890. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  3891. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  3892. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  3893. * a bitfield of isolation flags that we would have to set in
  3894. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  3895. * <b>circ</b> has had no streams attached to it.
  3896. */
  3897. int
  3898. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  3899. origin_circuit_t *circ,
  3900. int dry_run)
  3901. {
  3902. const socks_request_t *sr = conn->socks_request;
  3903. if (! conn->original_dest_address) {
  3904. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  3905. "having set conn->original_dest_address");
  3906. ((entry_connection_t*)conn)->original_dest_address =
  3907. tor_strdup(conn->socks_request->address);
  3908. }
  3909. if (!circ->isolation_values_set) {
  3910. if (dry_run)
  3911. return -1;
  3912. circ->associated_isolated_stream_global_id =
  3913. ENTRY_TO_CONN(conn)->global_identifier;
  3914. circ->dest_port = conn->socks_request->port;
  3915. circ->dest_address = tor_strdup(conn->original_dest_address);
  3916. circ->client_proto_type = conn->socks_request->listener_type;
  3917. circ->client_proto_socksver = conn->socks_request->socks_version;
  3918. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  3919. circ->session_group = conn->entry_cfg.session_group;
  3920. circ->nym_epoch = conn->nym_epoch;
  3921. circ->socks_username = sr->username ?
  3922. tor_memdup(sr->username, sr->usernamelen) : NULL;
  3923. circ->socks_password = sr->password ?
  3924. tor_memdup(sr->password, sr->passwordlen) : NULL;
  3925. circ->socks_username_len = sr->usernamelen;
  3926. circ->socks_password_len = sr->passwordlen;
  3927. circ->isolation_values_set = 1;
  3928. return 0;
  3929. } else {
  3930. uint8_t mixed = 0;
  3931. if (conn->socks_request->port != circ->dest_port)
  3932. mixed |= ISO_DESTPORT;
  3933. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  3934. mixed |= ISO_DESTADDR;
  3935. if (!memeq_opt(sr->username, sr->usernamelen,
  3936. circ->socks_username, circ->socks_username_len) ||
  3937. !memeq_opt(sr->password, sr->passwordlen,
  3938. circ->socks_password, circ->socks_password_len))
  3939. mixed |= ISO_SOCKSAUTH;
  3940. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  3941. conn->socks_request->socks_version != circ->client_proto_socksver))
  3942. mixed |= ISO_CLIENTPROTO;
  3943. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3944. mixed |= ISO_CLIENTADDR;
  3945. if (conn->entry_cfg.session_group != circ->session_group)
  3946. mixed |= ISO_SESSIONGRP;
  3947. if (conn->nym_epoch != circ->nym_epoch)
  3948. mixed |= ISO_NYM_EPOCH;
  3949. if (dry_run)
  3950. return mixed;
  3951. if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
  3952. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  3953. "isolation flags.");
  3954. }
  3955. circ->isolation_flags_mixed |= mixed;
  3956. return 0;
  3957. }
  3958. }
  3959. /**
  3960. * Clear the isolation settings on <b>circ</b>.
  3961. *
  3962. * This only works on an open circuit that has never had a stream attached to
  3963. * it, and whose isolation settings are hypothetical. (We set hypothetical
  3964. * isolation settings on circuits as we're launching them, so that we
  3965. * know whether they can handle more streams or whether we need to launch
  3966. * even more circuits. Once the circuit is open, if it turns out that
  3967. * we no longer have any streams to attach to it, we clear the isolation flags
  3968. * and data so that other streams can have a chance.)
  3969. */
  3970. void
  3971. circuit_clear_isolation(origin_circuit_t *circ)
  3972. {
  3973. if (circ->isolation_any_streams_attached) {
  3974. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  3975. return;
  3976. }
  3977. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  3978. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  3979. "circuit");
  3980. return;
  3981. }
  3982. circ->isolation_values_set = 0;
  3983. circ->isolation_flags_mixed = 0;
  3984. circ->associated_isolated_stream_global_id = 0;
  3985. circ->client_proto_type = 0;
  3986. circ->client_proto_socksver = 0;
  3987. circ->dest_port = 0;
  3988. tor_addr_make_unspec(&circ->client_addr);
  3989. tor_free(circ->dest_address);
  3990. circ->session_group = -1;
  3991. circ->nym_epoch = 0;
  3992. if (circ->socks_username) {
  3993. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  3994. tor_free(circ->socks_username);
  3995. }
  3996. if (circ->socks_password) {
  3997. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  3998. tor_free(circ->socks_password);
  3999. }
  4000. circ->socks_username_len = circ->socks_password_len = 0;
  4001. }
  4002. /** Free all storage held in module-scoped variables for connection_edge.c */
  4003. void
  4004. connection_edge_free_all(void)
  4005. {
  4006. untried_pending_connections = 0;
  4007. smartlist_free(pending_entry_connections);
  4008. pending_entry_connections = NULL;
  4009. mainloop_event_free(attach_pending_entry_connections_ev);
  4010. }