connection_edge.c 140 KB

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