connection_edge.c 104 KB

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