connection_edge.c 102 KB

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