connection_edge.c 116 KB

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