connection_edge.c 106 KB

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