connection_edge.c 106 KB

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