connection_edge.c 153 KB

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