connection_edge.c 155 KB

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