connection_edge.c 151 KB

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