connection_edge.c 161 KB

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