connection_edge.c 148 KB

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