connection_edge.c 154 KB

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