connection_edge.c 153 KB

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