connection_edge.c 132 KB

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