connection_edge.c 154 KB

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