connection_edge.c 149 KB

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