connection_edge.c 107 KB

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