connection_edge.c 163 KB

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