connection_edge.c 117 KB

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