connection_edge.c 149 KB

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