connection_edge.c 164 KB

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