connection_edge.c 106 KB

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