connection_edge.c 115 KB

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