connection_edge.c 164 KB

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