connection_edge.c 160 KB

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