connection_edge.c 154 KB

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