connection_edge.c 109 KB

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