connection_edge.c 145 KB

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