connection_edge.c 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033
  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-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. **/
  10. #include "or.h"
  11. #include "buffers.h"
  12. #include "circuitlist.h"
  13. #include "circuituse.h"
  14. #include "config.h"
  15. #include "connection.h"
  16. #include "connection_edge.h"
  17. #include "connection_or.h"
  18. #include "control.h"
  19. #include "dns.h"
  20. #include "dnsserv.h"
  21. #include "dirserv.h"
  22. #include "hibernate.h"
  23. #include "main.h"
  24. #include "nodelist.h"
  25. #include "policies.h"
  26. #include "reasons.h"
  27. #include "relay.h"
  28. #include "rendclient.h"
  29. #include "rendcommon.h"
  30. #include "rendservice.h"
  31. #include "rephist.h"
  32. #include "router.h"
  33. #include "routerlist.h"
  34. #ifdef HAVE_LINUX_TYPES_H
  35. #include <linux/types.h>
  36. #endif
  37. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  38. #include <linux/netfilter_ipv4.h>
  39. #define TRANS_NETFILTER
  40. #endif
  41. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  42. #include <net/if.h>
  43. #include <net/pfvar.h>
  44. #define TRANS_PF
  45. #endif
  46. #define SOCKS4_GRANTED 90
  47. #define SOCKS4_REJECT 91
  48. static int connection_ap_handshake_process_socks(edge_connection_t *conn);
  49. static int connection_ap_process_natd(edge_connection_t *conn);
  50. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  51. static int address_is_in_virtual_range(const char *addr);
  52. static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
  53. static void clear_trackexithost_mappings(const char *exitname);
  54. /** An AP stream has failed/finished. If it hasn't already sent back
  55. * a socks reply, send one now (based on endreason). Also set
  56. * has_sent_end to 1, and mark the conn.
  57. */
  58. void
  59. _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
  60. int line, const char *file)
  61. {
  62. tor_assert(conn->_base.type == CONN_TYPE_AP);
  63. conn->edge_has_sent_end = 1; /* no circ yet */
  64. if (conn->_base.marked_for_close) {
  65. /* This call will warn as appropriate. */
  66. _connection_mark_for_close(TO_CONN(conn), line, file);
  67. return;
  68. }
  69. if (!conn->socks_request->has_finished) {
  70. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  71. log_warn(LD_BUG,
  72. "stream (marked at %s:%d) sending two socks replies?",
  73. file, line);
  74. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  75. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  76. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  77. connection_ap_handshake_socks_resolved(conn,
  78. RESOLVED_TYPE_ERROR_TRANSIENT,
  79. 0, NULL, -1, -1);
  80. else /* unknown or no handshake at all. send no response. */
  81. conn->socks_request->has_finished = 1;
  82. }
  83. _connection_mark_and_flush(TO_CONN(conn), line, file);
  84. conn->end_reason = endreason;
  85. }
  86. /** There was an EOF. Send an end and mark the connection for close.
  87. */
  88. int
  89. connection_edge_reached_eof(edge_connection_t *conn)
  90. {
  91. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  92. connection_state_is_open(TO_CONN(conn))) {
  93. /* it still has stuff to process. don't let it die yet. */
  94. return 0;
  95. }
  96. log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
  97. if (!conn->_base.marked_for_close) {
  98. /* only mark it if not already marked. it's possible to
  99. * get the 'end' right around when the client hangs up on us. */
  100. connection_edge_end(conn, END_STREAM_REASON_DONE);
  101. if (conn->socks_request) /* eof, so don't send a socks reply back */
  102. conn->socks_request->has_finished = 1;
  103. connection_mark_for_close(TO_CONN(conn));
  104. }
  105. return 0;
  106. }
  107. /** Handle new bytes on conn->inbuf based on state:
  108. * - If it's waiting for socks info, try to read another step of the
  109. * socks handshake out of conn->inbuf.
  110. * - If it's waiting for the original destination, fetch it.
  111. * - If it's open, then package more relay cells from the stream.
  112. * - Else, leave the bytes on inbuf alone for now.
  113. *
  114. * Mark and return -1 if there was an unexpected error with the conn,
  115. * else return 0.
  116. */
  117. int
  118. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  119. {
  120. tor_assert(conn);
  121. switch (conn->_base.state) {
  122. case AP_CONN_STATE_SOCKS_WAIT:
  123. if (connection_ap_handshake_process_socks(conn) < 0) {
  124. /* already marked */
  125. return -1;
  126. }
  127. return 0;
  128. case AP_CONN_STATE_NATD_WAIT:
  129. if (connection_ap_process_natd(conn) < 0) {
  130. /* already marked */
  131. return -1;
  132. }
  133. return 0;
  134. case AP_CONN_STATE_OPEN:
  135. case EXIT_CONN_STATE_OPEN:
  136. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  137. /* (We already sent an end cell if possible) */
  138. connection_mark_for_close(TO_CONN(conn));
  139. return -1;
  140. }
  141. return 0;
  142. case EXIT_CONN_STATE_CONNECTING:
  143. case AP_CONN_STATE_RENDDESC_WAIT:
  144. case AP_CONN_STATE_CIRCUIT_WAIT:
  145. case AP_CONN_STATE_CONNECT_WAIT:
  146. case AP_CONN_STATE_RESOLVE_WAIT:
  147. case AP_CONN_STATE_CONTROLLER_WAIT:
  148. log_info(LD_EDGE,
  149. "data from edge while in '%s' state. Leaving it on buffer.",
  150. conn_state_to_string(conn->_base.type, conn->_base.state));
  151. return 0;
  152. }
  153. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
  154. tor_fragile_assert();
  155. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  156. connection_mark_for_close(TO_CONN(conn));
  157. return -1;
  158. }
  159. /** This edge needs to be closed, because its circuit has closed.
  160. * Mark it for close and return 0.
  161. */
  162. int
  163. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  164. {
  165. if (!conn->_base.marked_for_close) {
  166. log_info(LD_EDGE,
  167. "CircID %d: At an edge. Marking connection for close.", circ_id);
  168. if (conn->_base.type == CONN_TYPE_AP) {
  169. connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
  170. control_event_stream_bandwidth(conn);
  171. control_event_stream_status(conn, STREAM_EVENT_CLOSED,
  172. END_STREAM_REASON_DESTROY);
  173. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  174. } else {
  175. /* closing the circuit, nothing to send an END to */
  176. conn->edge_has_sent_end = 1;
  177. conn->end_reason = END_STREAM_REASON_DESTROY;
  178. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  179. connection_mark_and_flush(TO_CONN(conn));
  180. }
  181. }
  182. conn->cpath_layer = NULL;
  183. conn->on_circuit = NULL;
  184. return 0;
  185. }
  186. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  187. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  188. * is not a client connection, set the relay end cell's reason for closing
  189. * as <b>reason</b> */
  190. static int
  191. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  192. uint8_t reason, crypt_path_t *cpath_layer)
  193. {
  194. char payload[1];
  195. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  196. /* Never send the server an informative reason code; it doesn't need to
  197. * know why the client stream is failing. */
  198. reason = END_STREAM_REASON_MISC;
  199. }
  200. payload[0] = (char) reason;
  201. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  202. payload, 1, cpath_layer);
  203. }
  204. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  205. * remember that we've done so. If this is not a client connection, set the
  206. * relay end cell's reason for closing as <b>reason</b>.
  207. *
  208. * Return -1 if this function has already been called on this conn,
  209. * else return 0.
  210. */
  211. int
  212. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  213. {
  214. char payload[RELAY_PAYLOAD_SIZE];
  215. size_t payload_len=1;
  216. circuit_t *circ;
  217. uint8_t control_reason = reason;
  218. if (conn->edge_has_sent_end) {
  219. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  220. "on an already ended stream?", reason);
  221. tor_fragile_assert();
  222. return -1;
  223. }
  224. if (conn->_base.marked_for_close) {
  225. log_warn(LD_BUG,
  226. "called on conn that's already marked for close at %s:%d.",
  227. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  228. return 0;
  229. }
  230. circ = circuit_get_by_edge_conn(conn);
  231. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  232. /* If this is a client circuit, don't send the server an informative
  233. * reason code; it doesn't need to know why the client stream is
  234. * failing. */
  235. reason = END_STREAM_REASON_MISC;
  236. }
  237. payload[0] = (char)reason;
  238. if (reason == END_STREAM_REASON_EXITPOLICY &&
  239. !connection_edge_is_rendezvous_stream(conn)) {
  240. int addrlen;
  241. if (tor_addr_family(&conn->_base.addr) == AF_INET) {
  242. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
  243. addrlen = 4;
  244. } else {
  245. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
  246. addrlen = 16;
  247. }
  248. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  249. payload_len += 4+addrlen;
  250. }
  251. if (circ && !circ->marked_for_close) {
  252. log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
  253. connection_edge_send_command(conn, RELAY_COMMAND_END,
  254. payload, payload_len);
  255. } else {
  256. log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
  257. conn->_base.s);
  258. }
  259. conn->edge_has_sent_end = 1;
  260. conn->end_reason = control_reason;
  261. return 0;
  262. }
  263. /** An error has just occurred on an operation on an edge connection
  264. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  265. * appropriate relay end cell to the other end of the connection's circuit.
  266. **/
  267. int
  268. connection_edge_end_errno(edge_connection_t *conn)
  269. {
  270. uint8_t reason;
  271. tor_assert(conn);
  272. reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
  273. return connection_edge_end(conn, reason);
  274. }
  275. /** Connection <b>conn</b> has finished writing and has no bytes left on
  276. * its outbuf.
  277. *
  278. * If it's in state 'open', stop writing, consider responding with a
  279. * sendme, and return.
  280. * Otherwise, stop writing and return.
  281. *
  282. * If <b>conn</b> is broken, mark it for close and return -1, else
  283. * return 0.
  284. */
  285. int
  286. connection_edge_finished_flushing(edge_connection_t *conn)
  287. {
  288. tor_assert(conn);
  289. switch (conn->_base.state) {
  290. case AP_CONN_STATE_OPEN:
  291. case EXIT_CONN_STATE_OPEN:
  292. connection_edge_consider_sending_sendme(conn);
  293. return 0;
  294. case AP_CONN_STATE_SOCKS_WAIT:
  295. case AP_CONN_STATE_NATD_WAIT:
  296. case AP_CONN_STATE_RENDDESC_WAIT:
  297. case AP_CONN_STATE_CIRCUIT_WAIT:
  298. case AP_CONN_STATE_CONNECT_WAIT:
  299. case AP_CONN_STATE_CONTROLLER_WAIT:
  300. case AP_CONN_STATE_RESOLVE_WAIT:
  301. return 0;
  302. default:
  303. log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
  304. tor_fragile_assert();
  305. return -1;
  306. }
  307. return 0;
  308. }
  309. /** Connected handler for exit connections: start writing pending
  310. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  311. * any pending data that may have been received. */
  312. int
  313. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  314. {
  315. connection_t *conn;
  316. tor_assert(edge_conn);
  317. tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  318. conn = TO_CONN(edge_conn);
  319. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  320. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  321. escaped_safe_str(conn->address), conn->port,
  322. safe_str(fmt_addr(&conn->addr)));
  323. rep_hist_note_exit_stream_opened(conn->port);
  324. conn->state = EXIT_CONN_STATE_OPEN;
  325. IF_HAS_NO_BUFFEREVENT(conn)
  326. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  327. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  328. * cells */
  329. connection_start_writing(conn);
  330. /* deliver a 'connected' relay cell back through the circuit. */
  331. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  332. if (connection_edge_send_command(edge_conn,
  333. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  334. return 0; /* circuit is closed, don't continue */
  335. } else {
  336. char connected_payload[20];
  337. int connected_payload_len;
  338. if (tor_addr_family(&conn->addr) == AF_INET) {
  339. set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
  340. set_uint32(connected_payload+4,
  341. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  342. connected_payload_len = 8;
  343. } else {
  344. memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
  345. set_uint32(connected_payload+16,
  346. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  347. connected_payload_len = 20;
  348. }
  349. if (connection_edge_send_command(edge_conn,
  350. RELAY_COMMAND_CONNECTED,
  351. connected_payload, connected_payload_len) < 0)
  352. return 0; /* circuit is closed, don't continue */
  353. }
  354. tor_assert(edge_conn->package_window > 0);
  355. /* in case the server has written anything */
  356. return connection_edge_process_inbuf(edge_conn, 1);
  357. }
  358. /** Define a schedule for how long to wait between retrying
  359. * application connections. Rather than waiting a fixed amount of
  360. * time between each retry, we wait 10 seconds each for the first
  361. * two tries, and 15 seconds for each retry after
  362. * that. Hopefully this will improve the expected user experience. */
  363. static int
  364. compute_retry_timeout(edge_connection_t *conn)
  365. {
  366. int timeout = get_options()->CircuitStreamTimeout;
  367. if (timeout) /* if our config options override the default, use them */
  368. return timeout;
  369. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  370. return 10;
  371. return 15;
  372. }
  373. /** Find all general-purpose AP streams waiting for a response that sent their
  374. * begin/resolve cell too long ago. Detach from their current circuit, and
  375. * mark their current circuit as unsuitable for new streams. Then call
  376. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  377. * available) or launch a new one.
  378. *
  379. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  380. * retry attempt).
  381. */
  382. void
  383. connection_ap_expire_beginning(void)
  384. {
  385. edge_connection_t *conn;
  386. circuit_t *circ;
  387. time_t now = time(NULL);
  388. or_options_t *options = get_options();
  389. int severity;
  390. int cutoff;
  391. int seconds_idle, seconds_since_born;
  392. smartlist_t *conns = get_connection_array();
  393. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  394. if (c->type != CONN_TYPE_AP || c->marked_for_close)
  395. continue;
  396. conn = TO_EDGE_CONN(c);
  397. /* if it's an internal linked connection, don't yell its status. */
  398. severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
  399. ? LOG_INFO : LOG_NOTICE;
  400. seconds_idle = (int)( now - conn->_base.timestamp_lastread );
  401. seconds_since_born = (int)( now - conn->_base.timestamp_created );
  402. if (conn->_base.state == AP_CONN_STATE_OPEN)
  403. continue;
  404. /* We already consider SocksTimeout in
  405. * connection_ap_handshake_attach_circuit(), but we need to consider
  406. * it here too because controllers that put streams in controller_wait
  407. * state never ask Tor to attach the circuit. */
  408. if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
  409. if (seconds_since_born >= options->SocksTimeout) {
  410. log_fn(severity, LD_APP,
  411. "Tried for %d seconds to get a connection to %s:%d. "
  412. "Giving up. (%s)",
  413. seconds_since_born,
  414. safe_str_client(conn->socks_request->address),
  415. conn->socks_request->port,
  416. conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
  417. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  418. }
  419. continue;
  420. }
  421. /* We're in state connect_wait or resolve_wait now -- waiting for a
  422. * reply to our relay cell. See if we want to retry/give up. */
  423. cutoff = compute_retry_timeout(conn);
  424. if (seconds_idle < cutoff)
  425. continue;
  426. circ = circuit_get_by_edge_conn(conn);
  427. if (!circ) { /* it's vanished? */
  428. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  429. safe_str_client(conn->socks_request->address));
  430. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  431. continue;
  432. }
  433. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  434. if (seconds_idle >= options->SocksTimeout) {
  435. log_fn(severity, LD_REND,
  436. "Rend stream is %d seconds late. Giving up on address"
  437. " '%s.onion'.",
  438. seconds_idle,
  439. safe_str_client(conn->socks_request->address));
  440. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  441. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  442. }
  443. continue;
  444. }
  445. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  446. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  447. "We tried for %d seconds to connect to '%s' using exit '%s'."
  448. " Retrying on a new circuit.",
  449. seconds_idle,
  450. safe_str_client(conn->socks_request->address),
  451. conn->cpath_layer ?
  452. conn->cpath_layer->extend_info->nickname : "*unnamed*");
  453. /* send an end down the circuit */
  454. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  455. /* un-mark it as ending, since we're going to reuse it */
  456. conn->edge_has_sent_end = 0;
  457. conn->end_reason = 0;
  458. /* kludge to make us not try this circuit again, yet to allow
  459. * current streams on it to survive if they can: make it
  460. * unattractive to use for new streams */
  461. tor_assert(circ->timestamp_dirty);
  462. circ->timestamp_dirty -= options->MaxCircuitDirtiness;
  463. /* give our stream another 'cutoff' seconds to try */
  464. conn->_base.timestamp_lastread += cutoff;
  465. if (conn->num_socks_retries < 250) /* avoid overflow */
  466. conn->num_socks_retries++;
  467. /* move it back into 'pending' state, and try to attach. */
  468. if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
  469. END_STREAM_REASON_TIMEOUT)<0) {
  470. if (!conn->_base.marked_for_close)
  471. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  472. }
  473. } SMARTLIST_FOREACH_END(conn);
  474. }
  475. /** Tell any AP streams that are waiting for a new circuit to try again,
  476. * either attaching to an available circ or launching a new one.
  477. */
  478. void
  479. connection_ap_attach_pending(void)
  480. {
  481. edge_connection_t *edge_conn;
  482. smartlist_t *conns = get_connection_array();
  483. SMARTLIST_FOREACH(conns, connection_t *, conn,
  484. {
  485. if (conn->marked_for_close ||
  486. conn->type != CONN_TYPE_AP ||
  487. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  488. continue;
  489. edge_conn = TO_EDGE_CONN(conn);
  490. if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
  491. if (!edge_conn->_base.marked_for_close)
  492. connection_mark_unattached_ap(edge_conn,
  493. END_STREAM_REASON_CANT_ATTACH);
  494. }
  495. });
  496. }
  497. /** Tell any AP streams that are waiting for a one-hop tunnel to
  498. * <b>failed_digest</b> that they are going to fail. */
  499. /* XXX022 We should get rid of this function, and instead attach
  500. * one-hop streams to circ->p_streams so they get marked in
  501. * circuit_mark_for_close like normal p_streams. */
  502. void
  503. connection_ap_fail_onehop(const char *failed_digest,
  504. cpath_build_state_t *build_state)
  505. {
  506. edge_connection_t *edge_conn;
  507. char digest[DIGEST_LEN];
  508. smartlist_t *conns = get_connection_array();
  509. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  510. if (conn->marked_for_close ||
  511. conn->type != CONN_TYPE_AP ||
  512. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  513. continue;
  514. edge_conn = TO_EDGE_CONN(conn);
  515. if (!edge_conn->want_onehop)
  516. continue;
  517. if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
  518. memcmp(digest, failed_digest, DIGEST_LEN))
  519. continue;
  520. if (tor_digest_is_zero(digest)) {
  521. /* we don't know the digest; have to compare addr:port */
  522. tor_addr_t addr;
  523. if (!build_state || !build_state->chosen_exit ||
  524. !edge_conn->socks_request || !edge_conn->socks_request->address)
  525. continue;
  526. if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
  527. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  528. build_state->chosen_exit->port != edge_conn->socks_request->port)
  529. continue;
  530. }
  531. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  532. "just failed.", edge_conn->chosen_exit_name,
  533. edge_conn->socks_request->address);
  534. connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
  535. } SMARTLIST_FOREACH_END(conn);
  536. }
  537. /** A circuit failed to finish on its last hop <b>info</b>. If there
  538. * are any streams waiting with this exit node in mind, but they
  539. * don't absolutely require it, make them give up on it.
  540. */
  541. void
  542. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  543. {
  544. edge_connection_t *edge_conn;
  545. const node_t *r1, *r2;
  546. smartlist_t *conns = get_connection_array();
  547. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  548. if (conn->marked_for_close ||
  549. conn->type != CONN_TYPE_AP ||
  550. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  551. continue;
  552. edge_conn = TO_EDGE_CONN(conn);
  553. if (!edge_conn->chosen_exit_optional &&
  554. !edge_conn->chosen_exit_retries)
  555. continue;
  556. r1 = node_get_by_nickname(edge_conn->chosen_exit_name, 0);
  557. r2 = node_get_by_id(info->identity_digest);
  558. if (!r1 || !r2 || r1 != r2)
  559. continue;
  560. tor_assert(edge_conn->socks_request);
  561. if (edge_conn->chosen_exit_optional) {
  562. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  563. safe_str_client(edge_conn->chosen_exit_name),
  564. escaped_safe_str_client(edge_conn->socks_request->address));
  565. edge_conn->chosen_exit_optional = 0;
  566. tor_free(edge_conn->chosen_exit_name); /* clears it */
  567. /* if this port is dangerous, warn or reject it now that we don't
  568. * think it'll be using an enclave. */
  569. consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
  570. }
  571. if (edge_conn->chosen_exit_retries) {
  572. if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
  573. clear_trackexithost_mappings(edge_conn->chosen_exit_name);
  574. tor_free(edge_conn->chosen_exit_name); /* clears it */
  575. /* if this port is dangerous, warn or reject it now that we don't
  576. * think it'll be using an enclave. */
  577. consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
  578. }
  579. }
  580. } SMARTLIST_FOREACH_END(conn);
  581. }
  582. /** The AP connection <b>conn</b> has just failed while attaching or
  583. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  584. * might work. Detach the circuit, and either reattach it, launch a
  585. * new circuit, tell the controller, or give up as a appropriate.
  586. *
  587. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  588. */
  589. int
  590. connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
  591. int reason)
  592. {
  593. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  594. conn->_base.timestamp_lastread = time(NULL);
  595. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  596. /* If we're attaching streams ourself, or if this connection is
  597. * a tunneled directory connection, then just attach it. */
  598. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  599. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  600. return connection_ap_handshake_attach_circuit(conn);
  601. } else {
  602. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  603. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  604. return 0;
  605. }
  606. }
  607. /** A client-side struct to remember requests to rewrite addresses
  608. * to new addresses. These structs are stored in the hash table
  609. * "addressmap" below.
  610. *
  611. * There are 5 ways to set an address mapping:
  612. * - A MapAddress command from the controller [permanent]
  613. * - An AddressMap directive in the torrc [permanent]
  614. * - When a TrackHostExits torrc directive is triggered [temporary]
  615. * - When a DNS resolve succeeds [temporary]
  616. * - When a DNS resolve fails [temporary]
  617. *
  618. * When an addressmap request is made but one is already registered,
  619. * the new one is replaced only if the currently registered one has
  620. * no "new_address" (that is, it's in the process of DNS resolve),
  621. * or if the new one is permanent (expires==0 or 1).
  622. *
  623. * (We overload the 'expires' field, using "0" for mappings set via
  624. * the configuration file, "1" for mappings set from the control
  625. * interface, and other values for DNS and TrackHostExit mappings that can
  626. * expire.)
  627. */
  628. typedef struct {
  629. char *new_address;
  630. time_t expires;
  631. addressmap_entry_source_t source:3;
  632. short num_resolve_failures;
  633. } addressmap_entry_t;
  634. /** Entry for mapping addresses to which virtual address we mapped them to. */
  635. typedef struct {
  636. char *ipv4_address;
  637. char *hostname_address;
  638. } virtaddress_entry_t;
  639. /** A hash table to store client-side address rewrite instructions. */
  640. static strmap_t *addressmap=NULL;
  641. /**
  642. * Table mapping addresses to which virtual address, if any, we
  643. * assigned them to.
  644. *
  645. * We maintain the following invariant: if [A,B] is in
  646. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  647. * must be in addressmap. We do not require that the converse hold:
  648. * if it fails, then we could end up mapping two virtual addresses to
  649. * the same address, which is no disaster.
  650. **/
  651. static strmap_t *virtaddress_reversemap=NULL;
  652. /** Initialize addressmap. */
  653. void
  654. addressmap_init(void)
  655. {
  656. addressmap = strmap_new();
  657. virtaddress_reversemap = strmap_new();
  658. }
  659. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  660. static void
  661. addressmap_ent_free(void *_ent)
  662. {
  663. addressmap_entry_t *ent;
  664. if (!_ent)
  665. return;
  666. ent = _ent;
  667. tor_free(ent->new_address);
  668. tor_free(ent);
  669. }
  670. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
  671. static void
  672. addressmap_virtaddress_ent_free(void *_ent)
  673. {
  674. virtaddress_entry_t *ent;
  675. if (!_ent)
  676. return;
  677. ent = _ent;
  678. tor_free(ent->ipv4_address);
  679. tor_free(ent->hostname_address);
  680. tor_free(ent);
  681. }
  682. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
  683. static void
  684. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  685. {
  686. if (ent && ent->new_address &&
  687. address_is_in_virtual_range(ent->new_address)) {
  688. virtaddress_entry_t *ve =
  689. strmap_get(virtaddress_reversemap, ent->new_address);
  690. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  691. if (ve) {
  692. if (!strcmp(address, ve->ipv4_address))
  693. tor_free(ve->ipv4_address);
  694. if (!strcmp(address, ve->hostname_address))
  695. tor_free(ve->hostname_address);
  696. if (!ve->ipv4_address && !ve->hostname_address) {
  697. tor_free(ve);
  698. strmap_remove(virtaddress_reversemap, ent->new_address);
  699. }
  700. }
  701. }
  702. }
  703. /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
  704. * client address maps. */
  705. static void
  706. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  707. {
  708. addressmap_virtaddress_remove(address, ent);
  709. addressmap_ent_free(ent);
  710. }
  711. /** Unregister all TrackHostExits mappings from any address to
  712. * *.exitname.exit. */
  713. static void
  714. clear_trackexithost_mappings(const char *exitname)
  715. {
  716. char *suffix;
  717. size_t suffix_len;
  718. if (!addressmap || !exitname)
  719. return;
  720. suffix_len = strlen(exitname) + 16;
  721. suffix = tor_malloc(suffix_len);
  722. tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
  723. tor_strlower(suffix);
  724. STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
  725. if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
  726. addressmap_ent_remove(address, ent);
  727. MAP_DEL_CURRENT(address);
  728. }
  729. } STRMAP_FOREACH_END;
  730. tor_free(suffix);
  731. }
  732. /** Remove all entries from the addressmap that were set via the
  733. * configuration file or the command line. */
  734. void
  735. addressmap_clear_configured(void)
  736. {
  737. addressmap_get_mappings(NULL, 0, 0, 0);
  738. }
  739. /** Remove all entries from the addressmap that are set to expire, ever. */
  740. void
  741. addressmap_clear_transient(void)
  742. {
  743. addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
  744. }
  745. /** Clean out entries from the addressmap cache that were
  746. * added long enough ago that they are no longer valid.
  747. */
  748. void
  749. addressmap_clean(time_t now)
  750. {
  751. addressmap_get_mappings(NULL, 2, now, 0);
  752. }
  753. /** Free all the elements in the addressmap, and free the addressmap
  754. * itself. */
  755. void
  756. addressmap_free_all(void)
  757. {
  758. strmap_free(addressmap, addressmap_ent_free);
  759. addressmap = NULL;
  760. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  761. virtaddress_reversemap = NULL;
  762. }
  763. /** Look at address, and rewrite it until it doesn't want any
  764. * more rewrites; but don't get into an infinite loop.
  765. * Don't write more than maxlen chars into address. Return true if the
  766. * address changed; false otherwise. Set *<b>expires_out</b> to the
  767. * expiry time of the result, or to <b>time_max</b> if the result does
  768. * not expire.
  769. */
  770. int
  771. addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
  772. {
  773. addressmap_entry_t *ent;
  774. int rewrites;
  775. char *cp;
  776. time_t expires = TIME_MAX;
  777. for (rewrites = 0; rewrites < 16; rewrites++) {
  778. ent = strmap_get(addressmap, address);
  779. if (!ent || !ent->new_address) {
  780. if (expires_out)
  781. *expires_out = expires;
  782. return (rewrites > 0); /* done, no rewrite needed */
  783. }
  784. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  785. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  786. escaped_safe_str_client(address), cp);
  787. if (ent->expires > 1 && ent->expires < expires)
  788. expires = ent->expires;
  789. tor_free(cp);
  790. strlcpy(address, ent->new_address, maxlen);
  791. }
  792. log_warn(LD_CONFIG,
  793. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  794. escaped_safe_str_client(address));
  795. /* it's fine to rewrite a rewrite, but don't loop forever */
  796. if (expires_out)
  797. *expires_out = TIME_MAX;
  798. return 1;
  799. }
  800. /** If we have a cached reverse DNS entry for the address stored in the
  801. * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
  802. * rewrite to the cached value and return 1. Otherwise return 0. Set
  803. * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
  804. * if the result does not expire. */
  805. static int
  806. addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
  807. {
  808. size_t len = maxlen + 16;
  809. char *s = tor_malloc(len), *cp;
  810. addressmap_entry_t *ent;
  811. int r = 0;
  812. tor_snprintf(s, len, "REVERSE[%s]", address);
  813. ent = strmap_get(addressmap, s);
  814. if (ent) {
  815. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  816. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  817. escaped_safe_str_client(s), cp);
  818. tor_free(cp);
  819. strlcpy(address, ent->new_address, maxlen);
  820. r = 1;
  821. }
  822. if (expires_out)
  823. *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
  824. tor_free(s);
  825. return r;
  826. }
  827. /** Return 1 if <b>address</b> is already registered, else return 0. If address
  828. * is already registered, and <b>update_expires</b> is non-zero, then update
  829. * the expiry time on the mapping with update_expires if it is a
  830. * mapping created by TrackHostExits. */
  831. int
  832. addressmap_have_mapping(const char *address, int update_expiry)
  833. {
  834. addressmap_entry_t *ent;
  835. if (!(ent=strmap_get_lc(addressmap, address)))
  836. return 0;
  837. if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
  838. ent->expires=time(NULL) + update_expiry;
  839. return 1;
  840. }
  841. /** Register a request to map <b>address</b> to <b>new_address</b>,
  842. * which will expire on <b>expires</b> (or 0 if never expires from
  843. * config file, 1 if never expires from controller, 2 if never expires
  844. * (virtual address mapping) from the controller.)
  845. *
  846. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  847. * free as appropriate. We will leave address alone.
  848. *
  849. * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
  850. * any mappings that exist from <b>address</b>.
  851. */
  852. void
  853. addressmap_register(const char *address, char *new_address, time_t expires,
  854. addressmap_entry_source_t source)
  855. {
  856. addressmap_entry_t *ent;
  857. ent = strmap_get(addressmap, address);
  858. if (!new_address || !strcasecmp(address,new_address)) {
  859. /* Remove the mapping, if any. */
  860. tor_free(new_address);
  861. if (ent) {
  862. addressmap_ent_remove(address,ent);
  863. strmap_remove(addressmap, address);
  864. }
  865. return;
  866. }
  867. if (!ent) { /* make a new one and register it */
  868. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  869. strmap_set(addressmap, address, ent);
  870. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  871. if (expires > 1) {
  872. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  873. "since it's already mapped to '%s'",
  874. safe_str_client(address),
  875. safe_str_client(new_address),
  876. safe_str_client(ent->new_address));
  877. tor_free(new_address);
  878. return;
  879. }
  880. if (address_is_in_virtual_range(ent->new_address) &&
  881. expires != 2) {
  882. /* XXX This isn't the perfect test; we want to avoid removing
  883. * mappings set from the control interface _as virtual mapping */
  884. addressmap_virtaddress_remove(address, ent);
  885. }
  886. tor_free(ent->new_address);
  887. } /* else { we have an in-progress resolve with no mapping. } */
  888. ent->new_address = new_address;
  889. ent->expires = expires==2 ? 1 : expires;
  890. ent->num_resolve_failures = 0;
  891. ent->source = source;
  892. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  893. safe_str_client(address),
  894. safe_str_client(ent->new_address));
  895. control_event_address_mapped(address, ent->new_address, expires, NULL);
  896. }
  897. /** An attempt to resolve <b>address</b> failed at some OR.
  898. * Increment the number of resolve failures we have on record
  899. * for it, and then return that number.
  900. */
  901. int
  902. client_dns_incr_failures(const char *address)
  903. {
  904. addressmap_entry_t *ent = strmap_get(addressmap, address);
  905. if (!ent) {
  906. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  907. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  908. strmap_set(addressmap,address,ent);
  909. }
  910. if (ent->num_resolve_failures < SHORT_MAX)
  911. ++ent->num_resolve_failures; /* don't overflow */
  912. log_info(LD_APP, "Address %s now has %d resolve failures.",
  913. safe_str_client(address),
  914. ent->num_resolve_failures);
  915. return ent->num_resolve_failures;
  916. }
  917. /** If <b>address</b> is in the client DNS addressmap, reset
  918. * the number of resolve failures we have on record for it.
  919. * This is used when we fail a stream because it won't resolve:
  920. * otherwise future attempts on that address will only try once.
  921. */
  922. void
  923. client_dns_clear_failures(const char *address)
  924. {
  925. addressmap_entry_t *ent = strmap_get(addressmap, address);
  926. if (ent)
  927. ent->num_resolve_failures = 0;
  928. }
  929. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  930. * We can now use this in subsequent streams via addressmap_rewrite()
  931. * so we can more correctly choose an exit that will allow <b>address</b>.
  932. *
  933. * If <b>exitname</b> is defined, then append the addresses with
  934. * ".exitname.exit" before registering the mapping.
  935. *
  936. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  937. * <b>ttl</b>seconds; otherwise, we use the default.
  938. */
  939. static void
  940. client_dns_set_addressmap_impl(const char *address, const char *name,
  941. const char *exitname,
  942. int ttl)
  943. {
  944. /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
  945. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  946. /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
  947. char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  948. tor_assert(address);
  949. tor_assert(name);
  950. if (ttl<0)
  951. ttl = DEFAULT_DNS_TTL;
  952. else
  953. ttl = dns_clip_ttl(ttl);
  954. if (exitname) {
  955. /* XXXX fails to ever get attempts to get an exit address of
  956. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  957. * won't make strict RFC952-compliant applications (like us) barf. */
  958. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  959. "%s.%s.exit", address, exitname);
  960. tor_snprintf(extendedval, sizeof(extendedval),
  961. "%s.%s.exit", name, exitname);
  962. } else {
  963. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  964. "%s", address);
  965. tor_snprintf(extendedval, sizeof(extendedval),
  966. "%s", name);
  967. }
  968. addressmap_register(extendedaddress, tor_strdup(extendedval),
  969. time(NULL) + ttl, ADDRMAPSRC_DNS);
  970. }
  971. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  972. * We can now use this in subsequent streams via addressmap_rewrite()
  973. * so we can more correctly choose an exit that will allow <b>address</b>.
  974. *
  975. * If <b>exitname</b> is defined, then append the addresses with
  976. * ".exitname.exit" before registering the mapping.
  977. *
  978. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  979. * <b>ttl</b>seconds; otherwise, we use the default.
  980. */
  981. void
  982. client_dns_set_addressmap(const char *address, uint32_t val,
  983. const char *exitname,
  984. int ttl)
  985. {
  986. struct in_addr in;
  987. char valbuf[INET_NTOA_BUF_LEN];
  988. tor_assert(address);
  989. if (tor_inet_aton(address, &in))
  990. return; /* If address was an IP address already, don't add a mapping. */
  991. in.s_addr = htonl(val);
  992. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  993. client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
  994. }
  995. /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
  996. * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
  997. *
  998. * If <b>exitname</b> is defined, then append the addresses with
  999. * ".exitname.exit" before registering the mapping.
  1000. *
  1001. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  1002. * <b>ttl</b>seconds; otherwise, we use the default.
  1003. */
  1004. static void
  1005. client_dns_set_reverse_addressmap(const char *address, const char *v,
  1006. const char *exitname,
  1007. int ttl)
  1008. {
  1009. size_t len = strlen(address) + 16;
  1010. char *s = tor_malloc(len);
  1011. tor_snprintf(s, len, "REVERSE[%s]", address);
  1012. client_dns_set_addressmap_impl(s, v, exitname, ttl);
  1013. tor_free(s);
  1014. }
  1015. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  1016. * These addresses should map to localhost, so even if the
  1017. * application accidentally tried to connect to them directly (not
  1018. * via Tor), it wouldn't get too far astray.
  1019. *
  1020. * These options are configured by parse_virtual_addr_network().
  1021. */
  1022. /** Which network should we use for virtual IPv4 addresses? Only the first
  1023. * bits of this value are fixed. */
  1024. static uint32_t virtual_addr_network = 0x7fc00000u;
  1025. /** How many bits of <b>virtual_addr_network</b> are fixed? */
  1026. static maskbits_t virtual_addr_netmask_bits = 10;
  1027. /** What's the next virtual address we will hand out? */
  1028. static uint32_t next_virtual_addr = 0x7fc00000u;
  1029. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  1030. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  1031. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  1032. * string and return -1 on failure. If validate_only is false, sets the
  1033. * actual virtual address range to the parsed value. */
  1034. int
  1035. parse_virtual_addr_network(const char *val, int validate_only,
  1036. char **msg)
  1037. {
  1038. uint32_t addr;
  1039. uint16_t port_min, port_max;
  1040. maskbits_t bits;
  1041. if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
  1042. if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
  1043. return -1;
  1044. }
  1045. if (port_min != 1 || port_max != 65535) {
  1046. if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
  1047. return -1;
  1048. }
  1049. if (bits > 16) {
  1050. if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
  1051. "network or larger");
  1052. return -1;
  1053. }
  1054. if (validate_only)
  1055. return 0;
  1056. virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
  1057. virtual_addr_netmask_bits = bits;
  1058. if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
  1059. next_virtual_addr = addr;
  1060. return 0;
  1061. }
  1062. /**
  1063. * Return true iff <b>addr</b> is likely to have been returned by
  1064. * client_dns_get_unused_address.
  1065. **/
  1066. static int
  1067. address_is_in_virtual_range(const char *address)
  1068. {
  1069. struct in_addr in;
  1070. tor_assert(address);
  1071. if (!strcasecmpend(address, ".virtual")) {
  1072. return 1;
  1073. } else if (tor_inet_aton(address, &in)) {
  1074. uint32_t addr = ntohl(in.s_addr);
  1075. if (!addr_mask_cmp_bits(addr, virtual_addr_network,
  1076. virtual_addr_netmask_bits))
  1077. return 1;
  1078. }
  1079. return 0;
  1080. }
  1081. /** Return a newly allocated string holding an address of <b>type</b>
  1082. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  1083. * and that is very unlikely to be the address of any real host.
  1084. *
  1085. * May return NULL if we have run out of virtual addresses.
  1086. */
  1087. static char *
  1088. addressmap_get_virtual_address(int type)
  1089. {
  1090. char buf[64];
  1091. tor_assert(addressmap);
  1092. if (type == RESOLVED_TYPE_HOSTNAME) {
  1093. char rand[10];
  1094. do {
  1095. crypto_rand(rand, sizeof(rand));
  1096. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  1097. strlcat(buf, ".virtual", sizeof(buf));
  1098. } while (strmap_get(addressmap, buf));
  1099. return tor_strdup(buf);
  1100. } else if (type == RESOLVED_TYPE_IPV4) {
  1101. // This is an imperfect estimate of how many addresses are available, but
  1102. // that's ok.
  1103. struct in_addr in;
  1104. uint32_t available = 1u << (32-virtual_addr_netmask_bits);
  1105. while (available) {
  1106. /* Don't hand out any .0 or .255 address. */
  1107. while ((next_virtual_addr & 0xff) == 0 ||
  1108. (next_virtual_addr & 0xff) == 0xff) {
  1109. ++next_virtual_addr;
  1110. if (! --available) {
  1111. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  1112. return NULL;
  1113. }
  1114. }
  1115. in.s_addr = htonl(next_virtual_addr);
  1116. tor_inet_ntoa(&in, buf, sizeof(buf));
  1117. if (!strmap_get(addressmap, buf)) {
  1118. ++next_virtual_addr;
  1119. break;
  1120. }
  1121. ++next_virtual_addr;
  1122. --available;
  1123. log_info(LD_CONFIG, "%d addrs available", (int)available);
  1124. if (! available) {
  1125. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  1126. return NULL;
  1127. }
  1128. if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
  1129. virtual_addr_netmask_bits))
  1130. next_virtual_addr = virtual_addr_network;
  1131. }
  1132. return tor_strdup(buf);
  1133. } else {
  1134. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  1135. return NULL;
  1136. }
  1137. }
  1138. /** A controller has requested that we map some address of type
  1139. * <b>type</b> to the address <b>new_address</b>. Choose an address
  1140. * that is unlikely to be used, and map it, and return it in a newly
  1141. * allocated string. If another address of the same type is already
  1142. * mapped to <b>new_address</b>, try to return a copy of that address.
  1143. *
  1144. * The string in <b>new_address</b> may be freed or inserted into a map
  1145. * as appropriate. May return NULL if are out of virtual addresses.
  1146. **/
  1147. const char *
  1148. addressmap_register_virtual_address(int type, char *new_address)
  1149. {
  1150. char **addrp;
  1151. virtaddress_entry_t *vent;
  1152. int vent_needs_to_be_added = 0;
  1153. tor_assert(new_address);
  1154. tor_assert(addressmap);
  1155. tor_assert(virtaddress_reversemap);
  1156. vent = strmap_get(virtaddress_reversemap, new_address);
  1157. if (!vent) {
  1158. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  1159. vent_needs_to_be_added = 1;
  1160. }
  1161. addrp = (type == RESOLVED_TYPE_IPV4) ?
  1162. &vent->ipv4_address : &vent->hostname_address;
  1163. if (*addrp) {
  1164. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  1165. if (ent && ent->new_address &&
  1166. !strcasecmp(new_address, ent->new_address)) {
  1167. tor_free(new_address);
  1168. tor_assert(!vent_needs_to_be_added);
  1169. return tor_strdup(*addrp);
  1170. } else
  1171. log_warn(LD_BUG,
  1172. "Internal confusion: I thought that '%s' was mapped to by "
  1173. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  1174. safe_str_client(new_address),
  1175. safe_str_client(*addrp),
  1176. safe_str_client(*addrp),
  1177. ent?safe_str_client(ent->new_address):"(nothing)");
  1178. }
  1179. tor_free(*addrp);
  1180. *addrp = addressmap_get_virtual_address(type);
  1181. if (!*addrp) {
  1182. tor_free(vent);
  1183. tor_free(new_address);
  1184. return NULL;
  1185. }
  1186. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  1187. if (vent_needs_to_be_added)
  1188. strmap_set(virtaddress_reversemap, new_address, vent);
  1189. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
  1190. #if 0
  1191. {
  1192. /* Try to catch possible bugs */
  1193. addressmap_entry_t *ent;
  1194. ent = strmap_get(addressmap, *addrp);
  1195. tor_assert(ent);
  1196. tor_assert(!strcasecmp(ent->new_address,new_address));
  1197. vent = strmap_get(virtaddress_reversemap, new_address);
  1198. tor_assert(vent);
  1199. tor_assert(!strcasecmp(*addrp,
  1200. (type == RESOLVED_TYPE_IPV4) ?
  1201. vent->ipv4_address : vent->hostname_address));
  1202. log_info(LD_APP, "Map from %s to %s okay.",
  1203. safe_str_client(*addrp),
  1204. safe_str_client(new_address));
  1205. }
  1206. #endif
  1207. return *addrp;
  1208. }
  1209. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  1210. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  1211. * should be true if we're using this address as a client; false if we're
  1212. * using it as a server.
  1213. */
  1214. int
  1215. address_is_invalid_destination(const char *address, int client)
  1216. {
  1217. if (client) {
  1218. if (get_options()->AllowNonRFC953Hostnames)
  1219. return 0;
  1220. } else {
  1221. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  1222. return 0;
  1223. }
  1224. while (*address) {
  1225. if (TOR_ISALNUM(*address) ||
  1226. *address == '-' ||
  1227. *address == '.' ||
  1228. *address == '_') /* Underscore is not allowed, but Windows does it
  1229. * sometimes, just to thumb its nose at the IETF. */
  1230. ++address;
  1231. else
  1232. return 1;
  1233. }
  1234. return 0;
  1235. }
  1236. /** Iterate over all address mappings which have expiry times between
  1237. * min_expires and max_expires, inclusive. If sl is provided, add an
  1238. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  1239. * the expiry time if want_expiry is false. If sl is NULL, remove the
  1240. * mappings.
  1241. */
  1242. void
  1243. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  1244. time_t max_expires, int want_expiry)
  1245. {
  1246. strmap_iter_t *iter;
  1247. const char *key;
  1248. void *_val;
  1249. addressmap_entry_t *val;
  1250. if (!addressmap)
  1251. addressmap_init();
  1252. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  1253. strmap_iter_get(iter, &key, &_val);
  1254. val = _val;
  1255. if (val->expires >= min_expires && val->expires <= max_expires) {
  1256. if (!sl) {
  1257. iter = strmap_iter_next_rmv(addressmap,iter);
  1258. addressmap_ent_remove(key, val);
  1259. continue;
  1260. } else if (val->new_address) {
  1261. size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
  1262. char *line = tor_malloc(len);
  1263. if (want_expiry) {
  1264. if (val->expires < 3 || val->expires == TIME_MAX)
  1265. tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
  1266. else {
  1267. char time[ISO_TIME_LEN+1];
  1268. format_iso_time(time, val->expires);
  1269. tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
  1270. time);
  1271. }
  1272. } else {
  1273. tor_snprintf(line, len, "%s %s", key, val->new_address);
  1274. }
  1275. smartlist_add(sl, line);
  1276. }
  1277. }
  1278. iter = strmap_iter_next(addressmap,iter);
  1279. }
  1280. }
  1281. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  1282. * reject depending on our config options. */
  1283. static int
  1284. consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
  1285. {
  1286. or_options_t *options = get_options();
  1287. int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
  1288. if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
  1289. log_warn(LD_APP, "Application request to port %d: this port is "
  1290. "commonly used for unencrypted protocols. Please make sure "
  1291. "you don't send anything you would mind the rest of the "
  1292. "Internet reading!%s", port, reject ? " Closing." : "");
  1293. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  1294. port, reject ? "REJECT" : "WARN");
  1295. }
  1296. if (reject) {
  1297. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  1298. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1299. return -1;
  1300. }
  1301. return 0;
  1302. }
  1303. /** How many times do we try connecting with an exit configured via
  1304. * TrackHostExits before concluding that it won't work any more and trying a
  1305. * different one? */
  1306. #define TRACKHOSTEXITS_RETRIES 5
  1307. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  1308. * asked us to leave streams unattached. Return 0 in that case.
  1309. *
  1310. * See connection_ap_handshake_rewrite_and_attach()'s
  1311. * documentation for arguments and return value.
  1312. */
  1313. int
  1314. connection_ap_rewrite_and_attach_if_allowed(edge_connection_t *conn,
  1315. origin_circuit_t *circ,
  1316. crypt_path_t *cpath)
  1317. {
  1318. or_options_t *options = get_options();
  1319. if (options->LeaveStreamsUnattached) {
  1320. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1321. return 0;
  1322. }
  1323. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  1324. }
  1325. /** Connection <b>conn</b> just finished its socks handshake, or the
  1326. * controller asked us to take care of it. If <b>circ</b> is defined,
  1327. * then that's where we'll want to attach it. Otherwise we have to
  1328. * figure it out ourselves.
  1329. *
  1330. * First, parse whether it's a .exit address, remap it, and so on. Then
  1331. * if it's for a general circuit, try to attach it to a circuit (or launch
  1332. * one as needed), else if it's for a rendezvous circuit, fetch a
  1333. * rendezvous descriptor first (or attach/launch a circuit if the
  1334. * rendezvous descriptor is already here and fresh enough).
  1335. *
  1336. * The stream will exit from the hop
  1337. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1338. * <b>cpath</b> is NULL.
  1339. */
  1340. int
  1341. connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
  1342. origin_circuit_t *circ,
  1343. crypt_path_t *cpath)
  1344. {
  1345. socks_request_t *socks = conn->socks_request;
  1346. hostname_type_t addresstype;
  1347. or_options_t *options = get_options();
  1348. struct in_addr addr_tmp;
  1349. int automap = 0;
  1350. char orig_address[MAX_SOCKS_ADDR_LEN];
  1351. time_t map_expires = TIME_MAX;
  1352. int remapped_to_exit = 0;
  1353. time_t now = time(NULL);
  1354. tor_strlower(socks->address); /* normalize it */
  1355. strlcpy(orig_address, socks->address, sizeof(orig_address));
  1356. log_debug(LD_APP,"Client asked for %s:%d",
  1357. safe_str_client(socks->address),
  1358. socks->port);
  1359. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1360. !tor_inet_aton(socks->address, &addr_tmp) &&
  1361. options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
  1362. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
  1363. if (!strcasecmpend(socks->address, cp)) {
  1364. automap = 1;
  1365. break;
  1366. });
  1367. if (automap) {
  1368. const char *new_addr;
  1369. new_addr = addressmap_register_virtual_address(
  1370. RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
  1371. if (! new_addr) {
  1372. log_warn(LD_APP, "Unable to automap address %s",
  1373. escaped_safe_str(socks->address));
  1374. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1375. return -1;
  1376. }
  1377. log_info(LD_APP, "Automapping %s to %s",
  1378. escaped_safe_str_client(socks->address),
  1379. safe_str_client(new_addr));
  1380. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1381. }
  1382. }
  1383. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1384. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1385. &map_expires)) {
  1386. char *result = tor_strdup(socks->address);
  1387. /* remember _what_ is supposed to have been resolved. */
  1388. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1389. orig_address);
  1390. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1391. strlen(result), (uint8_t*)result,
  1392. -1,
  1393. map_expires);
  1394. connection_mark_unattached_ap(conn,
  1395. END_STREAM_REASON_DONE |
  1396. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1397. return 0;
  1398. }
  1399. if (options->ClientDNSRejectInternalAddresses) {
  1400. /* Don't let people try to do a reverse lookup on 10.0.0.1. */
  1401. tor_addr_t addr;
  1402. int ok;
  1403. ok = tor_addr_parse_reverse_lookup_name(
  1404. &addr, socks->address, AF_UNSPEC, 1);
  1405. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1406. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1407. 0, NULL, -1, TIME_MAX);
  1408. connection_mark_unattached_ap(conn,
  1409. END_STREAM_REASON_SOCKSPROTOCOL |
  1410. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1411. return -1;
  1412. }
  1413. }
  1414. } else if (!automap) {
  1415. int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
  1416. /* For address map controls, remap the address. */
  1417. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1418. &map_expires)) {
  1419. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1420. REMAP_STREAM_SOURCE_CACHE);
  1421. if (started_without_chosen_exit &&
  1422. !strcasecmpend(socks->address, ".exit") &&
  1423. map_expires < TIME_MAX)
  1424. remapped_to_exit = 1;
  1425. }
  1426. }
  1427. if (!automap && address_is_in_virtual_range(socks->address)) {
  1428. /* This address was probably handed out by client_dns_get_unmapped_address,
  1429. * but the mapping was discarded for some reason. We *don't* want to send
  1430. * the address through Tor; that's likely to fail, and may leak
  1431. * information.
  1432. */
  1433. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1434. safe_str_client(socks->address));
  1435. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1436. return -1;
  1437. }
  1438. /* Parse the address provided by SOCKS. Modify it in-place if it
  1439. * specifies a hidden-service (.onion) or particular exit node (.exit).
  1440. */
  1441. addresstype = parse_extended_hostname(socks->address,
  1442. remapped_to_exit || options->AllowDotExit);
  1443. if (addresstype == BAD_HOSTNAME) {
  1444. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  1445. safe_str_client(socks->address));
  1446. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1447. escaped(socks->address));
  1448. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1449. return -1;
  1450. }
  1451. if (addresstype == EXIT_HOSTNAME) {
  1452. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  1453. * node, and conn->address to hold only the address portion. */
  1454. char *s = strrchr(socks->address,'.');
  1455. tor_assert(!automap);
  1456. if (s) {
  1457. if (s[1] != '\0') {
  1458. conn->chosen_exit_name = tor_strdup(s+1);
  1459. if (remapped_to_exit) /* 5 tries before it expires the addressmap */
  1460. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1461. *s = 0;
  1462. } else {
  1463. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1464. safe_str_client(socks->address));
  1465. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1466. escaped(socks->address));
  1467. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1468. return -1;
  1469. }
  1470. } else {
  1471. const node_t *r;
  1472. conn->chosen_exit_name = tor_strdup(socks->address);
  1473. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1474. *socks->address = 0;
  1475. if (r) {
  1476. node_get_address_string(r, socks->address, sizeof(socks->address));
  1477. } else {
  1478. log_warn(LD_APP,
  1479. "Unrecognized server in exit address '%s.exit'. Refusing.",
  1480. safe_str_client(socks->address));
  1481. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1482. return -1;
  1483. }
  1484. }
  1485. }
  1486. if (addresstype != ONION_HOSTNAME) {
  1487. /* not a hidden-service request (i.e. normal or .exit) */
  1488. if (address_is_invalid_destination(socks->address, 1)) {
  1489. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1490. escaped(socks->address));
  1491. log_warn(LD_APP,
  1492. "Destination '%s' seems to be an invalid hostname. Failing.",
  1493. safe_str_client(socks->address));
  1494. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1495. return -1;
  1496. }
  1497. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1498. uint32_t answer;
  1499. struct in_addr in;
  1500. /* Reply to resolves immediately if we can. */
  1501. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  1502. /* leave it in network order */
  1503. answer = in.s_addr;
  1504. /* remember _what_ is supposed to have been resolved. */
  1505. strlcpy(socks->address, orig_address, sizeof(socks->address));
  1506. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  1507. (uint8_t*)&answer,
  1508. -1,map_expires);
  1509. connection_mark_unattached_ap(conn,
  1510. END_STREAM_REASON_DONE |
  1511. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1512. return 0;
  1513. }
  1514. tor_assert(!automap);
  1515. rep_hist_note_used_resolve(now); /* help predict this next time */
  1516. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1517. tor_assert(!automap);
  1518. if (socks->port == 0) {
  1519. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1520. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1521. return -1;
  1522. }
  1523. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1524. /* see if we can find a suitable enclave exit */
  1525. const node_t *r =
  1526. router_find_exact_exit_enclave(socks->address, socks->port);
  1527. if (r) {
  1528. log_info(LD_APP,
  1529. "Redirecting address %s to exit at enclave router %s",
  1530. safe_str_client(socks->address), node_get_nickname(r));
  1531. /* use the hex digest, not nickname, in case there are two
  1532. routers with this nickname */
  1533. conn->chosen_exit_name =
  1534. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  1535. conn->chosen_exit_optional = 1;
  1536. }
  1537. }
  1538. /* warn or reject if it's using a dangerous port */
  1539. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  1540. if (consider_plaintext_ports(conn, socks->port) < 0)
  1541. return -1;
  1542. if (!conn->use_begindir) {
  1543. /* help predict this next time */
  1544. rep_hist_note_used_port(now, socks->port);
  1545. }
  1546. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1547. rep_hist_note_used_resolve(now); /* help predict this next time */
  1548. /* no extra processing needed */
  1549. } else {
  1550. tor_fragile_assert();
  1551. }
  1552. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1553. if ((circ && connection_ap_handshake_attach_chosen_circuit(
  1554. conn, circ, cpath) < 0) ||
  1555. (!circ &&
  1556. connection_ap_handshake_attach_circuit(conn) < 0)) {
  1557. if (!conn->_base.marked_for_close)
  1558. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1559. return -1;
  1560. }
  1561. return 0;
  1562. } else {
  1563. /* it's a hidden-service request */
  1564. rend_cache_entry_t *entry;
  1565. int r;
  1566. rend_service_authorization_t *client_auth;
  1567. tor_assert(!automap);
  1568. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1569. /* if it's a resolve request, fail it right now, rather than
  1570. * building all the circuits and then realizing it won't work. */
  1571. log_warn(LD_APP,
  1572. "Resolve requests to hidden services not allowed. Failing.");
  1573. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1574. 0,NULL,-1,TIME_MAX);
  1575. connection_mark_unattached_ap(conn,
  1576. END_STREAM_REASON_SOCKSPROTOCOL |
  1577. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1578. return -1;
  1579. }
  1580. if (circ) {
  1581. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1582. "supported for .onion addresses currently. Failing.");
  1583. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1584. return -1;
  1585. }
  1586. conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1587. strlcpy(conn->rend_data->onion_address, socks->address,
  1588. sizeof(conn->rend_data->onion_address));
  1589. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1590. safe_str_client(conn->rend_data->onion_address));
  1591. /* see if we already have it cached */
  1592. r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
  1593. if (r<0) {
  1594. log_warn(LD_BUG,"Invalid service name '%s'",
  1595. safe_str_client(conn->rend_data->onion_address));
  1596. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1597. return -1;
  1598. }
  1599. /* Help predict this next time. We're not sure if it will need
  1600. * a stable circuit yet, but we know we'll need *something*. */
  1601. rep_hist_note_used_internal(now, 0, 1);
  1602. /* Look up if we have client authorization for it. */
  1603. client_auth = rend_client_lookup_service_authorization(
  1604. conn->rend_data->onion_address);
  1605. if (client_auth) {
  1606. log_info(LD_REND, "Using previously configured client authorization "
  1607. "for hidden service request.");
  1608. memcpy(conn->rend_data->descriptor_cookie,
  1609. client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1610. conn->rend_data->auth_type = client_auth->auth_type;
  1611. }
  1612. if (r==0) {
  1613. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1614. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1615. safe_str_client(conn->rend_data->onion_address));
  1616. rend_client_refetch_v2_renddesc(conn->rend_data);
  1617. } else { /* r > 0 */
  1618. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1619. log_info(LD_REND, "Descriptor is here. Great.");
  1620. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1621. if (!conn->_base.marked_for_close)
  1622. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1623. return -1;
  1624. }
  1625. }
  1626. return 0;
  1627. }
  1628. return 0; /* unreached but keeps the compiler happy */
  1629. }
  1630. #ifdef TRANS_PF
  1631. static int pf_socket = -1;
  1632. int
  1633. get_pf_socket(void)
  1634. {
  1635. int pf;
  1636. /* This should be opened before dropping privileges. */
  1637. if (pf_socket >= 0)
  1638. return pf_socket;
  1639. #ifdef OPENBSD
  1640. /* only works on OpenBSD */
  1641. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  1642. #else
  1643. /* works on NetBSD and FreeBSD */
  1644. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  1645. #endif
  1646. if (pf < 0) {
  1647. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1648. return -1;
  1649. }
  1650. pf_socket = pf;
  1651. return pf_socket;
  1652. }
  1653. #endif
  1654. /** Fetch the original destination address and port from a
  1655. * system-specific interface and put them into a
  1656. * socks_request_t as if they came from a socks request.
  1657. *
  1658. * Return -1 if an error prevents fetching the destination,
  1659. * else return 0.
  1660. */
  1661. static int
  1662. connection_ap_get_original_destination(edge_connection_t *conn,
  1663. socks_request_t *req)
  1664. {
  1665. #ifdef TRANS_NETFILTER
  1666. /* Linux 2.4+ */
  1667. struct sockaddr_storage orig_dst;
  1668. socklen_t orig_dst_len = sizeof(orig_dst);
  1669. tor_addr_t addr;
  1670. if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
  1671. (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
  1672. int e = tor_socket_errno(conn->_base.s);
  1673. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1674. return -1;
  1675. }
  1676. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  1677. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1678. return 0;
  1679. #elif defined(TRANS_PF)
  1680. struct sockaddr_storage proxy_addr;
  1681. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1682. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  1683. struct pfioc_natlook pnl;
  1684. tor_addr_t addr;
  1685. int pf = -1;
  1686. if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
  1687. &proxy_addr_len) < 0) {
  1688. int e = tor_socket_errno(conn->_base.s);
  1689. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1690. "failed: %s", tor_socket_strerror(e));
  1691. return -1;
  1692. }
  1693. memset(&pnl, 0, sizeof(pnl));
  1694. pnl.proto = IPPROTO_TCP;
  1695. pnl.direction = PF_OUT;
  1696. if (proxy_sa->sa_family == AF_INET) {
  1697. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  1698. pnl.af = AF_INET;
  1699. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
  1700. pnl.sport = htons(conn->_base.port);
  1701. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  1702. pnl.dport = sin->sin_port;
  1703. } else if (proxy_sa->sa_family == AF_INET6) {
  1704. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  1705. pnl.af = AF_INET6;
  1706. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
  1707. sizeof(struct in6_addr));
  1708. pnl.sport = htons(conn->_base.port);
  1709. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  1710. pnl.dport = sin6->sin6_port;
  1711. } else {
  1712. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  1713. (int)proxy_sa->sa_family);
  1714. return -1;
  1715. }
  1716. pf = get_pf_socket();
  1717. if (pf<0)
  1718. return -1;
  1719. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1720. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1721. return -1;
  1722. }
  1723. if (pnl.af == AF_INET) {
  1724. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  1725. } else if (pnl.af == AF_INET6) {
  1726. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  1727. } else {
  1728. tor_fragile_assert();
  1729. return -1;
  1730. }
  1731. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1732. req->port = ntohs(pnl.rdport);
  1733. return 0;
  1734. #else
  1735. (void)conn;
  1736. (void)req;
  1737. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1738. "transparent proxy method was configured.");
  1739. return -1;
  1740. #endif
  1741. }
  1742. /** connection_edge_process_inbuf() found a conn in state
  1743. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1744. * the socks handshake.
  1745. *
  1746. * If the handshake is complete, send it to
  1747. * connection_ap_handshake_rewrite_and_attach().
  1748. *
  1749. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  1750. * else return 0.
  1751. */
  1752. static int
  1753. connection_ap_handshake_process_socks(edge_connection_t *conn)
  1754. {
  1755. socks_request_t *socks;
  1756. int sockshere;
  1757. or_options_t *options = get_options();
  1758. tor_assert(conn);
  1759. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1760. tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
  1761. tor_assert(conn->socks_request);
  1762. socks = conn->socks_request;
  1763. log_debug(LD_APP,"entered.");
  1764. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1765. struct evbuffer *input = bufferevent_get_input(conn->_base.bufev);
  1766. sockshere = fetch_from_evbuffer_socks(input, socks,
  1767. options->TestSocks, options->SafeSocks);
  1768. }) ELSE_IF_NO_BUFFEREVENT {
  1769. sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
  1770. options->TestSocks, options->SafeSocks);
  1771. };
  1772. if (sockshere == 0) {
  1773. if (socks->replylen) {
  1774. connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
  1775. /* zero it out so we can do another round of negotiation */
  1776. socks->replylen = 0;
  1777. } else {
  1778. log_debug(LD_APP,"socks handshake not all here yet.");
  1779. }
  1780. return 0;
  1781. } else if (sockshere == -1) {
  1782. if (socks->replylen) { /* we should send reply back */
  1783. log_debug(LD_APP,"reply is already set for us. Using it.");
  1784. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
  1785. END_STREAM_REASON_SOCKSPROTOCOL);
  1786. } else {
  1787. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1788. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1789. END_STREAM_REASON_SOCKSPROTOCOL);
  1790. }
  1791. connection_mark_unattached_ap(conn,
  1792. END_STREAM_REASON_SOCKSPROTOCOL |
  1793. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1794. return -1;
  1795. } /* else socks handshake is done, continue processing */
  1796. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  1797. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1798. else
  1799. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  1800. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1801. }
  1802. /** connection_init_accepted_conn() found a new trans AP conn.
  1803. * Get the original destination and send it to
  1804. * connection_ap_handshake_rewrite_and_attach().
  1805. *
  1806. * Return -1 if an unexpected error with conn (and it should be marked
  1807. * for close), else return 0.
  1808. */
  1809. int
  1810. connection_ap_process_transparent(edge_connection_t *conn)
  1811. {
  1812. socks_request_t *socks;
  1813. tor_assert(conn);
  1814. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1815. tor_assert(conn->socks_request);
  1816. socks = conn->socks_request;
  1817. /* pretend that a socks handshake completed so we don't try to
  1818. * send a socks reply down a transparent conn */
  1819. socks->command = SOCKS_COMMAND_CONNECT;
  1820. socks->has_finished = 1;
  1821. log_debug(LD_APP,"entered.");
  1822. if (connection_ap_get_original_destination(conn, socks) < 0) {
  1823. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  1824. connection_mark_unattached_ap(conn,
  1825. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  1826. return -1;
  1827. }
  1828. /* we have the original destination */
  1829. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1830. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1831. }
  1832. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  1833. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  1834. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  1835. * form of the original destination.
  1836. *
  1837. * If the original destination is complete, send it to
  1838. * connection_ap_handshake_rewrite_and_attach().
  1839. *
  1840. * Return -1 if an unexpected error with conn (and it should be marked
  1841. * for close), else return 0.
  1842. */
  1843. static int
  1844. connection_ap_process_natd(edge_connection_t *conn)
  1845. {
  1846. char tmp_buf[36], *tbuf, *daddr;
  1847. size_t tlen = 30;
  1848. int err, port_ok;
  1849. socks_request_t *socks;
  1850. tor_assert(conn);
  1851. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1852. tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
  1853. tor_assert(conn->socks_request);
  1854. socks = conn->socks_request;
  1855. log_debug(LD_APP,"entered.");
  1856. /* look for LF-terminated "[DEST ip_addr port]"
  1857. * where ip_addr is a dotted-quad and port is in string form */
  1858. err = connection_fetch_from_buf_line(TO_CONN(conn), tmp_buf, &tlen);
  1859. if (err == 0)
  1860. return 0;
  1861. if (err < 0) {
  1862. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  1863. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1864. return -1;
  1865. }
  1866. if (strcmpstart(tmp_buf, "[DEST ")) {
  1867. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1868. "said: %s",
  1869. escaped(tmp_buf));
  1870. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1871. return -1;
  1872. }
  1873. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  1874. if (!(tbuf = strchr(tbuf, ' '))) {
  1875. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1876. "said: %s",
  1877. escaped(tmp_buf));
  1878. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1879. return -1;
  1880. }
  1881. *tbuf++ = '\0';
  1882. /* pretend that a socks handshake completed so we don't try to
  1883. * send a socks reply down a natd conn */
  1884. strlcpy(socks->address, daddr, sizeof(socks->address));
  1885. socks->port = (uint16_t)
  1886. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  1887. if (!port_ok) {
  1888. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  1889. "of range.", escaped(tbuf));
  1890. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1891. return -1;
  1892. }
  1893. socks->command = SOCKS_COMMAND_CONNECT;
  1894. socks->has_finished = 1;
  1895. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1896. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1897. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1898. }
  1899. /** Iterate over the two bytes of stream_id until we get one that is not
  1900. * already in use; return it. Return 0 if can't get a unique stream_id.
  1901. */
  1902. static streamid_t
  1903. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  1904. {
  1905. edge_connection_t *tmpconn;
  1906. streamid_t test_stream_id;
  1907. uint32_t attempts=0;
  1908. again:
  1909. test_stream_id = circ->next_stream_id++;
  1910. if (++attempts > 1<<16) {
  1911. /* Make sure we don't loop forever if all stream_id's are used. */
  1912. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1913. return 0;
  1914. }
  1915. if (test_stream_id == 0)
  1916. goto again;
  1917. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1918. if (tmpconn->stream_id == test_stream_id)
  1919. goto again;
  1920. return test_stream_id;
  1921. }
  1922. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1923. * socks_request field, and send it down circ.
  1924. *
  1925. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1926. */
  1927. int
  1928. connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
  1929. {
  1930. char payload[CELL_PAYLOAD_SIZE];
  1931. int payload_len;
  1932. int begin_type;
  1933. origin_circuit_t *circ;
  1934. tor_assert(ap_conn->on_circuit);
  1935. circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
  1936. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1937. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1938. tor_assert(ap_conn->socks_request);
  1939. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  1940. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1941. if (ap_conn->stream_id==0) {
  1942. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1943. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1944. return -1;
  1945. }
  1946. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1947. (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1948. ap_conn->socks_request->address : "",
  1949. ap_conn->socks_request->port);
  1950. payload_len = (int)strlen(payload)+1;
  1951. log_info(LD_APP,
  1952. "Sending relay cell %d to begin stream %d.",
  1953. (int)ap_conn->use_begindir,
  1954. ap_conn->stream_id);
  1955. begin_type = ap_conn->use_begindir ?
  1956. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  1957. if (begin_type == RELAY_COMMAND_BEGIN) {
  1958. tor_assert(circ->build_state->onehop_tunnel == 0);
  1959. }
  1960. if (connection_edge_send_command(ap_conn, begin_type,
  1961. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  1962. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  1963. return -1; /* circuit is closed, don't continue */
  1964. ap_conn->package_window = STREAMWINDOW_START;
  1965. ap_conn->deliver_window = STREAMWINDOW_START;
  1966. ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
  1967. log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
  1968. ap_conn->_base.s, circ->_base.n_circ_id);
  1969. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  1970. return 0;
  1971. }
  1972. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1973. * socks_request field, and send it down circ.
  1974. *
  1975. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1976. */
  1977. int
  1978. connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
  1979. {
  1980. int payload_len, command;
  1981. const char *string_addr;
  1982. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  1983. origin_circuit_t *circ;
  1984. tor_assert(ap_conn->on_circuit);
  1985. circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
  1986. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1987. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1988. tor_assert(ap_conn->socks_request);
  1989. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1990. command = ap_conn->socks_request->command;
  1991. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  1992. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1993. if (ap_conn->stream_id==0) {
  1994. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1995. /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
  1996. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1997. return -1;
  1998. }
  1999. if (command == SOCKS_COMMAND_RESOLVE) {
  2000. string_addr = ap_conn->socks_request->address;
  2001. payload_len = (int)strlen(string_addr)+1;
  2002. } else {
  2003. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2004. const char *a = ap_conn->socks_request->address;
  2005. tor_addr_t addr;
  2006. int r;
  2007. /* We're doing a reverse lookup. The input could be an IP address, or
  2008. * could be an .in-addr.arpa or .ip6.arpa address */
  2009. r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
  2010. if (r <= 0) {
  2011. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2012. safe_str_client(a));
  2013. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2014. return -1;
  2015. }
  2016. r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2017. if (r < 0) {
  2018. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2019. safe_str_client(a));
  2020. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2021. return -1;
  2022. }
  2023. string_addr = inaddr_buf;
  2024. payload_len = (int)strlen(inaddr_buf)+1;
  2025. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2026. }
  2027. log_debug(LD_APP,
  2028. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  2029. if (connection_edge_send_command(ap_conn,
  2030. RELAY_COMMAND_RESOLVE,
  2031. string_addr, payload_len) < 0)
  2032. return -1; /* circuit is closed, don't continue */
  2033. tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
  2034. ap_conn->_base.address = tor_strdup("(Tor_internal)");
  2035. ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
  2036. log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
  2037. ap_conn->_base.s, circ->_base.n_circ_id);
  2038. control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
  2039. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2040. return 0;
  2041. }
  2042. /** Make an AP connection_t, make a new linked connection pair, and attach
  2043. * one side to the conn, connection_add it, initialize it to circuit_wait,
  2044. * and call connection_ap_handshake_attach_circuit(conn) on it.
  2045. *
  2046. * Return the other end of the linked connection pair, or -1 if error.
  2047. * DOCDOC partner.
  2048. */
  2049. edge_connection_t *
  2050. connection_ap_make_link(connection_t *partner,
  2051. char *address, uint16_t port,
  2052. const char *digest, int use_begindir, int want_onehop)
  2053. {
  2054. edge_connection_t *conn;
  2055. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2056. want_onehop ? "direct" : "anonymized",
  2057. safe_str_client(address), port);
  2058. conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
  2059. conn->_base.linked = 1; /* so that we can add it safely below. */
  2060. /* populate conn->socks_request */
  2061. /* leave version at zero, so the socks_reply is empty */
  2062. conn->socks_request->socks_version = 0;
  2063. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2064. strlcpy(conn->socks_request->address, address,
  2065. sizeof(conn->socks_request->address));
  2066. conn->socks_request->port = port;
  2067. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2068. conn->want_onehop = want_onehop;
  2069. conn->use_begindir = use_begindir;
  2070. if (use_begindir) {
  2071. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2072. conn->chosen_exit_name[0] = '$';
  2073. tor_assert(digest);
  2074. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2075. digest, DIGEST_LEN);
  2076. }
  2077. conn->_base.address = tor_strdup("(Tor_internal)");
  2078. tor_addr_make_unspec(&conn->_base.addr);
  2079. conn->_base.port = 0;
  2080. connection_link_connections(partner, TO_CONN(conn));
  2081. if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
  2082. connection_free(TO_CONN(conn));
  2083. return NULL;
  2084. }
  2085. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  2086. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2087. /* attaching to a dirty circuit is fine */
  2088. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  2089. if (!conn->_base.marked_for_close)
  2090. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2091. return NULL;
  2092. }
  2093. log_info(LD_APP,"... application connection created and linked.");
  2094. return conn;
  2095. }
  2096. /** Notify any interested controller connections about a new hostname resolve
  2097. * or resolve error. Takes the same arguments as does
  2098. * connection_ap_handshake_socks_resolved(). */
  2099. static void
  2100. tell_controller_about_resolved_result(edge_connection_t *conn,
  2101. int answer_type,
  2102. size_t answer_len,
  2103. const char *answer,
  2104. int ttl,
  2105. time_t expires)
  2106. {
  2107. if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
  2108. answer_type == RESOLVED_TYPE_HOSTNAME)) {
  2109. return; /* we already told the controller. */
  2110. } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  2111. char *cp = tor_dup_ip(get_uint32(answer));
  2112. control_event_address_mapped(conn->socks_request->address,
  2113. cp, expires, NULL);
  2114. tor_free(cp);
  2115. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2116. char *cp = tor_strndup(answer, answer_len);
  2117. control_event_address_mapped(conn->socks_request->address,
  2118. cp, expires, NULL);
  2119. tor_free(cp);
  2120. } else {
  2121. control_event_address_mapped(conn->socks_request->address,
  2122. "<error>",
  2123. time(NULL)+ttl,
  2124. "error=yes");
  2125. }
  2126. }
  2127. /** Send an answer to an AP connection that has requested a DNS lookup via
  2128. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  2129. * for unreachable; the answer should be in the format specified in the socks
  2130. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  2131. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  2132. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  2133. **/
  2134. /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
  2135. * interface and those that use it less ugly. */
  2136. void
  2137. connection_ap_handshake_socks_resolved(edge_connection_t *conn,
  2138. int answer_type,
  2139. size_t answer_len,
  2140. const uint8_t *answer,
  2141. int ttl,
  2142. time_t expires)
  2143. {
  2144. char buf[384];
  2145. size_t replylen;
  2146. if (ttl >= 0) {
  2147. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2148. uint32_t a = ntohl(get_uint32(answer));
  2149. if (a)
  2150. client_dns_set_addressmap(conn->socks_request->address, a,
  2151. conn->chosen_exit_name, ttl);
  2152. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2153. char *cp = tor_strndup((char*)answer, answer_len);
  2154. client_dns_set_reverse_addressmap(conn->socks_request->address,
  2155. cp,
  2156. conn->chosen_exit_name, ttl);
  2157. tor_free(cp);
  2158. }
  2159. }
  2160. if (conn->is_dns_request) {
  2161. if (conn->dns_server_request) {
  2162. /* We had a request on our DNS port: answer it. */
  2163. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  2164. conn->socks_request->has_finished = 1;
  2165. return;
  2166. } else {
  2167. /* This must be a request from the controller. We already sent
  2168. * a mapaddress if there's a ttl. */
  2169. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  2170. (char*)answer, ttl, expires);
  2171. conn->socks_request->has_finished = 1;
  2172. return;
  2173. }
  2174. /* We shouldn't need to free conn here; it gets marked by the caller. */
  2175. }
  2176. if (conn->socks_request->socks_version == 4) {
  2177. buf[0] = 0x00; /* version */
  2178. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2179. buf[1] = SOCKS4_GRANTED;
  2180. set_uint16(buf+2, 0);
  2181. memcpy(buf+4, answer, 4); /* address */
  2182. replylen = SOCKS4_NETWORK_LEN;
  2183. } else { /* "error" */
  2184. buf[1] = SOCKS4_REJECT;
  2185. memset(buf+2, 0, 6);
  2186. replylen = SOCKS4_NETWORK_LEN;
  2187. }
  2188. } else if (conn->socks_request->socks_version == 5) {
  2189. /* SOCKS5 */
  2190. buf[0] = 0x05; /* version */
  2191. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2192. buf[1] = SOCKS5_SUCCEEDED;
  2193. buf[2] = 0; /* reserved */
  2194. buf[3] = 0x01; /* IPv4 address type */
  2195. memcpy(buf+4, answer, 4); /* address */
  2196. set_uint16(buf+8, 0); /* port == 0. */
  2197. replylen = 10;
  2198. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2199. buf[1] = SOCKS5_SUCCEEDED;
  2200. buf[2] = 0; /* reserved */
  2201. buf[3] = 0x04; /* IPv6 address type */
  2202. memcpy(buf+4, answer, 16); /* address */
  2203. set_uint16(buf+20, 0); /* port == 0. */
  2204. replylen = 22;
  2205. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2206. buf[1] = SOCKS5_SUCCEEDED;
  2207. buf[2] = 0; /* reserved */
  2208. buf[3] = 0x03; /* Domainname address type */
  2209. buf[4] = (char)answer_len;
  2210. memcpy(buf+5, answer, answer_len); /* address */
  2211. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  2212. replylen = 5+answer_len+2;
  2213. } else {
  2214. buf[1] = SOCKS5_HOST_UNREACHABLE;
  2215. memset(buf+2, 0, 8);
  2216. replylen = 10;
  2217. }
  2218. } else {
  2219. /* no socks version info; don't send anything back */
  2220. return;
  2221. }
  2222. connection_ap_handshake_socks_reply(conn, buf, replylen,
  2223. (answer_type == RESOLVED_TYPE_IPV4 ||
  2224. answer_type == RESOLVED_TYPE_IPV6) ?
  2225. 0 : END_STREAM_REASON_RESOLVEFAILED);
  2226. }
  2227. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  2228. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  2229. * handshaking.
  2230. *
  2231. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  2232. * and return, else reply based on <b>endreason</b> (one of
  2233. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  2234. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  2235. */
  2236. void
  2237. connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
  2238. size_t replylen, int endreason)
  2239. {
  2240. char buf[256];
  2241. socks5_reply_status_t status =
  2242. stream_end_reason_to_socks5_response(endreason);
  2243. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  2244. control_event_stream_status(conn,
  2245. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  2246. endreason);
  2247. if (conn->socks_request->has_finished) {
  2248. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  2249. "connection_ap_handshake_socks_reply.");
  2250. return;
  2251. }
  2252. if (replylen) { /* we already have a reply in mind */
  2253. connection_write_to_buf(reply, replylen, TO_CONN(conn));
  2254. conn->socks_request->has_finished = 1;
  2255. return;
  2256. }
  2257. if (conn->socks_request->socks_version == 4) {
  2258. memset(buf,0,SOCKS4_NETWORK_LEN);
  2259. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  2260. /* leave version, destport, destip zero */
  2261. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
  2262. } else if (conn->socks_request->socks_version == 5) {
  2263. buf[0] = 5; /* version 5 */
  2264. buf[1] = (char)status;
  2265. buf[2] = 0;
  2266. buf[3] = 1; /* ipv4 addr */
  2267. memset(buf+4,0,6); /* Set external addr/port to 0.
  2268. The spec doesn't seem to say what to do here. -RD */
  2269. connection_write_to_buf(buf,10,TO_CONN(conn));
  2270. }
  2271. /* If socks_version isn't 4 or 5, don't send anything.
  2272. * This can happen in the case of AP bridges. */
  2273. conn->socks_request->has_finished = 1;
  2274. return;
  2275. }
  2276. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  2277. * an exit hop for the circuit, or we are the origin and it is a
  2278. * rendezvous begin.
  2279. *
  2280. * Launch a new exit connection and initialize things appropriately.
  2281. *
  2282. * If it's a rendezvous stream, call connection_exit_connect() on
  2283. * it.
  2284. *
  2285. * For general streams, call dns_resolve() on it first, and only call
  2286. * connection_exit_connect() if the dns answer is already known.
  2287. *
  2288. * Note that we don't call connection_add() on the new stream! We wait
  2289. * for connection_exit_connect() to do that.
  2290. *
  2291. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  2292. * Else return 0.
  2293. */
  2294. int
  2295. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  2296. {
  2297. edge_connection_t *n_stream;
  2298. relay_header_t rh;
  2299. char *address=NULL;
  2300. uint16_t port;
  2301. or_circuit_t *or_circ = NULL;
  2302. or_options_t *options = get_options();
  2303. assert_circuit_ok(circ);
  2304. if (!CIRCUIT_IS_ORIGIN(circ))
  2305. or_circ = TO_OR_CIRCUIT(circ);
  2306. relay_header_unpack(&rh, cell->payload);
  2307. if (rh.length > RELAY_PAYLOAD_SIZE)
  2308. return -1;
  2309. /* Note: we have to use relay_send_command_from_edge here, not
  2310. * connection_edge_end or connection_edge_send_command, since those require
  2311. * that we have a stream connected to a circuit, and we don't connect to a
  2312. * circuit until we have a pending/successful resolve. */
  2313. if (!server_mode(options) &&
  2314. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  2315. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2316. "Relay begin cell at non-server. Closing.");
  2317. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2318. END_STREAM_REASON_EXITPOLICY, NULL);
  2319. return 0;
  2320. }
  2321. if (rh.command == RELAY_COMMAND_BEGIN) {
  2322. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  2323. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2324. "Relay begin cell has no \\0. Closing.");
  2325. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2326. END_STREAM_REASON_TORPROTOCOL, NULL);
  2327. return 0;
  2328. }
  2329. if (parse_addr_port(LOG_PROTOCOL_WARN,
  2330. (char*)(cell->payload+RELAY_HEADER_SIZE),
  2331. &address,NULL,&port)<0) {
  2332. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2333. "Unable to parse addr:port in relay begin cell. Closing.");
  2334. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2335. END_STREAM_REASON_TORPROTOCOL, NULL);
  2336. return 0;
  2337. }
  2338. if (port==0) {
  2339. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2340. "Missing port in relay begin cell. Closing.");
  2341. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2342. END_STREAM_REASON_TORPROTOCOL, NULL);
  2343. tor_free(address);
  2344. return 0;
  2345. }
  2346. if (or_circ && or_circ->p_conn && !options->AllowSingleHopExits &&
  2347. (or_circ->is_first_hop ||
  2348. (!connection_or_digest_is_known_relay(
  2349. or_circ->p_conn->identity_digest) &&
  2350. should_refuse_unknown_exits(options)))) {
  2351. /* Don't let clients use us as a single-hop proxy, unless the user
  2352. * has explicitly allowed that in the config. It attracts attackers
  2353. * and users who'd be better off with, well, single-hop proxies.
  2354. */
  2355. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2356. "Attempt by %s to open a stream %s. Closing.",
  2357. safe_str(or_circ->p_conn->_base.address),
  2358. or_circ->is_first_hop ? "on first hop of circuit" :
  2359. "from unknown relay");
  2360. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2361. or_circ->is_first_hop ?
  2362. END_STREAM_REASON_TORPROTOCOL :
  2363. END_STREAM_REASON_MISC,
  2364. NULL);
  2365. tor_free(address);
  2366. return 0;
  2367. }
  2368. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2369. if (!directory_permits_begindir_requests(options) ||
  2370. circ->purpose != CIRCUIT_PURPOSE_OR) {
  2371. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2372. END_STREAM_REASON_NOTDIRECTORY, NULL);
  2373. return 0;
  2374. }
  2375. /* Make sure to get the 'real' address of the previous hop: the
  2376. * caller might want to know whether his IP address has changed, and
  2377. * we might already have corrected _base.addr[ess] for the relay's
  2378. * canonical IP address. */
  2379. if (or_circ && or_circ->p_conn)
  2380. address = tor_dup_addr(&or_circ->p_conn->real_addr);
  2381. else
  2382. address = tor_strdup("127.0.0.1");
  2383. port = 1; /* XXXX This value is never actually used anywhere, and there
  2384. * isn't "really" a connection here. But we
  2385. * need to set it to something nonzero. */
  2386. } else {
  2387. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2388. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2389. END_STREAM_REASON_INTERNAL, NULL);
  2390. return 0;
  2391. }
  2392. log_debug(LD_EXIT,"Creating new exit connection.");
  2393. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2394. /* Remember the tunneled request ID in the new edge connection, so that
  2395. * we can measure download times. */
  2396. TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
  2397. n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
  2398. n_stream->stream_id = rh.stream_id;
  2399. n_stream->_base.port = port;
  2400. /* leave n_stream->s at -1, because it's not yet valid */
  2401. n_stream->package_window = STREAMWINDOW_START;
  2402. n_stream->deliver_window = STREAMWINDOW_START;
  2403. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  2404. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2405. log_info(LD_REND,"begin is for rendezvous. configuring stream.");
  2406. n_stream->_base.address = tor_strdup("(rendezvous)");
  2407. n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
  2408. n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
  2409. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  2410. assert_circuit_ok(circ);
  2411. if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
  2412. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  2413. n_stream->_base.port);
  2414. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2415. END_STREAM_REASON_EXITPOLICY,
  2416. origin_circ->cpath->prev);
  2417. connection_free(TO_CONN(n_stream));
  2418. tor_free(address);
  2419. return 0;
  2420. }
  2421. assert_circuit_ok(circ);
  2422. log_debug(LD_REND,"Finished assigning addr/port");
  2423. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  2424. /* add it into the linked list of p_streams on this circuit */
  2425. n_stream->next_stream = origin_circ->p_streams;
  2426. n_stream->on_circuit = circ;
  2427. origin_circ->p_streams = n_stream;
  2428. assert_circuit_ok(circ);
  2429. connection_exit_connect(n_stream);
  2430. tor_free(address);
  2431. return 0;
  2432. }
  2433. tor_strlower(address);
  2434. n_stream->_base.address = address;
  2435. n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2436. /* default to failed, change in dns_resolve if it turns out not to fail */
  2437. if (we_are_hibernating()) {
  2438. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2439. END_STREAM_REASON_HIBERNATING, NULL);
  2440. connection_free(TO_CONN(n_stream));
  2441. return 0;
  2442. }
  2443. n_stream->on_circuit = circ;
  2444. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2445. tor_assert(or_circ);
  2446. if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
  2447. tor_addr_copy(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
  2448. return connection_exit_connect_dir(n_stream);
  2449. }
  2450. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2451. /* send it off to the gethostbyname farm */
  2452. switch (dns_resolve(n_stream)) {
  2453. case 1: /* resolve worked; now n_stream is attached to circ. */
  2454. assert_circuit_ok(circ);
  2455. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2456. connection_exit_connect(n_stream);
  2457. return 0;
  2458. case -1: /* resolve failed */
  2459. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2460. END_STREAM_REASON_RESOLVEFAILED, NULL);
  2461. /* n_stream got freed. don't touch it. */
  2462. break;
  2463. case 0: /* resolve added to pending list */
  2464. assert_circuit_ok(circ);
  2465. break;
  2466. }
  2467. return 0;
  2468. }
  2469. /**
  2470. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  2471. * circuit <b>circ</b>;
  2472. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2473. */
  2474. int
  2475. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2476. {
  2477. edge_connection_t *dummy_conn;
  2478. relay_header_t rh;
  2479. assert_circuit_ok(TO_CIRCUIT(circ));
  2480. relay_header_unpack(&rh, cell->payload);
  2481. if (rh.length > RELAY_PAYLOAD_SIZE)
  2482. return -1;
  2483. /* This 'dummy_conn' only exists to remember the stream ID
  2484. * associated with the resolve request; and to make the
  2485. * implementation of dns.c more uniform. (We really only need to
  2486. * remember the circuit, the stream ID, and the hostname to be
  2487. * resolved; but if we didn't store them in a connection like this,
  2488. * the housekeeping in dns.c would get way more complicated.)
  2489. */
  2490. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2491. dummy_conn->stream_id = rh.stream_id;
  2492. dummy_conn->_base.address = tor_strndup(
  2493. (char*)cell->payload+RELAY_HEADER_SIZE,
  2494. rh.length);
  2495. dummy_conn->_base.port = 0;
  2496. dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2497. dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
  2498. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2499. /* send it off to the gethostbyname farm */
  2500. switch (dns_resolve(dummy_conn)) {
  2501. case -1: /* Impossible to resolve; a resolved cell was sent. */
  2502. /* Connection freed; don't touch it. */
  2503. return 0;
  2504. case 1: /* The result was cached; a resolved cell was sent. */
  2505. if (!dummy_conn->_base.marked_for_close)
  2506. connection_free(TO_CONN(dummy_conn));
  2507. return 0;
  2508. case 0: /* resolve added to pending list */
  2509. assert_circuit_ok(TO_CIRCUIT(circ));
  2510. break;
  2511. }
  2512. return 0;
  2513. }
  2514. /** Connect to conn's specified addr and port. If it worked, conn
  2515. * has now been added to the connection_array.
  2516. *
  2517. * Send back a connected cell. Include the resolved IP of the destination
  2518. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  2519. * streams must not reveal what IP they connected to.)
  2520. */
  2521. void
  2522. connection_exit_connect(edge_connection_t *edge_conn)
  2523. {
  2524. const tor_addr_t *addr;
  2525. uint16_t port;
  2526. connection_t *conn = TO_CONN(edge_conn);
  2527. int socket_error = 0;
  2528. if (!connection_edge_is_rendezvous_stream(edge_conn) &&
  2529. router_compare_to_my_exit_policy(edge_conn)) {
  2530. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  2531. escaped_safe_str_client(conn->address), conn->port);
  2532. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  2533. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2534. connection_free(conn);
  2535. return;
  2536. }
  2537. addr = &conn->addr;
  2538. port = conn->port;
  2539. log_debug(LD_EXIT,"about to try connecting");
  2540. switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
  2541. case -1:
  2542. /* XXX021 use socket_error below rather than trying to piece things
  2543. * together from the current errno, which may have been clobbered. */
  2544. connection_edge_end_errno(edge_conn);
  2545. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2546. connection_free(conn);
  2547. return;
  2548. case 0:
  2549. conn->state = EXIT_CONN_STATE_CONNECTING;
  2550. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  2551. /* writable indicates finish;
  2552. * readable/error indicates broken link in windows-land. */
  2553. return;
  2554. /* case 1: fall through */
  2555. }
  2556. conn->state = EXIT_CONN_STATE_OPEN;
  2557. if (connection_get_outbuf_len(conn)) {
  2558. /* in case there are any queued data cells */
  2559. log_warn(LD_BUG,"newly connected conn had data waiting!");
  2560. // connection_start_writing(conn);
  2561. }
  2562. IF_HAS_NO_BUFFEREVENT(conn)
  2563. connection_watch_events(conn, READ_EVENT);
  2564. /* also, deliver a 'connected' cell back through the circuit. */
  2565. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2566. /* rendezvous stream */
  2567. /* don't send an address back! */
  2568. connection_edge_send_command(edge_conn,
  2569. RELAY_COMMAND_CONNECTED,
  2570. NULL, 0);
  2571. } else { /* normal stream */
  2572. char connected_payload[20];
  2573. int connected_payload_len;
  2574. if (tor_addr_family(&conn->addr) == AF_INET) {
  2575. set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
  2576. connected_payload_len = 4;
  2577. } else {
  2578. memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
  2579. connected_payload_len = 16;
  2580. }
  2581. set_uint32(connected_payload+connected_payload_len,
  2582. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  2583. connected_payload_len += 4;
  2584. connection_edge_send_command(edge_conn,
  2585. RELAY_COMMAND_CONNECTED,
  2586. connected_payload, connected_payload_len);
  2587. }
  2588. }
  2589. /** Given an exit conn that should attach to us as a directory server, open a
  2590. * bridge connection with a linked connection pair, create a new directory
  2591. * conn, and join them together. Return 0 on success (or if there was an
  2592. * error we could send back an end cell for). Return -(some circuit end
  2593. * reason) if the circuit needs to be torn down. Either connects
  2594. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  2595. */
  2596. static int
  2597. connection_exit_connect_dir(edge_connection_t *exitconn)
  2598. {
  2599. dir_connection_t *dirconn = NULL;
  2600. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  2601. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  2602. exitconn->_base.state = EXIT_CONN_STATE_OPEN;
  2603. dirconn = dir_connection_new(AF_INET);
  2604. tor_addr_copy(&dirconn->_base.addr, &exitconn->_base.addr);
  2605. dirconn->_base.port = 0;
  2606. dirconn->_base.address = tor_strdup(exitconn->_base.address);
  2607. dirconn->_base.type = CONN_TYPE_DIR;
  2608. dirconn->_base.purpose = DIR_PURPOSE_SERVER;
  2609. dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2610. /* Note that the new dir conn belongs to the same tunneled request as
  2611. * the edge conn, so that we can measure download times. */
  2612. TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
  2613. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  2614. if (connection_add(TO_CONN(exitconn))<0) {
  2615. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2616. connection_free(TO_CONN(exitconn));
  2617. connection_free(TO_CONN(dirconn));
  2618. return 0;
  2619. }
  2620. /* link exitconn to circ, now that we know we can use it. */
  2621. exitconn->next_stream = circ->n_streams;
  2622. circ->n_streams = exitconn;
  2623. if (connection_add(TO_CONN(dirconn))<0) {
  2624. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2625. connection_close_immediate(TO_CONN(exitconn));
  2626. connection_mark_for_close(TO_CONN(exitconn));
  2627. connection_free(TO_CONN(dirconn));
  2628. return 0;
  2629. }
  2630. connection_start_reading(TO_CONN(dirconn));
  2631. connection_start_reading(TO_CONN(exitconn));
  2632. if (connection_edge_send_command(exitconn,
  2633. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  2634. connection_mark_for_close(TO_CONN(exitconn));
  2635. connection_mark_for_close(TO_CONN(dirconn));
  2636. return 0;
  2637. }
  2638. return 0;
  2639. }
  2640. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2641. * it is a general stream.
  2642. */
  2643. int
  2644. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2645. {
  2646. tor_assert(conn);
  2647. if (conn->rend_data)
  2648. return 1;
  2649. return 0;
  2650. }
  2651. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2652. * to exit from it, or 0 if it probably will not allow it.
  2653. * (We might be uncertain if conn's destination address has not yet been
  2654. * resolved.)
  2655. *
  2656. * If <b>excluded_means_no</b> is 1 and Exclude*Nodes is set and excludes
  2657. * this relay, return 0.
  2658. */
  2659. int
  2660. connection_ap_can_use_exit(edge_connection_t *conn, const node_t *exit,
  2661. int excluded_means_no)
  2662. {
  2663. or_options_t *options = get_options();
  2664. tor_assert(conn);
  2665. tor_assert(conn->_base.type == CONN_TYPE_AP);
  2666. tor_assert(conn->socks_request);
  2667. tor_assert(exit);
  2668. /* If a particular exit node has been requested for the new connection,
  2669. * make sure the exit node of the existing circuit matches exactly.
  2670. */
  2671. if (conn->chosen_exit_name) {
  2672. const node_t *chosen_exit =
  2673. node_get_by_nickname(conn->chosen_exit_name, 1);
  2674. if (!chosen_exit || memcmp(chosen_exit->identity,
  2675. exit->identity, DIGEST_LEN)) {
  2676. /* doesn't match */
  2677. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2678. // conn->chosen_exit_name, exit->nickname);
  2679. return 0;
  2680. }
  2681. }
  2682. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  2683. !conn->use_begindir) {
  2684. struct in_addr in;
  2685. uint32_t addr = 0;
  2686. addr_policy_result_t r;
  2687. if (tor_inet_aton(conn->socks_request->address, &in))
  2688. addr = ntohl(in.s_addr);
  2689. r = compare_addr_to_node_policy(addr, conn->socks_request->port, exit);
  2690. if (r == ADDR_POLICY_REJECTED)
  2691. return 0; /* We know the address, and the exit policy rejects it. */
  2692. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  2693. return 0; /* We don't know the addr, but the exit policy rejects most
  2694. * addresses with this port. Since the user didn't ask for
  2695. * this node, err on the side of caution. */
  2696. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2697. /* Don't send DNS requests to non-exit servers by default. */
  2698. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
  2699. return 0;
  2700. }
  2701. if (options->_ExcludeExitNodesUnion &&
  2702. (options->StrictNodes || excluded_means_no) &&
  2703. routerset_contains_node(options->_ExcludeExitNodesUnion, exit)) {
  2704. /* If we are trying to avoid this node as exit, and we have StrictNodes
  2705. * set, then this is not a suitable exit. Refuse it.
  2706. *
  2707. * If we don't have StrictNodes set, then this function gets called in
  2708. * two contexts. First, we've got a circuit open and we want to know
  2709. * whether we can use it. In that case, we somehow built this circuit
  2710. * despite having the last hop in ExcludeExitNodes, so we should be
  2711. * willing to use it. Second, we are evaluating whether this is an
  2712. * acceptable exit for a new circuit. In that case, skip it. */
  2713. return 0;
  2714. }
  2715. return 1;
  2716. }
  2717. /** If address is of the form "y.onion" with a well-formed handle y:
  2718. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2719. *
  2720. * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
  2721. * Put a NUL after y and return EXIT_HOSTNAME.
  2722. *
  2723. * Otherwise:
  2724. * Return NORMAL_HOSTNAME and change nothing.
  2725. */
  2726. hostname_type_t
  2727. parse_extended_hostname(char *address, int allowdotexit)
  2728. {
  2729. char *s;
  2730. char query[REND_SERVICE_ID_LEN_BASE32+1];
  2731. s = strrchr(address,'.');
  2732. if (!s)
  2733. return NORMAL_HOSTNAME; /* no dot, thus normal */
  2734. if (!strcmp(s+1,"exit")) {
  2735. if (allowdotexit) {
  2736. *s = 0; /* NUL-terminate it */
  2737. return EXIT_HOSTNAME; /* .exit */
  2738. } else {
  2739. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  2740. "security risks. Set AllowDotExit in your torrc to enable "
  2741. "it.");
  2742. /* FFFF send a controller event too to notify Vidalia users */
  2743. return BAD_HOSTNAME;
  2744. }
  2745. }
  2746. if (strcmp(s+1,"onion"))
  2747. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  2748. /* so it is .onion */
  2749. *s = 0; /* NUL-terminate it */
  2750. if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
  2751. REND_SERVICE_ID_LEN_BASE32+1)
  2752. goto failed;
  2753. if (rend_valid_service_id(query)) {
  2754. return ONION_HOSTNAME; /* success */
  2755. }
  2756. failed:
  2757. /* otherwise, return to previous state and return 0 */
  2758. *s = '.';
  2759. return BAD_HOSTNAME;
  2760. }