connection_edge.c 160 KB

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