connection_edge.c 154 KB

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