connection_edge.c 140 KB

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