connection_edge.c 105 KB

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