connection_edge.c 140 KB

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