connection_edge.c 118 KB

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