connection_edge.c 140 KB

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