connection_edge.c 145 KB

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