connection_edge.c 155 KB

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