connection_edge.c 156 KB

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