connection_edge.c 117 KB

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