connection_edge.c 116 KB

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