connection_edge.c 156 KB

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