connection_edge.c 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460
  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-2015, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. **/
  10. #define CONNECTION_EDGE_PRIVATE
  11. #include "or.h"
  12. #include "addressmap.h"
  13. #include "buffers.h"
  14. #include "channel.h"
  15. #include "circpathbias.h"
  16. #include "circuitlist.h"
  17. #include "circuituse.h"
  18. #include "config.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "dns.h"
  24. #include "dnsserv.h"
  25. #include "dirserv.h"
  26. #include "hibernate.h"
  27. #include "main.h"
  28. #include "nodelist.h"
  29. #include "policies.h"
  30. #include "reasons.h"
  31. #include "relay.h"
  32. #include "rendclient.h"
  33. #include "rendcommon.h"
  34. #include "rendservice.h"
  35. #include "rephist.h"
  36. #include "router.h"
  37. #include "routerlist.h"
  38. #include "routerset.h"
  39. #include "circuitbuild.h"
  40. #ifdef HAVE_LINUX_TYPES_H
  41. #include <linux/types.h>
  42. #endif
  43. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  44. #include <linux/netfilter_ipv4.h>
  45. #define TRANS_NETFILTER
  46. #define TRANS_NETFILTER_IPV4
  47. #endif
  48. #ifdef HAVE_LINUX_IF_H
  49. #include <linux/if.h>
  50. #endif
  51. #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
  52. #include <linux/netfilter_ipv6/ip6_tables.h>
  53. #if defined(IP6T_SO_ORIGINAL_DST)
  54. #define TRANS_NETFILTER
  55. #define TRANS_NETFILTER_IPV6
  56. #endif
  57. #endif
  58. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  59. #include <net/if.h>
  60. #include <net/pfvar.h>
  61. #define TRANS_PF
  62. #endif
  63. #ifdef IP_TRANSPARENT
  64. #define TRANS_TPROXY
  65. #endif
  66. #define SOCKS4_GRANTED 90
  67. #define SOCKS4_REJECT 91
  68. static int connection_ap_handshake_process_socks(entry_connection_t *conn);
  69. static int connection_ap_process_natd(entry_connection_t *conn);
  70. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  71. static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
  72. static int connection_ap_supports_optimistic_data(const entry_connection_t *);
  73. /** An AP stream has failed/finished. If it hasn't already sent back
  74. * a socks reply, send one now (based on endreason). Also set
  75. * has_sent_end to 1, and mark the conn.
  76. */
  77. MOCK_IMPL(void,
  78. connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
  79. int line, const char *file))
  80. {
  81. connection_t *base_conn = ENTRY_TO_CONN(conn);
  82. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  83. tor_assert(base_conn->type == CONN_TYPE_AP);
  84. ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
  85. /* If this is a rendezvous stream and it is failing without ever
  86. * being attached to a circuit, assume that an attempt to connect to
  87. * the destination hidden service has just ended.
  88. *
  89. * XXXX This condition doesn't limit to only streams failing
  90. * without ever being attached. That sloppiness should be harmless,
  91. * but we should fix it someday anyway. */
  92. if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
  93. connection_edge_is_rendezvous_stream(edge_conn)) {
  94. rend_client_note_connection_attempt_ended(
  95. edge_conn->rend_data->onion_address);
  96. }
  97. if (base_conn->marked_for_close) {
  98. /* This call will warn as appropriate. */
  99. connection_mark_for_close_(base_conn, line, file);
  100. return;
  101. }
  102. if (!conn->socks_request->has_finished) {
  103. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  104. log_warn(LD_BUG,
  105. "stream (marked at %s:%d) sending two socks replies?",
  106. file, line);
  107. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  108. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  109. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  110. connection_ap_handshake_socks_resolved(conn,
  111. RESOLVED_TYPE_ERROR_TRANSIENT,
  112. 0, NULL, -1, -1);
  113. else /* unknown or no handshake at all. send no response. */
  114. conn->socks_request->has_finished = 1;
  115. }
  116. connection_mark_and_flush_(base_conn, line, file);
  117. ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
  118. }
  119. /** There was an EOF. Send an end and mark the connection for close.
  120. */
  121. int
  122. connection_edge_reached_eof(edge_connection_t *conn)
  123. {
  124. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  125. connection_state_is_open(TO_CONN(conn))) {
  126. /* it still has stuff to process. don't let it die yet. */
  127. return 0;
  128. }
  129. log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
  130. conn->base_.s);
  131. if (!conn->base_.marked_for_close) {
  132. /* only mark it if not already marked. it's possible to
  133. * get the 'end' right around when the client hangs up on us. */
  134. connection_edge_end(conn, END_STREAM_REASON_DONE);
  135. if (conn->base_.type == CONN_TYPE_AP) {
  136. /* eof, so don't send a socks reply back */
  137. if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
  138. EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  139. }
  140. connection_mark_for_close(TO_CONN(conn));
  141. }
  142. return 0;
  143. }
  144. /** Handle new bytes on conn->inbuf based on state:
  145. * - If it's waiting for socks info, try to read another step of the
  146. * socks handshake out of conn->inbuf.
  147. * - If it's waiting for the original destination, fetch it.
  148. * - If it's open, then package more relay cells from the stream.
  149. * - Else, leave the bytes on inbuf alone for now.
  150. *
  151. * Mark and return -1 if there was an unexpected error with the conn,
  152. * else return 0.
  153. */
  154. int
  155. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  156. {
  157. tor_assert(conn);
  158. switch (conn->base_.state) {
  159. case AP_CONN_STATE_SOCKS_WAIT:
  160. if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
  161. /* already marked */
  162. return -1;
  163. }
  164. return 0;
  165. case AP_CONN_STATE_NATD_WAIT:
  166. if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  167. /* already marked */
  168. return -1;
  169. }
  170. return 0;
  171. case AP_CONN_STATE_OPEN:
  172. case EXIT_CONN_STATE_OPEN:
  173. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  174. /* (We already sent an end cell if possible) */
  175. connection_mark_for_close(TO_CONN(conn));
  176. return -1;
  177. }
  178. return 0;
  179. case AP_CONN_STATE_CONNECT_WAIT:
  180. if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
  181. log_info(LD_EDGE,
  182. "data from edge while in '%s' state. Sending it anyway. "
  183. "package_partial=%d, buflen=%ld",
  184. conn_state_to_string(conn->base_.type, conn->base_.state),
  185. package_partial,
  186. (long)connection_get_inbuf_len(TO_CONN(conn)));
  187. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
  188. /* (We already sent an end cell if possible) */
  189. connection_mark_for_close(TO_CONN(conn));
  190. return -1;
  191. }
  192. return 0;
  193. }
  194. /* Fall through if the connection is on a circuit without optimistic
  195. * data support. */
  196. case EXIT_CONN_STATE_CONNECTING:
  197. case AP_CONN_STATE_RENDDESC_WAIT:
  198. case AP_CONN_STATE_CIRCUIT_WAIT:
  199. case AP_CONN_STATE_RESOLVE_WAIT:
  200. case AP_CONN_STATE_CONTROLLER_WAIT:
  201. log_info(LD_EDGE,
  202. "data from edge while in '%s' state. Leaving it on buffer.",
  203. conn_state_to_string(conn->base_.type, conn->base_.state));
  204. return 0;
  205. }
  206. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
  207. tor_fragile_assert();
  208. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  209. connection_mark_for_close(TO_CONN(conn));
  210. return -1;
  211. }
  212. /** This edge needs to be closed, because its circuit has closed.
  213. * Mark it for close and return 0.
  214. */
  215. int
  216. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  217. {
  218. if (!conn->base_.marked_for_close) {
  219. log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
  220. (unsigned) circ_id);
  221. if (conn->base_.type == CONN_TYPE_AP) {
  222. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  223. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
  224. control_event_stream_bandwidth(conn);
  225. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  226. END_STREAM_REASON_DESTROY);
  227. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  228. } else {
  229. /* closing the circuit, nothing to send an END to */
  230. conn->edge_has_sent_end = 1;
  231. conn->end_reason = END_STREAM_REASON_DESTROY;
  232. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  233. connection_mark_and_flush(TO_CONN(conn));
  234. }
  235. }
  236. conn->cpath_layer = NULL;
  237. conn->on_circuit = NULL;
  238. return 0;
  239. }
  240. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  241. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  242. * is not a client connection, set the relay end cell's reason for closing
  243. * as <b>reason</b> */
  244. static int
  245. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  246. uint8_t reason, crypt_path_t *cpath_layer)
  247. {
  248. char payload[1];
  249. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  250. /* Never send the server an informative reason code; it doesn't need to
  251. * know why the client stream is failing. */
  252. reason = END_STREAM_REASON_MISC;
  253. }
  254. payload[0] = (char) reason;
  255. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  256. payload, 1, cpath_layer);
  257. }
  258. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  259. * remember that we've done so. If this is not a client connection, set the
  260. * relay end cell's reason for closing as <b>reason</b>.
  261. *
  262. * Return -1 if this function has already been called on this conn,
  263. * else return 0.
  264. */
  265. int
  266. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  267. {
  268. char payload[RELAY_PAYLOAD_SIZE];
  269. size_t payload_len=1;
  270. circuit_t *circ;
  271. uint8_t control_reason = reason;
  272. if (conn->edge_has_sent_end) {
  273. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  274. "on an already ended stream?", reason);
  275. tor_fragile_assert();
  276. return -1;
  277. }
  278. if (conn->base_.marked_for_close) {
  279. log_warn(LD_BUG,
  280. "called on conn that's already marked for close at %s:%d.",
  281. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  282. return 0;
  283. }
  284. circ = circuit_get_by_edge_conn(conn);
  285. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  286. /* If this is a client circuit, don't send the server an informative
  287. * reason code; it doesn't need to know why the client stream is
  288. * failing. */
  289. reason = END_STREAM_REASON_MISC;
  290. }
  291. payload[0] = (char)reason;
  292. if (reason == END_STREAM_REASON_EXITPOLICY &&
  293. !connection_edge_is_rendezvous_stream(conn)) {
  294. int addrlen;
  295. if (tor_addr_family(&conn->base_.addr) == AF_INET) {
  296. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
  297. addrlen = 4;
  298. } else {
  299. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
  300. addrlen = 16;
  301. }
  302. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  303. payload_len += 4+addrlen;
  304. }
  305. if (circ && !circ->marked_for_close) {
  306. log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
  307. conn->base_.s);
  308. connection_edge_send_command(conn, RELAY_COMMAND_END,
  309. payload, payload_len);
  310. } else {
  311. log_debug(LD_EDGE,"No circ to send end on conn "
  312. "(fd "TOR_SOCKET_T_FORMAT").",
  313. conn->base_.s);
  314. }
  315. conn->edge_has_sent_end = 1;
  316. conn->end_reason = control_reason;
  317. return 0;
  318. }
  319. /** An error has just occurred on an operation on an edge connection
  320. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  321. * appropriate relay end cell to the other end of the connection's circuit.
  322. **/
  323. int
  324. connection_edge_end_errno(edge_connection_t *conn)
  325. {
  326. uint8_t reason;
  327. tor_assert(conn);
  328. reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
  329. return connection_edge_end(conn, reason);
  330. }
  331. /** We just wrote some data to <b>conn</b>; act appropriately.
  332. *
  333. * (That is, if it's open, consider sending a stream-level sendme cell if we
  334. * have just flushed enough.)
  335. */
  336. int
  337. connection_edge_flushed_some(edge_connection_t *conn)
  338. {
  339. switch (conn->base_.state) {
  340. case AP_CONN_STATE_OPEN:
  341. case EXIT_CONN_STATE_OPEN:
  342. connection_edge_consider_sending_sendme(conn);
  343. break;
  344. }
  345. return 0;
  346. }
  347. /** Connection <b>conn</b> has finished writing and has no bytes left on
  348. * its outbuf.
  349. *
  350. * If it's in state 'open', stop writing, consider responding with a
  351. * sendme, and return.
  352. * Otherwise, stop writing and return.
  353. *
  354. * If <b>conn</b> is broken, mark it for close and return -1, else
  355. * return 0.
  356. */
  357. int
  358. connection_edge_finished_flushing(edge_connection_t *conn)
  359. {
  360. tor_assert(conn);
  361. switch (conn->base_.state) {
  362. case AP_CONN_STATE_OPEN:
  363. case EXIT_CONN_STATE_OPEN:
  364. connection_edge_consider_sending_sendme(conn);
  365. return 0;
  366. case AP_CONN_STATE_SOCKS_WAIT:
  367. case AP_CONN_STATE_NATD_WAIT:
  368. case AP_CONN_STATE_RENDDESC_WAIT:
  369. case AP_CONN_STATE_CIRCUIT_WAIT:
  370. case AP_CONN_STATE_CONNECT_WAIT:
  371. case AP_CONN_STATE_CONTROLLER_WAIT:
  372. case AP_CONN_STATE_RESOLVE_WAIT:
  373. return 0;
  374. default:
  375. log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
  376. tor_fragile_assert();
  377. return -1;
  378. }
  379. return 0;
  380. }
  381. /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
  382. * able to generate. */
  383. /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
  384. #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
  385. /** Set the buffer at <b>payload_out</b> -- which must have at least
  386. * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
  387. * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
  388. * that the name resolution that led us to <b>addr</b> will be valid for
  389. * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
  390. * success. */
  391. STATIC int
  392. connected_cell_format_payload(uint8_t *payload_out,
  393. const tor_addr_t *addr,
  394. uint32_t ttl)
  395. {
  396. const sa_family_t family = tor_addr_family(addr);
  397. int connected_payload_len;
  398. /* should be needless */
  399. memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
  400. if (family == AF_INET) {
  401. set_uint32(payload_out, tor_addr_to_ipv4n(addr));
  402. connected_payload_len = 4;
  403. } else if (family == AF_INET6) {
  404. set_uint32(payload_out, 0);
  405. set_uint8(payload_out + 4, 6);
  406. memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
  407. connected_payload_len = 21;
  408. } else {
  409. return -1;
  410. }
  411. set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
  412. connected_payload_len += 4;
  413. tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
  414. return connected_payload_len;
  415. }
  416. /** Connected handler for exit connections: start writing pending
  417. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  418. * any pending data that may have been received. */
  419. int
  420. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  421. {
  422. connection_t *conn;
  423. tor_assert(edge_conn);
  424. tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
  425. conn = TO_CONN(edge_conn);
  426. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  427. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  428. escaped_safe_str(conn->address), conn->port,
  429. safe_str(fmt_and_decorate_addr(&conn->addr)));
  430. rep_hist_note_exit_stream_opened(conn->port);
  431. conn->state = EXIT_CONN_STATE_OPEN;
  432. IF_HAS_NO_BUFFEREVENT(conn)
  433. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  434. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  435. * cells */
  436. connection_start_writing(conn);
  437. /* deliver a 'connected' relay cell back through the circuit. */
  438. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  439. if (connection_edge_send_command(edge_conn,
  440. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  441. return 0; /* circuit is closed, don't continue */
  442. } else {
  443. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  444. int connected_payload_len =
  445. connected_cell_format_payload(connected_payload, &conn->addr,
  446. edge_conn->address_ttl);
  447. if (connected_payload_len < 0)
  448. return -1;
  449. if (connection_edge_send_command(edge_conn,
  450. RELAY_COMMAND_CONNECTED,
  451. (char*)connected_payload, connected_payload_len) < 0)
  452. return 0; /* circuit is closed, don't continue */
  453. }
  454. tor_assert(edge_conn->package_window > 0);
  455. /* in case the server has written anything */
  456. return connection_edge_process_inbuf(edge_conn, 1);
  457. }
  458. /** Common code to connection_(ap|exit)_about_to_close. */
  459. static void
  460. connection_edge_about_to_close(edge_connection_t *edge_conn)
  461. {
  462. if (!edge_conn->edge_has_sent_end) {
  463. connection_t *conn = TO_CONN(edge_conn);
  464. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  465. "hasn't sent end yet?",
  466. conn->marked_for_close_file, conn->marked_for_close);
  467. tor_fragile_assert();
  468. }
  469. }
  470. /** Called when we're about to finally unlink and free an AP (client)
  471. * connection: perform necessary accounting and cleanup */
  472. void
  473. connection_ap_about_to_close(entry_connection_t *entry_conn)
  474. {
  475. circuit_t *circ;
  476. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  477. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  478. if (entry_conn->socks_request->has_finished == 0) {
  479. /* since conn gets removed right after this function finishes,
  480. * there's no point trying to send back a reply at this point. */
  481. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  482. " back a socks reply.",
  483. conn->marked_for_close_file, conn->marked_for_close);
  484. }
  485. if (!edge_conn->end_reason) {
  486. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  487. " set end_reason.",
  488. conn->marked_for_close_file, conn->marked_for_close);
  489. }
  490. if (entry_conn->dns_server_request) {
  491. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  492. " replied to DNS request.",
  493. conn->marked_for_close_file, conn->marked_for_close);
  494. dnsserv_reject_request(entry_conn);
  495. }
  496. control_event_stream_bandwidth(edge_conn);
  497. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  498. edge_conn->end_reason);
  499. circ = circuit_get_by_edge_conn(edge_conn);
  500. if (circ)
  501. circuit_detach_stream(circ, edge_conn);
  502. }
  503. /** Called when we're about to finally unlink and free an exit
  504. * connection: perform necessary accounting and cleanup */
  505. void
  506. connection_exit_about_to_close(edge_connection_t *edge_conn)
  507. {
  508. circuit_t *circ;
  509. connection_t *conn = TO_CONN(edge_conn);
  510. connection_edge_about_to_close(edge_conn);
  511. circ = circuit_get_by_edge_conn(edge_conn);
  512. if (circ)
  513. circuit_detach_stream(circ, edge_conn);
  514. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  515. connection_dns_remove(edge_conn);
  516. }
  517. }
  518. /** Define a schedule for how long to wait between retrying
  519. * application connections. Rather than waiting a fixed amount of
  520. * time between each retry, we wait 10 seconds each for the first
  521. * two tries, and 15 seconds for each retry after
  522. * that. Hopefully this will improve the expected user experience. */
  523. static int
  524. compute_retry_timeout(entry_connection_t *conn)
  525. {
  526. int timeout = get_options()->CircuitStreamTimeout;
  527. if (timeout) /* if our config options override the default, use them */
  528. return timeout;
  529. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  530. return 10;
  531. return 15;
  532. }
  533. /** Find all general-purpose AP streams waiting for a response that sent their
  534. * begin/resolve cell too long ago. Detach from their current circuit, and
  535. * mark their current circuit as unsuitable for new streams. Then call
  536. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  537. * available) or launch a new one.
  538. *
  539. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  540. * retry attempt).
  541. */
  542. void
  543. connection_ap_expire_beginning(void)
  544. {
  545. edge_connection_t *conn;
  546. entry_connection_t *entry_conn;
  547. circuit_t *circ;
  548. time_t now = time(NULL);
  549. const or_options_t *options = get_options();
  550. int severity;
  551. int cutoff;
  552. int seconds_idle, seconds_since_born;
  553. smartlist_t *conns = get_connection_array();
  554. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  555. if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
  556. continue;
  557. entry_conn = TO_ENTRY_CONN(base_conn);
  558. conn = ENTRY_TO_EDGE_CONN(entry_conn);
  559. /* if it's an internal linked connection, don't yell its status. */
  560. severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
  561. ? LOG_INFO : LOG_NOTICE;
  562. seconds_idle = (int)( now - base_conn->timestamp_lastread );
  563. seconds_since_born = (int)( now - base_conn->timestamp_created );
  564. if (base_conn->state == AP_CONN_STATE_OPEN)
  565. continue;
  566. /* We already consider SocksTimeout in
  567. * connection_ap_handshake_attach_circuit(), but we need to consider
  568. * it here too because controllers that put streams in controller_wait
  569. * state never ask Tor to attach the circuit. */
  570. if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
  571. if (seconds_since_born >= options->SocksTimeout) {
  572. log_fn(severity, LD_APP,
  573. "Tried for %d seconds to get a connection to %s:%d. "
  574. "Giving up. (%s)",
  575. seconds_since_born,
  576. safe_str_client(entry_conn->socks_request->address),
  577. entry_conn->socks_request->port,
  578. conn_state_to_string(CONN_TYPE_AP, base_conn->state));
  579. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  580. }
  581. continue;
  582. }
  583. /* We're in state connect_wait or resolve_wait now -- waiting for a
  584. * reply to our relay cell. See if we want to retry/give up. */
  585. cutoff = compute_retry_timeout(entry_conn);
  586. if (seconds_idle < cutoff)
  587. continue;
  588. circ = circuit_get_by_edge_conn(conn);
  589. if (!circ) { /* it's vanished? */
  590. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  591. safe_str_client(entry_conn->socks_request->address));
  592. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  593. continue;
  594. }
  595. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  596. if (seconds_idle >= options->SocksTimeout) {
  597. log_fn(severity, LD_REND,
  598. "Rend stream is %d seconds late. Giving up on address"
  599. " '%s.onion'.",
  600. seconds_idle,
  601. safe_str_client(entry_conn->socks_request->address));
  602. /* Roll back path bias use state so that we probe the circuit
  603. * if nothing else succeeds on it */
  604. pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
  605. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  606. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  607. }
  608. continue;
  609. }
  610. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  611. circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  612. circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  613. log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
  614. "The purpose on the circuit was %s; it was in state %s, "
  615. "path_state %s.",
  616. circuit_purpose_to_string(circ->purpose),
  617. circuit_state_to_string(circ->state),
  618. CIRCUIT_IS_ORIGIN(circ) ?
  619. pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
  620. "none");
  621. }
  622. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  623. "We tried for %d seconds to connect to '%s' using exit %s."
  624. " Retrying on a new circuit.",
  625. seconds_idle,
  626. safe_str_client(entry_conn->socks_request->address),
  627. conn->cpath_layer ?
  628. extend_info_describe(conn->cpath_layer->extend_info):
  629. "*unnamed*");
  630. /* send an end down the circuit */
  631. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  632. /* un-mark it as ending, since we're going to reuse it */
  633. conn->edge_has_sent_end = 0;
  634. conn->end_reason = 0;
  635. /* make us not try this circuit again, but allow
  636. * current streams on it to survive if they can */
  637. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  638. /* give our stream another 'cutoff' seconds to try */
  639. conn->base_.timestamp_lastread += cutoff;
  640. if (entry_conn->num_socks_retries < 250) /* avoid overflow */
  641. entry_conn->num_socks_retries++;
  642. /* move it back into 'pending' state, and try to attach. */
  643. if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
  644. END_STREAM_REASON_TIMEOUT)<0) {
  645. if (!base_conn->marked_for_close)
  646. connection_mark_unattached_ap(entry_conn,
  647. END_STREAM_REASON_CANT_ATTACH);
  648. }
  649. } SMARTLIST_FOREACH_END(base_conn);
  650. }
  651. /** Tell any AP streams that are waiting for a new circuit to try again,
  652. * either attaching to an available circ or launching a new one.
  653. */
  654. void
  655. connection_ap_attach_pending(void)
  656. {
  657. entry_connection_t *entry_conn;
  658. smartlist_t *conns = get_connection_array();
  659. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  660. if (conn->marked_for_close ||
  661. conn->type != CONN_TYPE_AP ||
  662. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  663. continue;
  664. entry_conn = TO_ENTRY_CONN(conn);
  665. if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
  666. if (!conn->marked_for_close)
  667. connection_mark_unattached_ap(entry_conn,
  668. END_STREAM_REASON_CANT_ATTACH);
  669. }
  670. } SMARTLIST_FOREACH_END(conn);
  671. }
  672. /** Tell any AP streams that are waiting for a one-hop tunnel to
  673. * <b>failed_digest</b> that they are going to fail. */
  674. /* XXX024 We should get rid of this function, and instead attach
  675. * one-hop streams to circ->p_streams so they get marked in
  676. * circuit_mark_for_close like normal p_streams. */
  677. void
  678. connection_ap_fail_onehop(const char *failed_digest,
  679. cpath_build_state_t *build_state)
  680. {
  681. entry_connection_t *entry_conn;
  682. char digest[DIGEST_LEN];
  683. smartlist_t *conns = get_connection_array();
  684. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  685. if (conn->marked_for_close ||
  686. conn->type != CONN_TYPE_AP ||
  687. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  688. continue;
  689. entry_conn = TO_ENTRY_CONN(conn);
  690. if (!entry_conn->want_onehop)
  691. continue;
  692. if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
  693. tor_memneq(digest, failed_digest, DIGEST_LEN))
  694. continue;
  695. if (tor_digest_is_zero(digest)) {
  696. /* we don't know the digest; have to compare addr:port */
  697. tor_addr_t addr;
  698. if (!build_state || !build_state->chosen_exit ||
  699. !entry_conn->socks_request) {
  700. continue;
  701. }
  702. if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
  703. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  704. build_state->chosen_exit->port != entry_conn->socks_request->port)
  705. continue;
  706. }
  707. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  708. "just failed.", entry_conn->chosen_exit_name,
  709. entry_conn->socks_request->address);
  710. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  711. } SMARTLIST_FOREACH_END(conn);
  712. }
  713. /** A circuit failed to finish on its last hop <b>info</b>. If there
  714. * are any streams waiting with this exit node in mind, but they
  715. * don't absolutely require it, make them give up on it.
  716. */
  717. void
  718. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  719. {
  720. entry_connection_t *entry_conn;
  721. const node_t *r1, *r2;
  722. smartlist_t *conns = get_connection_array();
  723. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  724. if (conn->marked_for_close ||
  725. conn->type != CONN_TYPE_AP ||
  726. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  727. continue;
  728. entry_conn = TO_ENTRY_CONN(conn);
  729. if (!entry_conn->chosen_exit_optional &&
  730. !entry_conn->chosen_exit_retries)
  731. continue;
  732. r1 = node_get_by_nickname(entry_conn->chosen_exit_name, 0);
  733. r2 = node_get_by_id(info->identity_digest);
  734. if (!r1 || !r2 || r1 != r2)
  735. continue;
  736. tor_assert(entry_conn->socks_request);
  737. if (entry_conn->chosen_exit_optional) {
  738. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  739. safe_str_client(entry_conn->chosen_exit_name),
  740. escaped_safe_str_client(entry_conn->socks_request->address));
  741. entry_conn->chosen_exit_optional = 0;
  742. tor_free(entry_conn->chosen_exit_name); /* clears it */
  743. /* if this port is dangerous, warn or reject it now that we don't
  744. * think it'll be using an enclave. */
  745. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  746. }
  747. if (entry_conn->chosen_exit_retries) {
  748. if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
  749. clear_trackexithost_mappings(entry_conn->chosen_exit_name);
  750. tor_free(entry_conn->chosen_exit_name); /* clears it */
  751. /* if this port is dangerous, warn or reject it now that we don't
  752. * think it'll be using an enclave. */
  753. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  754. }
  755. }
  756. } SMARTLIST_FOREACH_END(conn);
  757. }
  758. /** The AP connection <b>conn</b> has just failed while attaching or
  759. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  760. * might work. Detach the circuit, and either reattach it, launch a
  761. * new circuit, tell the controller, or give up as appropriate.
  762. *
  763. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  764. */
  765. int
  766. connection_ap_detach_retriable(entry_connection_t *conn,
  767. origin_circuit_t *circ,
  768. int reason)
  769. {
  770. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  771. ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
  772. /* Roll back path bias use state so that we probe the circuit
  773. * if nothing else succeeds on it */
  774. pathbias_mark_use_rollback(circ);
  775. if (conn->pending_optimistic_data) {
  776. generic_buffer_set_to_copy(&conn->sending_optimistic_data,
  777. conn->pending_optimistic_data);
  778. }
  779. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  780. /* If we're attaching streams ourself, or if this connection is
  781. * a tunneled directory connection, then just attach it. */
  782. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  783. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  784. return connection_ap_handshake_attach_circuit(conn);
  785. } else {
  786. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  787. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  788. return 0;
  789. }
  790. }
  791. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  792. * reject depending on our config options. */
  793. static int
  794. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  795. {
  796. const or_options_t *options = get_options();
  797. int reject = smartlist_contains_int_as_string(
  798. options->RejectPlaintextPorts, port);
  799. if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
  800. log_warn(LD_APP, "Application request to port %d: this port is "
  801. "commonly used for unencrypted protocols. Please make sure "
  802. "you don't send anything you would mind the rest of the "
  803. "Internet reading!%s", port, reject ? " Closing." : "");
  804. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  805. port, reject ? "REJECT" : "WARN");
  806. }
  807. if (reject) {
  808. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  809. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  810. return -1;
  811. }
  812. return 0;
  813. }
  814. /** How many times do we try connecting with an exit configured via
  815. * TrackHostExits before concluding that it won't work any more and trying a
  816. * different one? */
  817. #define TRACKHOSTEXITS_RETRIES 5
  818. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  819. * asked us to leave streams unattached. Return 0 in that case.
  820. *
  821. * See connection_ap_handshake_rewrite_and_attach()'s
  822. * documentation for arguments and return value.
  823. */
  824. int
  825. connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
  826. origin_circuit_t *circ,
  827. crypt_path_t *cpath)
  828. {
  829. const or_options_t *options = get_options();
  830. if (options->LeaveStreamsUnattached) {
  831. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  832. return 0;
  833. }
  834. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  835. }
  836. /* Try to perform any map-based rewriting of the target address in
  837. * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
  838. * conn->socks_request.address as appropriate.
  839. */
  840. STATIC void
  841. connection_ap_handshake_rewrite(entry_connection_t *conn,
  842. rewrite_result_t *out)
  843. {
  844. socks_request_t *socks = conn->socks_request;
  845. const or_options_t *options = get_options();
  846. tor_addr_t addr_tmp;
  847. /* Initialize all the fields of 'out' to reasonable defaults */
  848. out->automap = 0;
  849. out->exit_source = ADDRMAPSRC_NONE;
  850. out->map_expires = TIME_MAX;
  851. out->end_reason = 0;
  852. out->should_close = 0;
  853. out->orig_address[0] = 0;
  854. /* We convert all incoming addresses to lowercase. */
  855. tor_strlower(socks->address);
  856. /* Remember the original address. */
  857. strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
  858. log_debug(LD_APP,"Client asked for %s:%d",
  859. safe_str_client(socks->address),
  860. socks->port);
  861. /* Check for whether this is a .exit address. By default, those are
  862. * disallowed when they're coming straight from the client, but you're
  863. * allowed to have them in MapAddress commands and so forth. */
  864. if (!strcmpend(socks->address, ".exit") && !options->AllowDotExit) {
  865. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  866. "security risks. Set AllowDotExit in your torrc to enable "
  867. "it (at your own risk).");
  868. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  869. escaped(socks->address));
  870. out->end_reason = END_STREAM_REASON_TORPROTOCOL;
  871. out->should_close = 1;
  872. return;
  873. }
  874. /* Remember the original address so we can tell the user about what
  875. * they actually said, not just what it turned into. */
  876. if (! conn->original_dest_address) {
  877. /* Is the 'if' necessary here? XXXX */
  878. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  879. }
  880. /* First, apply MapAddress and MAPADDRESS mappings. We need to do
  881. * these only for non-reverse lookups, since they don't exist for those.
  882. * We need to do this before we consider automapping, since we might
  883. * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
  884. * we'd need to automap it. */
  885. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
  886. const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
  887. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  888. rewrite_flags, &out->map_expires, &out->exit_source)) {
  889. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  890. REMAP_STREAM_SOURCE_CACHE);
  891. }
  892. }
  893. /* Now, handle automapping. Automapping happens when we're asked to
  894. * resolve a hostname, and AutomapHostsOnResolve is set, and
  895. * the hostname has a suffix listed in AutomapHostsSuffixes.
  896. */
  897. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  898. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  899. options->AutomapHostsOnResolve) {
  900. /* Check the suffix... */
  901. out->automap = addressmap_address_should_automap(socks->address, options);
  902. if (out->automap) {
  903. /* If we get here, then we should apply an automapping for this. */
  904. const char *new_addr;
  905. /* We return an IPv4 address by default, or an IPv6 address if we
  906. * are allowed to do so. */
  907. int addr_type = RESOLVED_TYPE_IPV4;
  908. if (conn->socks_request->socks_version != 4) {
  909. if (!conn->entry_cfg.ipv4_traffic ||
  910. (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
  911. conn->entry_cfg.prefer_ipv6_virtaddr)
  912. addr_type = RESOLVED_TYPE_IPV6;
  913. }
  914. /* Okay, register the target address as automapped, and find the new
  915. * address we're supposed to give as a resolve answer. (Return a cached
  916. * value if we've looked up this address before.
  917. */
  918. new_addr = addressmap_register_virtual_address(
  919. addr_type, tor_strdup(socks->address));
  920. if (! new_addr) {
  921. log_warn(LD_APP, "Unable to automap address %s",
  922. escaped_safe_str(socks->address));
  923. out->end_reason = END_STREAM_REASON_INTERNAL;
  924. out->should_close = 1;
  925. return;
  926. }
  927. log_info(LD_APP, "Automapping %s to %s",
  928. escaped_safe_str_client(socks->address),
  929. safe_str_client(new_addr));
  930. strlcpy(socks->address, new_addr, sizeof(socks->address));
  931. }
  932. }
  933. /* Now handle reverse lookups, if they're in the cache. This doesn't
  934. * happen too often, since client-side DNS caching is off by default. */
  935. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  936. unsigned rewrite_flags = 0;
  937. if (conn->entry_cfg.use_cached_ipv4_answers)
  938. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  939. if (conn->entry_cfg.use_cached_ipv6_answers)
  940. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  941. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  942. rewrite_flags, &out->map_expires)) {
  943. char *result = tor_strdup(socks->address);
  944. /* remember _what_ is supposed to have been resolved. */
  945. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  946. out->orig_address);
  947. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  948. strlen(result), (uint8_t*)result,
  949. -1,
  950. out->map_expires);
  951. tor_free(result);
  952. out->end_reason = END_STREAM_REASON_DONE |
  953. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  954. out->should_close = 1;
  955. return;
  956. }
  957. /* Hang on, did we find an answer saying that this is a reverse lookup for
  958. * an internal address? If so, we should reject it if we're condigured to
  959. * do so. */
  960. if (options->ClientDNSRejectInternalAddresses) {
  961. /* Don't let people try to do a reverse lookup on 10.0.0.1. */
  962. tor_addr_t addr;
  963. int ok;
  964. ok = tor_addr_parse_PTR_name(
  965. &addr, socks->address, AF_UNSPEC, 1);
  966. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  967. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  968. 0, NULL, -1, TIME_MAX);
  969. out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
  970. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  971. out->should_close = 1;
  972. return;
  973. }
  974. }
  975. }
  976. /* If we didn't automap it before, then this is still the address
  977. * that came straight from the user, mapped according to any
  978. * MapAddress/MAPADDRESS commands. Now other mappings, including
  979. * previously registered Automap entries, TrackHostExits entries,
  980. * and client-side DNS cache entries (not recommended).
  981. */
  982. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
  983. !out->automap) {
  984. unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
  985. addressmap_entry_source_t exit_source2;
  986. if (conn->entry_cfg.use_cached_ipv4_answers)
  987. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  988. if (conn->entry_cfg.use_cached_ipv6_answers)
  989. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  990. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  991. rewrite_flags, &out->map_expires, &exit_source2)) {
  992. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  993. REMAP_STREAM_SOURCE_CACHE);
  994. }
  995. if (out->exit_source == ADDRMAPSRC_NONE) {
  996. /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
  997. * the original source of a .exit. */
  998. out->exit_source = exit_source2;
  999. }
  1000. }
  1001. /* Check to see whether we're about to use an address in the virtual
  1002. * range without actually having gotten it from an Automap. */
  1003. if (!out->automap && address_is_in_virtual_range(socks->address)) {
  1004. /* This address was probably handed out by
  1005. * client_dns_get_unmapped_address, but the mapping was discarded for some
  1006. * reason. Or the user typed in a virtual address range manually. We
  1007. * *don't* want to send the address through Tor; that's likely to fail,
  1008. * and may leak information.
  1009. */
  1010. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1011. safe_str_client(socks->address));
  1012. out->end_reason = END_STREAM_REASON_INTERNAL;
  1013. out->should_close = 1;
  1014. return;
  1015. }
  1016. }
  1017. /** Connection <b>conn</b> just finished its socks handshake, or the
  1018. * controller asked us to take care of it. If <b>circ</b> is defined,
  1019. * then that's where we'll want to attach it. Otherwise we have to
  1020. * figure it out ourselves.
  1021. *
  1022. * First, parse whether it's a .exit address, remap it, and so on. Then
  1023. * if it's for a general circuit, try to attach it to a circuit (or launch
  1024. * one as needed), else if it's for a rendezvous circuit, fetch a
  1025. * rendezvous descriptor first (or attach/launch a circuit if the
  1026. * rendezvous descriptor is already here and fresh enough).
  1027. *
  1028. * The stream will exit from the hop
  1029. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1030. * <b>cpath</b> is NULL.
  1031. */
  1032. int
  1033. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1034. origin_circuit_t *circ,
  1035. crypt_path_t *cpath)
  1036. {
  1037. socks_request_t *socks = conn->socks_request;
  1038. const or_options_t *options = get_options();
  1039. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1040. time_t now = time(NULL);
  1041. rewrite_result_t rr;
  1042. memset(&rr, 0, sizeof(rr));
  1043. connection_ap_handshake_rewrite(conn,&rr);
  1044. if (rr.should_close) {
  1045. /* connection_ap_handshake_rewrite told us to close the connection,
  1046. * either because it sent back an answer, or because it sent back an
  1047. * error */
  1048. connection_mark_unattached_ap(conn, rr.end_reason);
  1049. if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
  1050. return 0;
  1051. else
  1052. return -1;
  1053. }
  1054. const time_t map_expires = rr.map_expires;
  1055. const int automap = rr.automap;
  1056. const addressmap_entry_source_t exit_source = rr.exit_source;
  1057. /* Parse the address provided by SOCKS. Modify it in-place if it
  1058. * specifies a hidden-service (.onion) or particular exit node (.exit).
  1059. */
  1060. const hostname_type_t addresstype = parse_extended_hostname(socks->address);
  1061. /* Now see whether the hostname is bogus. This could happen because of an
  1062. * onion hostname whose format we don't recognize. */
  1063. if (addresstype == BAD_HOSTNAME) {
  1064. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1065. escaped(socks->address));
  1066. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1067. return -1;
  1068. }
  1069. /* If this is a .exit hostname, strip off the .name.exit part, and
  1070. * see whether we're going to connect there, and otherwise handle it.
  1071. * (The ".exit" part got stripped off by "parse_extended_hostname").
  1072. *
  1073. * We'll set chosen_exit_name and/or close the connection as appropriate.
  1074. */
  1075. if (addresstype == EXIT_HOSTNAME) {
  1076. /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
  1077. * not ExcludeExitNodes. */
  1078. routerset_t *excludeset = options->StrictNodes ?
  1079. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  1080. const node_t *node = NULL;
  1081. /* If this .exit was added by an AUTOMAP, then it came straight from
  1082. * a user. Make sure that options->AllowDotExit permits that. */
  1083. if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) {
  1084. /* Whoops; this one is stale. It must have gotten added earlier,
  1085. * when AllowDotExit was on. */
  1086. log_warn(LD_APP,"Stale automapped address for '%s.exit', with "
  1087. "AllowDotExit disabled. Refusing.",
  1088. safe_str_client(socks->address));
  1089. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1090. escaped(socks->address));
  1091. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1092. return -1;
  1093. }
  1094. /* Double-check to make sure there are no .exits coming from
  1095. * impossible/weird sources. */
  1096. if (exit_source == ADDRMAPSRC_DNS ||
  1097. (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) {
  1098. /* It shouldn't be possible to get a .exit address from any of these
  1099. * sources. */
  1100. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  1101. ".exit part. Refusing.",
  1102. safe_str_client(socks->address));
  1103. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1104. escaped(socks->address));
  1105. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1106. return -1;
  1107. }
  1108. tor_assert(!automap);
  1109. /* Now, find the character before the .(name) part. */
  1110. char *s = strrchr(socks->address,'.');
  1111. if (s) {
  1112. /* The address was of the form "(stuff).(name).exit */
  1113. if (s[1] != '\0') {
  1114. /* Looks like a real .exit one. */
  1115. conn->chosen_exit_name = tor_strdup(s+1);
  1116. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1117. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1118. /* We 5 tries before it expires the addressmap */
  1119. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1120. }
  1121. *s = 0;
  1122. } else {
  1123. /* Oops, the address was (stuff)..exit. That's not okay. */
  1124. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1125. safe_str_client(socks->address));
  1126. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1127. escaped(socks->address));
  1128. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1129. return -1;
  1130. }
  1131. } else {
  1132. /* It looks like they just asked for "foo.exit". That's a special
  1133. * form that means (foo's address).foo.exit. */
  1134. conn->chosen_exit_name = tor_strdup(socks->address);
  1135. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1136. if (node) {
  1137. *socks->address = 0;
  1138. node_get_address_string(node, socks->address, sizeof(socks->address));
  1139. }
  1140. }
  1141. /* Now make sure that the chosen exit exists... */
  1142. if (!node) {
  1143. log_warn(LD_APP,
  1144. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1145. safe_str_client(socks->address));
  1146. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1147. return -1;
  1148. }
  1149. /* ...and make sure that it isn't excluded. */
  1150. if (routerset_contains_node(excludeset, node)) {
  1151. log_warn(LD_APP,
  1152. "Excluded relay in exit address '%s.exit'. Refusing.",
  1153. safe_str_client(socks->address));
  1154. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1155. return -1;
  1156. }
  1157. /* XXXX024-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1158. Bar is not listed in it? I say yes, but our revised manpage branch
  1159. implies no. */
  1160. }
  1161. /* Now, handle everything that isn't a .onion address. */
  1162. if (addresstype != ONION_HOSTNAME) {
  1163. /* Not a hidden-service request. It's either a hostname or an IP,
  1164. * possibly with a .exit that we stripped off. */
  1165. /* Check for funny characters in the address. */
  1166. if (address_is_invalid_destination(socks->address, 1)) {
  1167. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1168. escaped(socks->address));
  1169. log_warn(LD_APP,
  1170. "Destination '%s' seems to be an invalid hostname. Failing.",
  1171. safe_str_client(socks->address));
  1172. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1173. return -1;
  1174. }
  1175. /* If we're running in Tor2webMode, we don't allow anything BUT .onion
  1176. * addresses. */
  1177. if (options->Tor2webMode) {
  1178. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname %s "
  1179. "because tor2web mode is enabled.",
  1180. safe_str_client(socks->address));
  1181. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1182. return -1;
  1183. }
  1184. /* See if this is a hostname lookup that we can answer immediately.
  1185. * (For example, an attempt to look up the IP address for an IP address.)
  1186. */
  1187. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1188. tor_addr_t answer;
  1189. /* Reply to resolves immediately if we can. */
  1190. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  1191. /* remember _what_ is supposed to have been resolved. */
  1192. strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
  1193. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  1194. map_expires);
  1195. connection_mark_unattached_ap(conn,
  1196. END_STREAM_REASON_DONE |
  1197. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1198. return 0;
  1199. }
  1200. tor_assert(!automap);
  1201. rep_hist_note_used_resolve(now); /* help predict this next time */
  1202. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1203. /* Special handling for attempts to connect */
  1204. tor_assert(!automap);
  1205. /* Don't allow connections to port 0. */
  1206. if (socks->port == 0) {
  1207. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1208. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1209. return -1;
  1210. }
  1211. /* You can't make connections to internal addresses, by default.
  1212. * Exceptions are begindir requests (where the address is meaningless,
  1213. * or cases where you've hand-configured a particular exit, thereby
  1214. * making the local address meaningful. */
  1215. if (options->ClientRejectInternalAddresses &&
  1216. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1217. /* If we reach this point then we don't want to allow internal
  1218. * addresses. Check if we got one. */
  1219. tor_addr_t addr;
  1220. if (tor_addr_hostname_is_local(socks->address) ||
  1221. (tor_addr_parse(&addr, socks->address) >= 0 &&
  1222. tor_addr_is_internal(&addr, 0))) {
  1223. /* If this is an explicit private address with no chosen exit node,
  1224. * then we really don't want to try to connect to it. That's
  1225. * probably an error. */
  1226. if (conn->is_transparent_ap) {
  1227. #define WARN_INTRVL_LOOP 300
  1228. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  1229. char *m;
  1230. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  1231. log_warn(LD_NET,
  1232. "Rejecting request for anonymous connection to private "
  1233. "address %s on a TransPort or NATDPort. Possible loop "
  1234. "in your NAT rules?%s", safe_str_client(socks->address),
  1235. m);
  1236. tor_free(m);
  1237. }
  1238. } else {
  1239. #define WARN_INTRVL_PRIV 300
  1240. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  1241. char *m;
  1242. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  1243. log_warn(LD_NET,
  1244. "Rejecting SOCKS request for anonymous connection to "
  1245. "private address %s.%s",
  1246. safe_str_client(socks->address),m);
  1247. tor_free(m);
  1248. }
  1249. }
  1250. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  1251. return -1;
  1252. }
  1253. } /* end "if we should check for internal addresses" */
  1254. /* Okay. We're still doing a CONNECT, and it wasn't a private
  1255. * address. Do special handling for literal IP addresses */
  1256. {
  1257. tor_addr_t addr;
  1258. /* XXX Duplicate call to tor_addr_parse. */
  1259. if (tor_addr_parse(&addr, socks->address) >= 0) {
  1260. /* If we reach this point, it's an IPv4 or an IPv6 address. */
  1261. sa_family_t family = tor_addr_family(&addr);
  1262. if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
  1263. (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
  1264. /* You can't do an IPv4 address on a v6-only socks listener,
  1265. * or vice versa. */
  1266. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  1267. "family that this listener does not support.");
  1268. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1269. return -1;
  1270. } else if (family == AF_INET6 && socks->socks_version == 4) {
  1271. /* You can't make a socks4 request to an IPv6 address. Socks4
  1272. * doesn't support that. */
  1273. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  1274. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1275. return -1;
  1276. } else if (socks->socks_version == 4 &&
  1277. !conn->entry_cfg.ipv4_traffic) {
  1278. /* You can't do any kind of Socks4 request when IPv4 is forbidden.
  1279. *
  1280. * XXX raise this check outside the enclosing block? */
  1281. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  1282. "no IPv4 traffic supported.");
  1283. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1284. return -1;
  1285. } else if (family == AF_INET6) {
  1286. /* Tell the exit: we won't accept any ipv4 connection to an IPv6
  1287. * address. */
  1288. conn->entry_cfg.ipv4_traffic = 0;
  1289. } else if (family == AF_INET) {
  1290. /* Tell the exit: we won't accept any ipv6 connection to an IPv4
  1291. * address. */
  1292. conn->entry_cfg.ipv6_traffic = 0;
  1293. }
  1294. }
  1295. }
  1296. if (socks->socks_version == 4)
  1297. conn->entry_cfg.ipv6_traffic = 0;
  1298. /* Still handling CONNECT. Now, check for exit enclaves. (Which we
  1299. * don't do on BEGINDIR, or there is a chosen exit.)
  1300. */
  1301. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1302. /* see if we can find a suitable enclave exit */
  1303. const node_t *r =
  1304. router_find_exact_exit_enclave(socks->address, socks->port);
  1305. if (r) {
  1306. log_info(LD_APP,
  1307. "Redirecting address %s to exit at enclave router %s",
  1308. safe_str_client(socks->address), node_describe(r));
  1309. /* use the hex digest, not nickname, in case there are two
  1310. routers with this nickname */
  1311. conn->chosen_exit_name =
  1312. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  1313. conn->chosen_exit_optional = 1;
  1314. }
  1315. }
  1316. /* Still handling CONNECT: warn or reject if it's using a dangerous
  1317. * port. */
  1318. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  1319. if (consider_plaintext_ports(conn, socks->port) < 0)
  1320. return -1;
  1321. /* Remember the port so that we do predicted requests there. */
  1322. if (!conn->use_begindir) {
  1323. /* help predict this next time */
  1324. rep_hist_note_used_port(now, socks->port);
  1325. }
  1326. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1327. rep_hist_note_used_resolve(now); /* help predict this next time */
  1328. /* no extra processing needed */
  1329. } else {
  1330. /* We should only be doing CONNECT or RESOLVE! */
  1331. tor_fragile_assert();
  1332. }
  1333. /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
  1334. * address, and decided not to reject it for any number of reasons. Now
  1335. * mark the connection as waiting for a circuit, and try to attach it!
  1336. */
  1337. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1338. /* If we were given a circuit to attach to, try to attach. Otherwise,
  1339. * try to find a good one and attach to that. */
  1340. int rv;
  1341. if (circ)
  1342. rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
  1343. else
  1344. rv = connection_ap_handshake_attach_circuit(conn);
  1345. /* If the above function returned 0 then we're waiting for a circuit.
  1346. * if it returned 1, we're attached. Both are okay. But if it returned
  1347. * -1, there was an error, so make sure the connection is marked, and
  1348. * return -1. */
  1349. if (rv < 0) {
  1350. if (!base_conn->marked_for_close)
  1351. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1352. return -1;
  1353. }
  1354. return 0;
  1355. } else {
  1356. /* If we get here, it's a request for a .onion address! */
  1357. tor_assert(!automap);
  1358. /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
  1359. * for hidden service addresses. */
  1360. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1361. /* if it's a resolve request, fail it right now, rather than
  1362. * building all the circuits and then realizing it won't work. */
  1363. log_warn(LD_APP,
  1364. "Resolve requests to hidden services not allowed. Failing.");
  1365. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1366. 0,NULL,-1,TIME_MAX);
  1367. connection_mark_unattached_ap(conn,
  1368. END_STREAM_REASON_SOCKSPROTOCOL |
  1369. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1370. return -1;
  1371. }
  1372. /* If we were passed a circuit, then we need to fail. .onion addresses
  1373. * only work when we launch our own circuits for now. */
  1374. if (circ) {
  1375. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1376. "supported for .onion addresses currently. Failing.");
  1377. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1378. return -1;
  1379. }
  1380. /* Fill in the rend_data field so we can start doing a connection to
  1381. * a hidden service. */
  1382. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
  1383. tor_malloc_zero(sizeof(rend_data_t));
  1384. strlcpy(rend_data->onion_address, socks->address,
  1385. sizeof(rend_data->onion_address));
  1386. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1387. safe_str_client(rend_data->onion_address));
  1388. /* see if we already have a hidden service descriptor cached for this
  1389. * address. */
  1390. rend_cache_entry_t *entry = NULL;
  1391. const int rend_cache_lookup_result =
  1392. rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
  1393. if (rend_cache_lookup_result < 0) {
  1394. /* We should already have rejected this address! */
  1395. log_warn(LD_BUG,"Invalid service name '%s'",
  1396. safe_str_client(rend_data->onion_address));
  1397. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1398. return -1;
  1399. }
  1400. /* Help predict this next time. We're not sure if it will need
  1401. * a stable circuit yet, but we know we'll need *something*. */
  1402. rep_hist_note_used_internal(now, 0, 1);
  1403. /* Look up if we have client authorization configured for this hidden
  1404. * service. If we do, associate it with the rend_data. */
  1405. rend_service_authorization_t *client_auth =
  1406. rend_client_lookup_service_authorization(
  1407. rend_data->onion_address);
  1408. if (client_auth) {
  1409. log_info(LD_REND, "Using previously configured client authorization "
  1410. "for hidden service request.");
  1411. memcpy(rend_data->descriptor_cookie,
  1412. client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1413. rend_data->auth_type = client_auth->auth_type;
  1414. }
  1415. /* Now, we either launch an attempt to connect to the hidden service,
  1416. * or we launch an attempt to look up its descriptor, depending on
  1417. * whether we had the descriptor. */
  1418. if (rend_cache_lookup_result == 0) {
  1419. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1420. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1421. safe_str_client(rend_data->onion_address));
  1422. rend_client_refetch_v2_renddesc(rend_data);
  1423. } else { /* rend_cache_lookup_result > 0 */
  1424. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1425. log_info(LD_REND, "Descriptor is here. Great.");
  1426. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1427. if (!base_conn->marked_for_close)
  1428. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1429. return -1;
  1430. }
  1431. }
  1432. return 0;
  1433. }
  1434. return 0; /* unreached but keeps the compiler happy */
  1435. }
  1436. #ifdef TRANS_PF
  1437. static int pf_socket = -1;
  1438. int
  1439. get_pf_socket(void)
  1440. {
  1441. int pf;
  1442. /* This should be opened before dropping privileges. */
  1443. if (pf_socket >= 0)
  1444. return pf_socket;
  1445. #ifdef OPENBSD
  1446. /* only works on OpenBSD */
  1447. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  1448. #else
  1449. /* works on NetBSD and FreeBSD */
  1450. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  1451. #endif
  1452. if (pf < 0) {
  1453. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1454. return -1;
  1455. }
  1456. pf_socket = pf;
  1457. return pf_socket;
  1458. }
  1459. #endif
  1460. #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || defined(TRANS_TPROXY)
  1461. /** Try fill in the address of <b>req</b> from the socket configured
  1462. * with <b>conn</b>. */
  1463. static int
  1464. destination_from_socket(entry_connection_t *conn, socks_request_t *req)
  1465. {
  1466. struct sockaddr_storage orig_dst;
  1467. socklen_t orig_dst_len = sizeof(orig_dst);
  1468. tor_addr_t addr;
  1469. int rv;
  1470. #ifdef TRANS_TRPOXY
  1471. if (options->TransProxyType_parsed == TPT_TPROXY) {
  1472. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  1473. &orig_dst_len) < 0) {
  1474. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1475. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1476. return -1;
  1477. }
  1478. goto done;
  1479. }
  1480. #endif
  1481. #ifdef TRANS_NETFILTER
  1482. switch (ENTRY_TO_CONN(conn)->socket_family) {
  1483. #ifdef TRANS_NETFILTER_IPV4
  1484. case AF_INET:
  1485. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  1486. (struct sockaddr*)&orig_dst, &orig_dst_len);
  1487. break;
  1488. #endif
  1489. #ifdef TRANS_NETFILTER_IPV6
  1490. case AF_INET6:
  1491. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
  1492. (struct sockaddr*)&orig_dst, &orig_dst_len);
  1493. break;
  1494. #endif
  1495. default:
  1496. log_warn(LD_BUG,
  1497. "Received transparent data from an unsuported socket family %d",
  1498. ENTRY_TO_CONN(conn)->socket_family);
  1499. return -1;
  1500. }
  1501. if (rv < 0) {
  1502. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1503. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1504. return -1;
  1505. }
  1506. goto done;
  1507. #elif defined(TRANS_PF)
  1508. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  1509. &orig_dst_len) < 0) {
  1510. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1511. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1512. return -1;
  1513. }
  1514. goto done;
  1515. #else
  1516. (void)conn;
  1517. (void)req;
  1518. log_warn(LD_BUG, "Unable to determine destination from socket.");
  1519. return -1;
  1520. #endif
  1521. done:
  1522. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  1523. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1524. return 0;
  1525. }
  1526. #endif
  1527. #ifdef TRANS_PF
  1528. static int
  1529. destination_from_pf(entry_connection_t *conn, socks_request_t *req)
  1530. {
  1531. struct sockaddr_storage proxy_addr;
  1532. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1533. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  1534. struct pfioc_natlook pnl;
  1535. tor_addr_t addr;
  1536. int pf = -1;
  1537. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  1538. &proxy_addr_len) < 0) {
  1539. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1540. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1541. "failed: %s", tor_socket_strerror(e));
  1542. return -1;
  1543. }
  1544. #ifdef __FreeBSD__
  1545. if (get_options()->TransProxyType_parsed == TPT_IPFW) {
  1546. /* ipfw(8) is used and in this case getsockname returned the original
  1547. destination */
  1548. if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
  1549. tor_fragile_assert();
  1550. return -1;
  1551. }
  1552. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1553. return 0;
  1554. }
  1555. #endif
  1556. memset(&pnl, 0, sizeof(pnl));
  1557. pnl.proto = IPPROTO_TCP;
  1558. pnl.direction = PF_OUT;
  1559. if (proxy_sa->sa_family == AF_INET) {
  1560. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  1561. pnl.af = AF_INET;
  1562. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  1563. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1564. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  1565. pnl.dport = sin->sin_port;
  1566. } else if (proxy_sa->sa_family == AF_INET6) {
  1567. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  1568. pnl.af = AF_INET6;
  1569. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
  1570. sizeof(struct in6_addr));
  1571. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1572. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  1573. pnl.dport = sin6->sin6_port;
  1574. } else {
  1575. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  1576. (int)proxy_sa->sa_family);
  1577. return -1;
  1578. }
  1579. pf = get_pf_socket();
  1580. if (pf<0)
  1581. return -1;
  1582. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1583. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1584. return -1;
  1585. }
  1586. if (pnl.af == AF_INET) {
  1587. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  1588. } else if (pnl.af == AF_INET6) {
  1589. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  1590. } else {
  1591. tor_fragile_assert();
  1592. return -1;
  1593. }
  1594. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1595. req->port = ntohs(pnl.rdport);
  1596. return 0;
  1597. }
  1598. #endif
  1599. /** Fetch the original destination address and port from a
  1600. * system-specific interface and put them into a
  1601. * socks_request_t as if they came from a socks request.
  1602. *
  1603. * Return -1 if an error prevents fetching the destination,
  1604. * else return 0.
  1605. */
  1606. static int
  1607. connection_ap_get_original_destination(entry_connection_t *conn,
  1608. socks_request_t *req)
  1609. {
  1610. #ifdef TRANS_NETFILTER
  1611. return destination_from_socket(conn, req);
  1612. #elif defined(TRANS_PF)
  1613. const or_options_t *options = get_options();
  1614. if (options->TransProxyType_parsed == TPT_PF_DIVERT)
  1615. return destination_from_socket(conn, req);
  1616. if (options->TransProxyType_parsed == TPT_DEFAULT)
  1617. return destination_from_pf(conn, req);
  1618. (void)conn;
  1619. (void)req;
  1620. log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
  1621. options->TransProxyType);
  1622. return -1;
  1623. #else
  1624. (void)conn;
  1625. (void)req;
  1626. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1627. "transparent proxy method was configured.");
  1628. return -1;
  1629. #endif
  1630. }
  1631. /** connection_edge_process_inbuf() found a conn in state
  1632. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1633. * the socks handshake.
  1634. *
  1635. * If the handshake is complete, send it to
  1636. * connection_ap_handshake_rewrite_and_attach().
  1637. *
  1638. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  1639. * else return 0.
  1640. */
  1641. static int
  1642. connection_ap_handshake_process_socks(entry_connection_t *conn)
  1643. {
  1644. socks_request_t *socks;
  1645. int sockshere;
  1646. const or_options_t *options = get_options();
  1647. int had_reply = 0;
  1648. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1649. tor_assert(conn);
  1650. tor_assert(base_conn->type == CONN_TYPE_AP);
  1651. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  1652. tor_assert(conn->socks_request);
  1653. socks = conn->socks_request;
  1654. log_debug(LD_APP,"entered.");
  1655. IF_HAS_BUFFEREVENT(base_conn, {
  1656. struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
  1657. sockshere = fetch_from_evbuffer_socks(input, socks,
  1658. options->TestSocks, options->SafeSocks);
  1659. }) ELSE_IF_NO_BUFFEREVENT {
  1660. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  1661. options->TestSocks, options->SafeSocks);
  1662. };
  1663. if (socks->replylen) {
  1664. had_reply = 1;
  1665. connection_write_to_buf((const char*)socks->reply, socks->replylen,
  1666. base_conn);
  1667. socks->replylen = 0;
  1668. if (sockshere == -1) {
  1669. /* An invalid request just got a reply, no additional
  1670. * one is necessary. */
  1671. socks->has_finished = 1;
  1672. }
  1673. }
  1674. if (sockshere == 0) {
  1675. log_debug(LD_APP,"socks handshake not all here yet.");
  1676. return 0;
  1677. } else if (sockshere == -1) {
  1678. if (!had_reply) {
  1679. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1680. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1681. END_STREAM_REASON_SOCKSPROTOCOL);
  1682. }
  1683. connection_mark_unattached_ap(conn,
  1684. END_STREAM_REASON_SOCKSPROTOCOL |
  1685. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1686. return -1;
  1687. } /* else socks handshake is done, continue processing */
  1688. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  1689. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1690. else
  1691. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  1692. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1693. }
  1694. /** connection_init_accepted_conn() found a new trans AP conn.
  1695. * Get the original destination and send it to
  1696. * connection_ap_handshake_rewrite_and_attach().
  1697. *
  1698. * Return -1 if an unexpected error with conn (and it should be marked
  1699. * for close), else return 0.
  1700. */
  1701. int
  1702. connection_ap_process_transparent(entry_connection_t *conn)
  1703. {
  1704. socks_request_t *socks;
  1705. tor_assert(conn);
  1706. tor_assert(conn->socks_request);
  1707. socks = conn->socks_request;
  1708. /* pretend that a socks handshake completed so we don't try to
  1709. * send a socks reply down a transparent conn */
  1710. socks->command = SOCKS_COMMAND_CONNECT;
  1711. socks->has_finished = 1;
  1712. log_debug(LD_APP,"entered.");
  1713. if (connection_ap_get_original_destination(conn, socks) < 0) {
  1714. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  1715. connection_mark_unattached_ap(conn,
  1716. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  1717. return -1;
  1718. }
  1719. /* we have the original destination */
  1720. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1721. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1722. }
  1723. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  1724. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  1725. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  1726. * form of the original destination.
  1727. *
  1728. * If the original destination is complete, send it to
  1729. * connection_ap_handshake_rewrite_and_attach().
  1730. *
  1731. * Return -1 if an unexpected error with conn (and it should be marked
  1732. * for close), else return 0.
  1733. */
  1734. static int
  1735. connection_ap_process_natd(entry_connection_t *conn)
  1736. {
  1737. char tmp_buf[36], *tbuf, *daddr;
  1738. size_t tlen = 30;
  1739. int err, port_ok;
  1740. socks_request_t *socks;
  1741. tor_assert(conn);
  1742. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  1743. tor_assert(conn->socks_request);
  1744. socks = conn->socks_request;
  1745. log_debug(LD_APP,"entered.");
  1746. /* look for LF-terminated "[DEST ip_addr port]"
  1747. * where ip_addr is a dotted-quad and port is in string form */
  1748. err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  1749. if (err == 0)
  1750. return 0;
  1751. if (err < 0) {
  1752. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  1753. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1754. return -1;
  1755. }
  1756. if (strcmpstart(tmp_buf, "[DEST ")) {
  1757. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1758. "said: %s",
  1759. escaped(tmp_buf));
  1760. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1761. return -1;
  1762. }
  1763. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  1764. if (!(tbuf = strchr(tbuf, ' '))) {
  1765. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1766. "said: %s",
  1767. escaped(tmp_buf));
  1768. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1769. return -1;
  1770. }
  1771. *tbuf++ = '\0';
  1772. /* pretend that a socks handshake completed so we don't try to
  1773. * send a socks reply down a natd conn */
  1774. strlcpy(socks->address, daddr, sizeof(socks->address));
  1775. socks->port = (uint16_t)
  1776. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  1777. if (!port_ok) {
  1778. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  1779. "of range.", escaped(tbuf));
  1780. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1781. return -1;
  1782. }
  1783. socks->command = SOCKS_COMMAND_CONNECT;
  1784. socks->has_finished = 1;
  1785. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1786. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1787. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1788. }
  1789. /** Iterate over the two bytes of stream_id until we get one that is not
  1790. * already in use; return it. Return 0 if can't get a unique stream_id.
  1791. */
  1792. streamid_t
  1793. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  1794. {
  1795. edge_connection_t *tmpconn;
  1796. streamid_t test_stream_id;
  1797. uint32_t attempts=0;
  1798. again:
  1799. test_stream_id = circ->next_stream_id++;
  1800. if (++attempts > 1<<16) {
  1801. /* Make sure we don't loop forever if all stream_id's are used. */
  1802. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1803. return 0;
  1804. }
  1805. if (test_stream_id == 0)
  1806. goto again;
  1807. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1808. if (tmpconn->stream_id == test_stream_id)
  1809. goto again;
  1810. return test_stream_id;
  1811. }
  1812. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  1813. * an exit that supports optimistic data. */
  1814. static int
  1815. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  1816. {
  1817. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  1818. /* We can only send optimistic data if we're connected to an open
  1819. general circuit. */
  1820. if (edge_conn->on_circuit == NULL ||
  1821. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  1822. (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  1823. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
  1824. return 0;
  1825. return conn->may_use_optimistic_data;
  1826. }
  1827. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  1828. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  1829. static uint32_t
  1830. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  1831. {
  1832. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1833. const node_t *exitnode = NULL;
  1834. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  1835. uint32_t flags = 0;
  1836. /* No flags for begindir */
  1837. if (ap_conn->use_begindir)
  1838. return 0;
  1839. /* No flags for hidden services. */
  1840. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1841. return 0;
  1842. /* If only IPv4 is supported, no flags */
  1843. if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
  1844. return 0;
  1845. if (! cpath_layer ||
  1846. ! cpath_layer->extend_info)
  1847. return 0;
  1848. if (!ap_conn->entry_cfg.ipv4_traffic)
  1849. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  1850. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  1851. if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
  1852. tor_addr_t a;
  1853. tor_addr_make_null(&a, AF_INET6);
  1854. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  1855. exitnode)
  1856. != ADDR_POLICY_REJECTED) {
  1857. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  1858. * no point. */
  1859. flags |= BEGIN_FLAG_IPV6_OK;
  1860. }
  1861. }
  1862. if (flags == BEGIN_FLAG_IPV6_OK) {
  1863. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  1864. * prefer IPv6. Otherwise there's no point in declaring a preference */
  1865. if (ap_conn->entry_cfg.prefer_ipv6)
  1866. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  1867. }
  1868. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  1869. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  1870. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  1871. "not going to work. Did you perhaps ask for an IPv6 address "
  1872. "on an IPv4Only port, or vice versa?");
  1873. }
  1874. return flags;
  1875. }
  1876. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1877. * socks_request field, and send it down circ.
  1878. *
  1879. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1880. */
  1881. int
  1882. connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
  1883. {
  1884. char payload[CELL_PAYLOAD_SIZE];
  1885. int payload_len;
  1886. int begin_type;
  1887. origin_circuit_t *circ;
  1888. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1889. connection_t *base_conn = TO_CONN(edge_conn);
  1890. tor_assert(edge_conn->on_circuit);
  1891. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  1892. tor_assert(base_conn->type == CONN_TYPE_AP);
  1893. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1894. tor_assert(ap_conn->socks_request);
  1895. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  1896. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1897. if (edge_conn->stream_id==0) {
  1898. /* XXXX024 Instead of closing this stream, we should make it get
  1899. * retried on another circuit. */
  1900. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1901. /* Mark this circuit "unusable for new streams". */
  1902. mark_circuit_unusable_for_new_conns(circ);
  1903. return -1;
  1904. }
  1905. /* Set up begin cell flags. */
  1906. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  1907. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1908. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1909. ap_conn->socks_request->address : "",
  1910. ap_conn->socks_request->port);
  1911. payload_len = (int)strlen(payload)+1;
  1912. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  1913. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  1914. payload_len += 4;
  1915. }
  1916. log_info(LD_APP,
  1917. "Sending relay cell %d to begin stream %d.",
  1918. (int)ap_conn->use_begindir,
  1919. edge_conn->stream_id);
  1920. begin_type = ap_conn->use_begindir ?
  1921. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  1922. if (begin_type == RELAY_COMMAND_BEGIN) {
  1923. #ifndef NON_ANONYMOUS_MODE_ENABLED
  1924. tor_assert(circ->build_state->onehop_tunnel == 0);
  1925. #endif
  1926. }
  1927. if (connection_edge_send_command(edge_conn, begin_type,
  1928. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  1929. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  1930. return -1; /* circuit is closed, don't continue */
  1931. edge_conn->package_window = STREAMWINDOW_START;
  1932. edge_conn->deliver_window = STREAMWINDOW_START;
  1933. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  1934. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  1935. ", n_circ_id %u",
  1936. base_conn->s, (unsigned)circ->base_.n_circ_id);
  1937. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  1938. /* If there's queued-up data, send it now */
  1939. if ((connection_get_inbuf_len(base_conn) ||
  1940. ap_conn->sending_optimistic_data) &&
  1941. connection_ap_supports_optimistic_data(ap_conn)) {
  1942. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  1943. (long)connection_get_inbuf_len(base_conn),
  1944. ap_conn->sending_optimistic_data ?
  1945. (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
  1946. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  1947. connection_mark_for_close(base_conn);
  1948. }
  1949. }
  1950. return 0;
  1951. }
  1952. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1953. * socks_request field, and send it down circ.
  1954. *
  1955. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1956. */
  1957. int
  1958. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  1959. {
  1960. int payload_len, command;
  1961. const char *string_addr;
  1962. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  1963. origin_circuit_t *circ;
  1964. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1965. connection_t *base_conn = TO_CONN(edge_conn);
  1966. tor_assert(edge_conn->on_circuit);
  1967. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  1968. tor_assert(base_conn->type == CONN_TYPE_AP);
  1969. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1970. tor_assert(ap_conn->socks_request);
  1971. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1972. command = ap_conn->socks_request->command;
  1973. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  1974. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1975. if (edge_conn->stream_id==0) {
  1976. /* XXXX024 Instead of closing this stream, we should make it get
  1977. * retried on another circuit. */
  1978. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1979. /* Mark this circuit "unusable for new streams". */
  1980. mark_circuit_unusable_for_new_conns(circ);
  1981. return -1;
  1982. }
  1983. if (command == SOCKS_COMMAND_RESOLVE) {
  1984. string_addr = ap_conn->socks_request->address;
  1985. payload_len = (int)strlen(string_addr)+1;
  1986. } else {
  1987. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  1988. const char *a = ap_conn->socks_request->address;
  1989. tor_addr_t addr;
  1990. int r;
  1991. /* We're doing a reverse lookup. The input could be an IP address, or
  1992. * could be an .in-addr.arpa or .ip6.arpa address */
  1993. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  1994. if (r <= 0) {
  1995. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  1996. safe_str_client(a));
  1997. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1998. return -1;
  1999. }
  2000. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2001. if (r < 0) {
  2002. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2003. safe_str_client(a));
  2004. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2005. return -1;
  2006. }
  2007. string_addr = inaddr_buf;
  2008. payload_len = (int)strlen(inaddr_buf)+1;
  2009. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2010. }
  2011. log_debug(LD_APP,
  2012. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2013. if (connection_edge_send_command(edge_conn,
  2014. RELAY_COMMAND_RESOLVE,
  2015. string_addr, payload_len) < 0)
  2016. return -1; /* circuit is closed, don't continue */
  2017. if (!base_conn->address) {
  2018. /* This might be unnecessary. XXXX */
  2019. base_conn->address = tor_dup_addr(&base_conn->addr);
  2020. }
  2021. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2022. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  2023. ", n_circ_id %u",
  2024. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2025. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2026. return 0;
  2027. }
  2028. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  2029. * new linked connection pair, and attach one side to the conn, connection_add
  2030. * it, initialize it to circuit_wait, and call
  2031. * connection_ap_handshake_attach_circuit(conn) on it.
  2032. *
  2033. * Return the newly created end of the linked connection pair, or -1 if error.
  2034. */
  2035. entry_connection_t *
  2036. connection_ap_make_link(connection_t *partner,
  2037. char *address, uint16_t port,
  2038. const char *digest,
  2039. int session_group, int isolation_flags,
  2040. int use_begindir, int want_onehop)
  2041. {
  2042. entry_connection_t *conn;
  2043. connection_t *base_conn;
  2044. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2045. want_onehop ? "direct" : "anonymized",
  2046. safe_str_client(address), port);
  2047. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  2048. base_conn = ENTRY_TO_CONN(conn);
  2049. base_conn->linked = 1; /* so that we can add it safely below. */
  2050. /* populate conn->socks_request */
  2051. /* leave version at zero, so the socks_reply is empty */
  2052. conn->socks_request->socks_version = 0;
  2053. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2054. strlcpy(conn->socks_request->address, address,
  2055. sizeof(conn->socks_request->address));
  2056. conn->socks_request->port = port;
  2057. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2058. conn->want_onehop = want_onehop;
  2059. conn->use_begindir = use_begindir;
  2060. if (use_begindir) {
  2061. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2062. conn->chosen_exit_name[0] = '$';
  2063. tor_assert(digest);
  2064. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2065. digest, DIGEST_LEN);
  2066. }
  2067. /* Populate isolation fields. */
  2068. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2069. conn->original_dest_address = tor_strdup(address);
  2070. conn->entry_cfg.session_group = session_group;
  2071. conn->entry_cfg.isolation_flags = isolation_flags;
  2072. base_conn->address = tor_strdup("(Tor_internal)");
  2073. tor_addr_make_unspec(&base_conn->addr);
  2074. base_conn->port = 0;
  2075. connection_link_connections(partner, base_conn);
  2076. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2077. connection_free(base_conn);
  2078. return NULL;
  2079. }
  2080. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2081. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2082. /* attaching to a dirty circuit is fine */
  2083. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  2084. if (!base_conn->marked_for_close)
  2085. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2086. return NULL;
  2087. }
  2088. log_info(LD_APP,"... application connection created and linked.");
  2089. return conn;
  2090. }
  2091. /** Notify any interested controller connections about a new hostname resolve
  2092. * or resolve error. Takes the same arguments as does
  2093. * connection_ap_handshake_socks_resolved(). */
  2094. static void
  2095. tell_controller_about_resolved_result(entry_connection_t *conn,
  2096. int answer_type,
  2097. size_t answer_len,
  2098. const char *answer,
  2099. int ttl,
  2100. time_t expires)
  2101. {
  2102. expires = time(NULL) + ttl;
  2103. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  2104. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  2105. control_event_address_mapped(conn->socks_request->address,
  2106. cp, expires, NULL, 0);
  2107. tor_free(cp);
  2108. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2109. char *cp = tor_strndup(answer, answer_len);
  2110. control_event_address_mapped(conn->socks_request->address,
  2111. cp, expires, NULL, 0);
  2112. tor_free(cp);
  2113. } else {
  2114. control_event_address_mapped(conn->socks_request->address,
  2115. "<error>", time(NULL)+ttl,
  2116. "error=yes", 0);
  2117. }
  2118. }
  2119. /**
  2120. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  2121. * as the answer.
  2122. */
  2123. void
  2124. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  2125. const tor_addr_t *answer,
  2126. int ttl,
  2127. time_t expires)
  2128. {
  2129. if (tor_addr_family(answer) == AF_INET) {
  2130. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  2131. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  2132. (uint8_t*)&a,
  2133. ttl, expires);
  2134. } else if (tor_addr_family(answer) == AF_INET6) {
  2135. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  2136. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  2137. a,
  2138. ttl, expires);
  2139. } else {
  2140. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  2141. tor_addr_family(answer));
  2142. connection_ap_handshake_socks_resolved(conn,
  2143. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  2144. }
  2145. }
  2146. /** Send an answer to an AP connection that has requested a DNS lookup via
  2147. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  2148. * for unreachable; the answer should be in the format specified in the socks
  2149. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  2150. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  2151. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  2152. **/
  2153. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  2154. * interface and those that use it less ugly. */
  2155. MOCK_IMPL(void,
  2156. connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
  2157. int answer_type,
  2158. size_t answer_len,
  2159. const uint8_t *answer,
  2160. int ttl,
  2161. time_t expires))
  2162. {
  2163. char buf[384];
  2164. size_t replylen;
  2165. if (ttl >= 0) {
  2166. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2167. tor_addr_t a;
  2168. tor_addr_from_ipv4n(&a, get_uint32(answer));
  2169. if (! tor_addr_is_null(&a)) {
  2170. client_dns_set_addressmap(conn,
  2171. conn->socks_request->address, &a,
  2172. conn->chosen_exit_name, ttl);
  2173. }
  2174. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2175. tor_addr_t a;
  2176. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  2177. if (! tor_addr_is_null(&a)) {
  2178. client_dns_set_addressmap(conn,
  2179. conn->socks_request->address, &a,
  2180. conn->chosen_exit_name, ttl);
  2181. }
  2182. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2183. char *cp = tor_strndup((char*)answer, answer_len);
  2184. client_dns_set_reverse_addressmap(conn,
  2185. conn->socks_request->address,
  2186. cp,
  2187. conn->chosen_exit_name, ttl);
  2188. tor_free(cp);
  2189. }
  2190. }
  2191. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  2192. if (conn->dns_server_request) {
  2193. /* We had a request on our DNS port: answer it. */
  2194. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  2195. conn->socks_request->has_finished = 1;
  2196. return;
  2197. } else {
  2198. /* This must be a request from the controller. Since answers to those
  2199. * requests are not cached, they do not generate an ADDRMAP event on
  2200. * their own. */
  2201. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  2202. (char*)answer, ttl, expires);
  2203. conn->socks_request->has_finished = 1;
  2204. return;
  2205. }
  2206. /* We shouldn't need to free conn here; it gets marked by the caller. */
  2207. }
  2208. if (conn->socks_request->socks_version == 4) {
  2209. buf[0] = 0x00; /* version */
  2210. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2211. buf[1] = SOCKS4_GRANTED;
  2212. set_uint16(buf+2, 0);
  2213. memcpy(buf+4, answer, 4); /* address */
  2214. replylen = SOCKS4_NETWORK_LEN;
  2215. } else { /* "error" */
  2216. buf[1] = SOCKS4_REJECT;
  2217. memset(buf+2, 0, 6);
  2218. replylen = SOCKS4_NETWORK_LEN;
  2219. }
  2220. } else if (conn->socks_request->socks_version == 5) {
  2221. /* SOCKS5 */
  2222. buf[0] = 0x05; /* version */
  2223. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2224. buf[1] = SOCKS5_SUCCEEDED;
  2225. buf[2] = 0; /* reserved */
  2226. buf[3] = 0x01; /* IPv4 address type */
  2227. memcpy(buf+4, answer, 4); /* address */
  2228. set_uint16(buf+8, 0); /* port == 0. */
  2229. replylen = 10;
  2230. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2231. buf[1] = SOCKS5_SUCCEEDED;
  2232. buf[2] = 0; /* reserved */
  2233. buf[3] = 0x04; /* IPv6 address type */
  2234. memcpy(buf+4, answer, 16); /* address */
  2235. set_uint16(buf+20, 0); /* port == 0. */
  2236. replylen = 22;
  2237. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2238. buf[1] = SOCKS5_SUCCEEDED;
  2239. buf[2] = 0; /* reserved */
  2240. buf[3] = 0x03; /* Domainname address type */
  2241. buf[4] = (char)answer_len;
  2242. memcpy(buf+5, answer, answer_len); /* address */
  2243. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  2244. replylen = 5+answer_len+2;
  2245. } else {
  2246. buf[1] = SOCKS5_HOST_UNREACHABLE;
  2247. memset(buf+2, 0, 8);
  2248. replylen = 10;
  2249. }
  2250. } else {
  2251. /* no socks version info; don't send anything back */
  2252. return;
  2253. }
  2254. connection_ap_handshake_socks_reply(conn, buf, replylen,
  2255. (answer_type == RESOLVED_TYPE_IPV4 ||
  2256. answer_type == RESOLVED_TYPE_IPV6 ||
  2257. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  2258. 0 : END_STREAM_REASON_RESOLVEFAILED);
  2259. }
  2260. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  2261. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  2262. * handshaking.
  2263. *
  2264. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  2265. * and return, else reply based on <b>endreason</b> (one of
  2266. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  2267. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  2268. */
  2269. void
  2270. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  2271. size_t replylen, int endreason)
  2272. {
  2273. char buf[256];
  2274. socks5_reply_status_t status =
  2275. stream_end_reason_to_socks5_response(endreason);
  2276. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  2277. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2278. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  2279. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  2280. endreason);
  2281. }
  2282. /* Flag this stream's circuit as having completed a stream successfully
  2283. * (for path bias) */
  2284. if (status == SOCKS5_SUCCEEDED ||
  2285. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  2286. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  2287. endreason == END_STREAM_REASON_CONNRESET ||
  2288. endreason == END_STREAM_REASON_NOROUTE ||
  2289. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  2290. if (!conn->edge_.on_circuit ||
  2291. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  2292. if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
  2293. log_info(LD_BUG,
  2294. "No origin circuit for successful SOCKS stream "U64_FORMAT
  2295. ". Reason: %d",
  2296. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  2297. endreason);
  2298. }
  2299. /*
  2300. * Else DNS remaps and failed hidden service lookups can send us
  2301. * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
  2302. *
  2303. * Perhaps we could make the test more precise; we can tell hidden
  2304. * services by conn->edge_.renddata != NULL; anything analogous for
  2305. * the DNS remap case?
  2306. */
  2307. } else {
  2308. // XXX: Hrmm. It looks like optimistic data can't go through this
  2309. // codepath, but someone should probably test it and make sure.
  2310. // We don't want to mark optimistically opened streams as successful.
  2311. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  2312. }
  2313. }
  2314. if (conn->socks_request->has_finished) {
  2315. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  2316. "connection_ap_handshake_socks_reply.");
  2317. return;
  2318. }
  2319. if (replylen) { /* we already have a reply in mind */
  2320. connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
  2321. conn->socks_request->has_finished = 1;
  2322. return;
  2323. }
  2324. if (conn->socks_request->socks_version == 4) {
  2325. memset(buf,0,SOCKS4_NETWORK_LEN);
  2326. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  2327. /* leave version, destport, destip zero */
  2328. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  2329. } else if (conn->socks_request->socks_version == 5) {
  2330. size_t buf_len;
  2331. memset(buf,0,sizeof(buf));
  2332. if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
  2333. buf[0] = 5; /* version 5 */
  2334. buf[1] = (char)status;
  2335. buf[2] = 0;
  2336. buf[3] = 1; /* ipv4 addr */
  2337. /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
  2338. buf_len = 10;
  2339. } else { /* AF_INET6. */
  2340. buf[0] = 5; /* version 5 */
  2341. buf[1] = (char)status;
  2342. buf[2] = 0;
  2343. buf[3] = 4; /* ipv6 addr */
  2344. /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
  2345. buf_len = 22;
  2346. }
  2347. connection_write_to_buf(buf,buf_len,ENTRY_TO_CONN(conn));
  2348. }
  2349. /* If socks_version isn't 4 or 5, don't send anything.
  2350. * This can happen in the case of AP bridges. */
  2351. conn->socks_request->has_finished = 1;
  2352. return;
  2353. }
  2354. /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
  2355. * place the result in <b>bcell</b>. On success return 0; on failure return
  2356. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  2357. * the client.
  2358. *
  2359. * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
  2360. * we don't.
  2361. **/
  2362. STATIC int
  2363. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  2364. uint8_t *end_reason_out)
  2365. {
  2366. relay_header_t rh;
  2367. const uint8_t *body, *nul;
  2368. memset(bcell, 0, sizeof(*bcell));
  2369. *end_reason_out = END_STREAM_REASON_MISC;
  2370. relay_header_unpack(&rh, cell->payload);
  2371. if (rh.length > RELAY_PAYLOAD_SIZE) {
  2372. return -2; /*XXXX why not TORPROTOCOL? */
  2373. }
  2374. bcell->stream_id = rh.stream_id;
  2375. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2376. bcell->is_begindir = 1;
  2377. return 0;
  2378. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  2379. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2380. *end_reason_out = END_STREAM_REASON_INTERNAL;
  2381. return -1;
  2382. }
  2383. body = cell->payload + RELAY_HEADER_SIZE;
  2384. nul = memchr(body, 0, rh.length);
  2385. if (! nul) {
  2386. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2387. "Relay begin cell has no \\0. Closing.");
  2388. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2389. return -1;
  2390. }
  2391. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  2392. (char*)(body),
  2393. &bcell->address,&bcell->port)<0) {
  2394. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2395. "Unable to parse addr:port in relay begin cell. Closing.");
  2396. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2397. return -1;
  2398. }
  2399. if (bcell->port == 0) {
  2400. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2401. "Missing port in relay begin cell. Closing.");
  2402. tor_free(bcell->address);
  2403. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2404. return -1;
  2405. }
  2406. if (body + rh.length >= nul + 4)
  2407. bcell->flags = ntohl(get_uint32(nul+1));
  2408. return 0;
  2409. }
  2410. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  2411. * an exit hop for the circuit, or we are the origin and it is a
  2412. * rendezvous begin.
  2413. *
  2414. * Launch a new exit connection and initialize things appropriately.
  2415. *
  2416. * If it's a rendezvous stream, call connection_exit_connect() on
  2417. * it.
  2418. *
  2419. * For general streams, call dns_resolve() on it first, and only call
  2420. * connection_exit_connect() if the dns answer is already known.
  2421. *
  2422. * Note that we don't call connection_add() on the new stream! We wait
  2423. * for connection_exit_connect() to do that.
  2424. *
  2425. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  2426. * Else return 0.
  2427. */
  2428. int
  2429. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  2430. {
  2431. edge_connection_t *n_stream;
  2432. relay_header_t rh;
  2433. char *address = NULL;
  2434. uint16_t port = 0;
  2435. or_circuit_t *or_circ = NULL;
  2436. const or_options_t *options = get_options();
  2437. begin_cell_t bcell;
  2438. int r;
  2439. uint8_t end_reason=0;
  2440. assert_circuit_ok(circ);
  2441. if (!CIRCUIT_IS_ORIGIN(circ))
  2442. or_circ = TO_OR_CIRCUIT(circ);
  2443. relay_header_unpack(&rh, cell->payload);
  2444. if (rh.length > RELAY_PAYLOAD_SIZE)
  2445. return -END_CIRC_REASON_TORPROTOCOL;
  2446. /* Note: we have to use relay_send_command_from_edge here, not
  2447. * connection_edge_end or connection_edge_send_command, since those require
  2448. * that we have a stream connected to a circuit, and we don't connect to a
  2449. * circuit until we have a pending/successful resolve. */
  2450. if (!server_mode(options) &&
  2451. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  2452. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2453. "Relay begin cell at non-server. Closing.");
  2454. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2455. END_STREAM_REASON_EXITPOLICY, NULL);
  2456. return 0;
  2457. }
  2458. r = begin_cell_parse(cell, &bcell, &end_reason);
  2459. if (r < -1) {
  2460. return -END_CIRC_REASON_TORPROTOCOL;
  2461. } else if (r == -1) {
  2462. tor_free(bcell.address);
  2463. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);
  2464. return 0;
  2465. }
  2466. if (! bcell.is_begindir) {
  2467. /* Steal reference */
  2468. address = bcell.address;
  2469. port = bcell.port;
  2470. if (or_circ && or_circ->p_chan) {
  2471. if (!options->AllowSingleHopExits &&
  2472. (or_circ->is_first_hop ||
  2473. (!connection_or_digest_is_known_relay(
  2474. or_circ->p_chan->identity_digest) &&
  2475. should_refuse_unknown_exits(options)))) {
  2476. /* Don't let clients use us as a single-hop proxy, unless the user
  2477. * has explicitly allowed that in the config. It attracts attackers
  2478. * and users who'd be better off with, well, single-hop proxies.
  2479. */
  2480. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2481. "Attempt by %s to open a stream %s. Closing.",
  2482. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  2483. or_circ->is_first_hop ? "on first hop of circuit" :
  2484. "from unknown relay");
  2485. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2486. or_circ->is_first_hop ?
  2487. END_STREAM_REASON_TORPROTOCOL :
  2488. END_STREAM_REASON_MISC,
  2489. NULL);
  2490. tor_free(address);
  2491. return 0;
  2492. }
  2493. }
  2494. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2495. if (!directory_permits_begindir_requests(options) ||
  2496. circ->purpose != CIRCUIT_PURPOSE_OR) {
  2497. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2498. END_STREAM_REASON_NOTDIRECTORY, NULL);
  2499. return 0;
  2500. }
  2501. /* Make sure to get the 'real' address of the previous hop: the
  2502. * caller might want to know whether his IP address has changed, and
  2503. * we might already have corrected base_.addr[ess] for the relay's
  2504. * canonical IP address. */
  2505. if (or_circ && or_circ->p_chan)
  2506. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  2507. else
  2508. address = tor_strdup("127.0.0.1");
  2509. port = 1; /* XXXX This value is never actually used anywhere, and there
  2510. * isn't "really" a connection here. But we
  2511. * need to set it to something nonzero. */
  2512. } else {
  2513. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2514. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2515. END_STREAM_REASON_INTERNAL, NULL);
  2516. return 0;
  2517. }
  2518. if (! options->IPv6Exit) {
  2519. /* I don't care if you prefer IPv6; I can't give you any. */
  2520. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  2521. /* If you don't want IPv4, I can't help. */
  2522. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  2523. tor_free(address);
  2524. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2525. END_STREAM_REASON_EXITPOLICY, NULL);
  2526. return 0;
  2527. }
  2528. }
  2529. log_debug(LD_EXIT,"Creating new exit connection.");
  2530. /* The 'AF_INET' here is temporary; we might need to change it later in
  2531. * connection_exit_connect(). */
  2532. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2533. /* Remember the tunneled request ID in the new edge connection, so that
  2534. * we can measure download times. */
  2535. n_stream->dirreq_id = circ->dirreq_id;
  2536. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  2537. n_stream->begincell_flags = bcell.flags;
  2538. n_stream->stream_id = rh.stream_id;
  2539. n_stream->base_.port = port;
  2540. /* leave n_stream->s at -1, because it's not yet valid */
  2541. n_stream->package_window = STREAMWINDOW_START;
  2542. n_stream->deliver_window = STREAMWINDOW_START;
  2543. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  2544. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2545. log_info(LD_REND,"begin is for rendezvous. configuring stream.");
  2546. n_stream->base_.address = tor_strdup("(rendezvous)");
  2547. n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;
  2548. n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
  2549. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  2550. assert_circuit_ok(circ);
  2551. const int r = rend_service_set_connection_addr_port(n_stream, origin_circ);
  2552. if (r < 0) {
  2553. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  2554. n_stream->base_.port);
  2555. /* Send back reason DONE because we want to make hidden service port
  2556. * scanning harder thus instead of returning that the exit policy
  2557. * didn't match, which makes it obvious that the port is closed,
  2558. * return DONE and kill the circuit. That way, a user (malicious or
  2559. * not) needs one circuit per bad port unless it matches the policy of
  2560. * the hidden service. */
  2561. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2562. END_STREAM_REASON_DONE,
  2563. origin_circ->cpath->prev);
  2564. connection_free(TO_CONN(n_stream));
  2565. tor_free(address);
  2566. /* Drop the circuit here since it might be someone deliberately
  2567. * scanning the hidden service ports. Note that this mitigates port
  2568. * scanning by adding more work on the attacker side to successfully
  2569. * scan but does not fully solve it. */
  2570. if (r < -1)
  2571. return END_CIRC_AT_ORIGIN;
  2572. else
  2573. return 0;
  2574. }
  2575. assert_circuit_ok(circ);
  2576. log_debug(LD_REND,"Finished assigning addr/port");
  2577. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  2578. /* add it into the linked list of p_streams on this circuit */
  2579. n_stream->next_stream = origin_circ->p_streams;
  2580. n_stream->on_circuit = circ;
  2581. origin_circ->p_streams = n_stream;
  2582. assert_circuit_ok(circ);
  2583. connection_exit_connect(n_stream);
  2584. /* For path bias: This circuit was used successfully */
  2585. pathbias_mark_use_success(origin_circ);
  2586. tor_free(address);
  2587. return 0;
  2588. }
  2589. tor_strlower(address);
  2590. n_stream->base_.address = address;
  2591. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2592. /* default to failed, change in dns_resolve if it turns out not to fail */
  2593. if (we_are_hibernating()) {
  2594. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2595. END_STREAM_REASON_HIBERNATING, NULL);
  2596. connection_free(TO_CONN(n_stream));
  2597. return 0;
  2598. }
  2599. n_stream->on_circuit = circ;
  2600. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2601. tor_addr_t tmp_addr;
  2602. tor_assert(or_circ);
  2603. if (or_circ->p_chan &&
  2604. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  2605. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  2606. }
  2607. return connection_exit_connect_dir(n_stream);
  2608. }
  2609. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2610. /* send it off to the gethostbyname farm */
  2611. switch (dns_resolve(n_stream)) {
  2612. case 1: /* resolve worked; now n_stream is attached to circ. */
  2613. assert_circuit_ok(circ);
  2614. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2615. connection_exit_connect(n_stream);
  2616. return 0;
  2617. case -1: /* resolve failed */
  2618. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2619. END_STREAM_REASON_RESOLVEFAILED, NULL);
  2620. /* n_stream got freed. don't touch it. */
  2621. break;
  2622. case 0: /* resolve added to pending list */
  2623. assert_circuit_ok(circ);
  2624. break;
  2625. }
  2626. return 0;
  2627. }
  2628. /**
  2629. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  2630. * circuit <b>circ</b>;
  2631. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2632. */
  2633. int
  2634. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2635. {
  2636. edge_connection_t *dummy_conn;
  2637. relay_header_t rh;
  2638. assert_circuit_ok(TO_CIRCUIT(circ));
  2639. relay_header_unpack(&rh, cell->payload);
  2640. if (rh.length > RELAY_PAYLOAD_SIZE)
  2641. return -1;
  2642. /* This 'dummy_conn' only exists to remember the stream ID
  2643. * associated with the resolve request; and to make the
  2644. * implementation of dns.c more uniform. (We really only need to
  2645. * remember the circuit, the stream ID, and the hostname to be
  2646. * resolved; but if we didn't store them in a connection like this,
  2647. * the housekeeping in dns.c would get way more complicated.)
  2648. */
  2649. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2650. dummy_conn->stream_id = rh.stream_id;
  2651. dummy_conn->base_.address = tor_strndup(
  2652. (char*)cell->payload+RELAY_HEADER_SIZE,
  2653. rh.length);
  2654. dummy_conn->base_.port = 0;
  2655. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2656. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  2657. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2658. /* send it off to the gethostbyname farm */
  2659. switch (dns_resolve(dummy_conn)) {
  2660. case -1: /* Impossible to resolve; a resolved cell was sent. */
  2661. /* Connection freed; don't touch it. */
  2662. return 0;
  2663. case 1: /* The result was cached; a resolved cell was sent. */
  2664. if (!dummy_conn->base_.marked_for_close)
  2665. connection_free(TO_CONN(dummy_conn));
  2666. return 0;
  2667. case 0: /* resolve added to pending list */
  2668. assert_circuit_ok(TO_CIRCUIT(circ));
  2669. break;
  2670. }
  2671. return 0;
  2672. }
  2673. /** Connect to conn's specified addr and port. If it worked, conn
  2674. * has now been added to the connection_array.
  2675. *
  2676. * Send back a connected cell. Include the resolved IP of the destination
  2677. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  2678. * streams must not reveal what IP they connected to.)
  2679. */
  2680. void
  2681. connection_exit_connect(edge_connection_t *edge_conn)
  2682. {
  2683. const tor_addr_t *addr;
  2684. uint16_t port;
  2685. connection_t *conn = TO_CONN(edge_conn);
  2686. int socket_error = 0, result;
  2687. if ( (!connection_edge_is_rendezvous_stream(edge_conn) &&
  2688. router_compare_to_my_exit_policy(&edge_conn->base_.addr,
  2689. edge_conn->base_.port)) ||
  2690. (tor_addr_family(&conn->addr) == AF_INET6 &&
  2691. ! get_options()->IPv6Exit)) {
  2692. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  2693. escaped_safe_str_client(conn->address), conn->port);
  2694. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  2695. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2696. connection_free(conn);
  2697. return;
  2698. }
  2699. #ifdef HAVE_SYS_UN_H
  2700. if (conn->socket_family != AF_UNIX) {
  2701. #else
  2702. {
  2703. #endif /* defined(HAVE_SYS_UN_H) */
  2704. addr = &conn->addr;
  2705. port = conn->port;
  2706. if (tor_addr_family(addr) == AF_INET6)
  2707. conn->socket_family = AF_INET6;
  2708. log_debug(LD_EXIT, "about to try connecting");
  2709. result = connection_connect(conn, conn->address,
  2710. addr, port, &socket_error);
  2711. #ifdef HAVE_SYS_UN_H
  2712. } else {
  2713. /*
  2714. * In the AF_UNIX case, we expect to have already had conn->port = 1,
  2715. * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
  2716. * case in connection_handle_listener_read()), and conn->address should
  2717. * have the socket path to connect to.
  2718. */
  2719. tor_assert(conn->address && strlen(conn->address) > 0);
  2720. log_debug(LD_EXIT, "about to try connecting");
  2721. result = connection_connect_unix(conn, conn->address, &socket_error);
  2722. #endif /* defined(HAVE_SYS_UN_H) */
  2723. }
  2724. switch (result) {
  2725. case -1: {
  2726. int reason = errno_to_stream_end_reason(socket_error);
  2727. connection_edge_end(edge_conn, reason);
  2728. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2729. connection_free(conn);
  2730. return;
  2731. }
  2732. case 0:
  2733. conn->state = EXIT_CONN_STATE_CONNECTING;
  2734. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  2735. /* writable indicates finish;
  2736. * readable/error indicates broken link in windows-land. */
  2737. return;
  2738. /* case 1: fall through */
  2739. }
  2740. conn->state = EXIT_CONN_STATE_OPEN;
  2741. if (connection_get_outbuf_len(conn)) {
  2742. /* in case there are any queued data cells, from e.g. optimistic data */
  2743. IF_HAS_NO_BUFFEREVENT(conn)
  2744. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  2745. } else {
  2746. IF_HAS_NO_BUFFEREVENT(conn)
  2747. connection_watch_events(conn, READ_EVENT);
  2748. }
  2749. /* also, deliver a 'connected' cell back through the circuit. */
  2750. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2751. /* don't send an address back! */
  2752. connection_edge_send_command(edge_conn,
  2753. RELAY_COMMAND_CONNECTED,
  2754. NULL, 0);
  2755. } else { /* normal stream */
  2756. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  2757. int connected_payload_len =
  2758. connected_cell_format_payload(connected_payload, &conn->addr,
  2759. edge_conn->address_ttl);
  2760. if (connected_payload_len < 0) {
  2761. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  2762. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2763. connection_free(conn);
  2764. return;
  2765. }
  2766. connection_edge_send_command(edge_conn,
  2767. RELAY_COMMAND_CONNECTED,
  2768. (char*)connected_payload,
  2769. connected_payload_len);
  2770. }
  2771. }
  2772. /** Given an exit conn that should attach to us as a directory server, open a
  2773. * bridge connection with a linked connection pair, create a new directory
  2774. * conn, and join them together. Return 0 on success (or if there was an
  2775. * error we could send back an end cell for). Return -(some circuit end
  2776. * reason) if the circuit needs to be torn down. Either connects
  2777. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  2778. */
  2779. static int
  2780. connection_exit_connect_dir(edge_connection_t *exitconn)
  2781. {
  2782. dir_connection_t *dirconn = NULL;
  2783. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  2784. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  2785. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  2786. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  2787. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  2788. dirconn->base_.port = 0;
  2789. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  2790. dirconn->base_.type = CONN_TYPE_DIR;
  2791. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  2792. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2793. /* Note that the new dir conn belongs to the same tunneled request as
  2794. * the edge conn, so that we can measure download times. */
  2795. dirconn->dirreq_id = exitconn->dirreq_id;
  2796. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  2797. if (connection_add(TO_CONN(exitconn))<0) {
  2798. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2799. connection_free(TO_CONN(exitconn));
  2800. connection_free(TO_CONN(dirconn));
  2801. return 0;
  2802. }
  2803. /* link exitconn to circ, now that we know we can use it. */
  2804. exitconn->next_stream = circ->n_streams;
  2805. circ->n_streams = exitconn;
  2806. if (connection_add(TO_CONN(dirconn))<0) {
  2807. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2808. connection_close_immediate(TO_CONN(exitconn));
  2809. connection_mark_for_close(TO_CONN(exitconn));
  2810. connection_free(TO_CONN(dirconn));
  2811. return 0;
  2812. }
  2813. connection_start_reading(TO_CONN(dirconn));
  2814. connection_start_reading(TO_CONN(exitconn));
  2815. if (connection_edge_send_command(exitconn,
  2816. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  2817. connection_mark_for_close(TO_CONN(exitconn));
  2818. connection_mark_for_close(TO_CONN(dirconn));
  2819. return 0;
  2820. }
  2821. return 0;
  2822. }
  2823. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2824. * it is a general stream.
  2825. */
  2826. int
  2827. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2828. {
  2829. tor_assert(conn);
  2830. if (conn->rend_data)
  2831. return 1;
  2832. return 0;
  2833. }
  2834. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2835. * to exit from it, or 0 if it probably will not allow it.
  2836. * (We might be uncertain if conn's destination address has not yet been
  2837. * resolved.)
  2838. */
  2839. int
  2840. connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
  2841. {
  2842. const or_options_t *options = get_options();
  2843. tor_assert(conn);
  2844. tor_assert(conn->socks_request);
  2845. tor_assert(exit);
  2846. /* If a particular exit node has been requested for the new connection,
  2847. * make sure the exit node of the existing circuit matches exactly.
  2848. */
  2849. if (conn->chosen_exit_name) {
  2850. const node_t *chosen_exit =
  2851. node_get_by_nickname(conn->chosen_exit_name, 1);
  2852. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  2853. exit->identity, DIGEST_LEN)) {
  2854. /* doesn't match */
  2855. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2856. // conn->chosen_exit_name, exit->nickname);
  2857. return 0;
  2858. }
  2859. }
  2860. if (conn->use_begindir) {
  2861. /* Internal directory fetches do not count as exiting. */
  2862. return 1;
  2863. }
  2864. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2865. tor_addr_t addr, *addrp = NULL;
  2866. addr_policy_result_t r;
  2867. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  2868. addrp = &addr;
  2869. } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
  2870. tor_addr_make_null(&addr, AF_INET6);
  2871. addrp = &addr;
  2872. } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
  2873. tor_addr_make_null(&addr, AF_INET);
  2874. addrp = &addr;
  2875. }
  2876. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
  2877. if (r == ADDR_POLICY_REJECTED)
  2878. return 0; /* We know the address, and the exit policy rejects it. */
  2879. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  2880. return 0; /* We don't know the addr, but the exit policy rejects most
  2881. * addresses with this port. Since the user didn't ask for
  2882. * this node, err on the side of caution. */
  2883. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2884. /* Don't send DNS requests to non-exit servers by default. */
  2885. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
  2886. return 0;
  2887. }
  2888. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit)) {
  2889. /* Not a suitable exit. Refuse it. */
  2890. return 0;
  2891. }
  2892. return 1;
  2893. }
  2894. /** If address is of the form "y.onion" with a well-formed handle y:
  2895. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2896. *
  2897. * If address is of the form "x.y.onion" with a well-formed handle x:
  2898. * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2899. *
  2900. * If address is of the form "y.onion" with a badly-formed handle y:
  2901. * Return BAD_HOSTNAME and log a message.
  2902. *
  2903. * If address is of the form "y.exit":
  2904. * Put a NUL after y and return EXIT_HOSTNAME.
  2905. *
  2906. * Otherwise:
  2907. * Return NORMAL_HOSTNAME and change nothing.
  2908. */
  2909. hostname_type_t
  2910. parse_extended_hostname(char *address)
  2911. {
  2912. char *s;
  2913. char *q;
  2914. char query[REND_SERVICE_ID_LEN_BASE32+1];
  2915. s = strrchr(address,'.');
  2916. if (!s)
  2917. return NORMAL_HOSTNAME; /* no dot, thus normal */
  2918. if (!strcmp(s+1,"exit")) {
  2919. *s = 0; /* NUL-terminate it */
  2920. return EXIT_HOSTNAME; /* .exit */
  2921. }
  2922. if (strcmp(s+1,"onion"))
  2923. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  2924. /* so it is .onion */
  2925. *s = 0; /* NUL-terminate it */
  2926. /* locate a 'sub-domain' component, in order to remove it */
  2927. q = strrchr(address, '.');
  2928. if (q == address) {
  2929. goto failed; /* reject sub-domain, as DNS does */
  2930. }
  2931. q = (NULL == q) ? address : q + 1;
  2932. if (strlcpy(query, q, REND_SERVICE_ID_LEN_BASE32+1) >=
  2933. REND_SERVICE_ID_LEN_BASE32+1)
  2934. goto failed;
  2935. if (q != address) {
  2936. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  2937. }
  2938. if (rend_valid_service_id(query)) {
  2939. return ONION_HOSTNAME; /* success */
  2940. }
  2941. failed:
  2942. /* otherwise, return to previous state and return 0 */
  2943. *s = '.';
  2944. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  2945. safe_str_client(address));
  2946. return BAD_HOSTNAME;
  2947. }
  2948. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  2949. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  2950. * at <b>b</b>. */
  2951. static int
  2952. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  2953. {
  2954. if (a == NULL) {
  2955. return (b == NULL);
  2956. } else if (b == NULL) {
  2957. return 0;
  2958. } else if (alen != blen) {
  2959. return 0;
  2960. } else {
  2961. return tor_memeq(a, b, alen);
  2962. }
  2963. }
  2964. /**
  2965. * Return true iff none of the isolation flags and fields in <b>conn</b>
  2966. * should prevent it from being attached to <b>circ</b>.
  2967. */
  2968. int
  2969. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  2970. const origin_circuit_t *circ)
  2971. {
  2972. const uint8_t iso = conn->entry_cfg.isolation_flags;
  2973. const socks_request_t *sr = conn->socks_request;
  2974. /* If circ has never been used for an isolated connection, we can
  2975. * totally use it for this one. */
  2976. if (!circ->isolation_values_set)
  2977. return 1;
  2978. /* If circ has been used for connections having more than one value
  2979. * for some field f, it will have the corresponding bit set in
  2980. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  2981. * in common with iso, then conn must be isolated from at least
  2982. * one stream that has been attached to circ. */
  2983. if ((iso & circ->isolation_flags_mixed) != 0) {
  2984. /* For at least one field where conn is isolated, the circuit
  2985. * already has mixed streams. */
  2986. return 0;
  2987. }
  2988. if (! conn->original_dest_address) {
  2989. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  2990. "having set conn->original_dest_address");
  2991. ((entry_connection_t*)conn)->original_dest_address =
  2992. tor_strdup(conn->socks_request->address);
  2993. }
  2994. if ((iso & ISO_STREAM) &&
  2995. (circ->associated_isolated_stream_global_id !=
  2996. ENTRY_TO_CONN(conn)->global_identifier))
  2997. return 0;
  2998. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  2999. return 0;
  3000. if ((iso & ISO_DESTADDR) &&
  3001. strcasecmp(conn->original_dest_address, circ->dest_address))
  3002. return 0;
  3003. if ((iso & ISO_SOCKSAUTH) &&
  3004. (! memeq_opt(sr->username, sr->usernamelen,
  3005. circ->socks_username, circ->socks_username_len) ||
  3006. ! memeq_opt(sr->password, sr->passwordlen,
  3007. circ->socks_password, circ->socks_password_len)))
  3008. return 0;
  3009. if ((iso & ISO_CLIENTPROTO) &&
  3010. (conn->socks_request->listener_type != circ->client_proto_type ||
  3011. conn->socks_request->socks_version != circ->client_proto_socksver))
  3012. return 0;
  3013. if ((iso & ISO_CLIENTADDR) &&
  3014. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3015. return 0;
  3016. if ((iso & ISO_SESSIONGRP) &&
  3017. conn->entry_cfg.session_group != circ->session_group)
  3018. return 0;
  3019. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  3020. return 0;
  3021. return 1;
  3022. }
  3023. /**
  3024. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  3025. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  3026. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  3027. * a bitfield of isolation flags that we would have to set in
  3028. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  3029. * <b>circ</b> has had no streams attached to it.
  3030. */
  3031. int
  3032. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  3033. origin_circuit_t *circ,
  3034. int dry_run)
  3035. {
  3036. const socks_request_t *sr = conn->socks_request;
  3037. if (! conn->original_dest_address) {
  3038. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  3039. "having set conn->original_dest_address");
  3040. ((entry_connection_t*)conn)->original_dest_address =
  3041. tor_strdup(conn->socks_request->address);
  3042. }
  3043. if (!circ->isolation_values_set) {
  3044. if (dry_run)
  3045. return -1;
  3046. circ->associated_isolated_stream_global_id =
  3047. ENTRY_TO_CONN(conn)->global_identifier;
  3048. circ->dest_port = conn->socks_request->port;
  3049. circ->dest_address = tor_strdup(conn->original_dest_address);
  3050. circ->client_proto_type = conn->socks_request->listener_type;
  3051. circ->client_proto_socksver = conn->socks_request->socks_version;
  3052. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  3053. circ->session_group = conn->entry_cfg.session_group;
  3054. circ->nym_epoch = conn->nym_epoch;
  3055. circ->socks_username = sr->username ?
  3056. tor_memdup(sr->username, sr->usernamelen) : NULL;
  3057. circ->socks_password = sr->password ?
  3058. tor_memdup(sr->password, sr->passwordlen) : NULL;
  3059. circ->socks_username_len = sr->usernamelen;
  3060. circ->socks_password_len = sr->passwordlen;
  3061. circ->isolation_values_set = 1;
  3062. return 0;
  3063. } else {
  3064. uint8_t mixed = 0;
  3065. if (conn->socks_request->port != circ->dest_port)
  3066. mixed |= ISO_DESTPORT;
  3067. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  3068. mixed |= ISO_DESTADDR;
  3069. if (!memeq_opt(sr->username, sr->usernamelen,
  3070. circ->socks_username, circ->socks_username_len) ||
  3071. !memeq_opt(sr->password, sr->passwordlen,
  3072. circ->socks_password, circ->socks_password_len))
  3073. mixed |= ISO_SOCKSAUTH;
  3074. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  3075. conn->socks_request->socks_version != circ->client_proto_socksver))
  3076. mixed |= ISO_CLIENTPROTO;
  3077. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3078. mixed |= ISO_CLIENTADDR;
  3079. if (conn->entry_cfg.session_group != circ->session_group)
  3080. mixed |= ISO_SESSIONGRP;
  3081. if (conn->nym_epoch != circ->nym_epoch)
  3082. mixed |= ISO_NYM_EPOCH;
  3083. if (dry_run)
  3084. return mixed;
  3085. if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
  3086. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  3087. "isolation flags.");
  3088. }
  3089. circ->isolation_flags_mixed |= mixed;
  3090. return 0;
  3091. }
  3092. }
  3093. /**
  3094. * Clear the isolation settings on <b>circ</b>.
  3095. *
  3096. * This only works on an open circuit that has never had a stream attached to
  3097. * it, and whose isolation settings are hypothetical. (We set hypothetical
  3098. * isolation settings on circuits as we're launching them, so that we
  3099. * know whether they can handle more streams or whether we need to launch
  3100. * even more circuits. Once the circuit is open, if it turns out that
  3101. * we no longer have any streams to attach to it, we clear the isolation flags
  3102. * and data so that other streams can have a chance.)
  3103. */
  3104. void
  3105. circuit_clear_isolation(origin_circuit_t *circ)
  3106. {
  3107. if (circ->isolation_any_streams_attached) {
  3108. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  3109. return;
  3110. }
  3111. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  3112. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  3113. "circuit");
  3114. return;
  3115. }
  3116. circ->isolation_values_set = 0;
  3117. circ->isolation_flags_mixed = 0;
  3118. circ->associated_isolated_stream_global_id = 0;
  3119. circ->client_proto_type = 0;
  3120. circ->client_proto_socksver = 0;
  3121. circ->dest_port = 0;
  3122. tor_addr_make_unspec(&circ->client_addr);
  3123. tor_free(circ->dest_address);
  3124. circ->session_group = -1;
  3125. circ->nym_epoch = 0;
  3126. if (circ->socks_username) {
  3127. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  3128. tor_free(circ->socks_username);
  3129. }
  3130. if (circ->socks_password) {
  3131. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  3132. tor_free(circ->socks_password);
  3133. }
  3134. circ->socks_username_len = circ->socks_password_len = 0;
  3135. }