connection_edge.c 154 KB

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