connection_edge.c 109 KB

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