connection_edge.c 148 KB

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