connection_edge.c 148 KB

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