connection_edge.c 163 KB

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