connection_edge.c 152 KB

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