connection_edge.c 164 KB

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