connection_edge.c 140 KB

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