connection_edge.c 127 KB

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