connection_edge.c 151 KB

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