connection_edge.c 151 KB

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