rendservice.c 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendservice.c
  6. * \brief The hidden-service side of rendezvous functionality.
  7. **/
  8. #define RENDSERVICE_PRIVATE
  9. #include "or.h"
  10. #include "circpathbias.h"
  11. #include "circuitbuild.h"
  12. #include "circuitlist.h"
  13. #include "circuituse.h"
  14. #include "config.h"
  15. #include "control.h"
  16. #include "directory.h"
  17. #include "hs_common.h"
  18. #include "main.h"
  19. #include "networkstatus.h"
  20. #include "nodelist.h"
  21. #include "policies.h"
  22. #include "rendclient.h"
  23. #include "rendcommon.h"
  24. #include "rendservice.h"
  25. #include "router.h"
  26. #include "relay.h"
  27. #include "rephist.h"
  28. #include "replaycache.h"
  29. #include "routerlist.h"
  30. #include "routerparse.h"
  31. #include "routerset.h"
  32. struct rend_service_t;
  33. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  34. const char *pk_digest);
  35. static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
  36. static rend_intro_point_t *find_expiring_intro_point(
  37. struct rend_service_t *service, origin_circuit_t *circ);
  38. static extend_info_t *find_rp_for_intro(
  39. const rend_intro_cell_t *intro,
  40. char **err_msg_out);
  41. static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
  42. static int intro_point_should_expire_now(rend_intro_point_t *intro,
  43. time_t now);
  44. static int rend_service_derive_key_digests(struct rend_service_t *s);
  45. static int rend_service_load_keys(struct rend_service_t *s);
  46. static int rend_service_load_auth_keys(struct rend_service_t *s,
  47. const char *hfname);
  48. static struct rend_service_t *rend_service_get_by_pk_digest(
  49. const char* digest);
  50. static struct rend_service_t *rend_service_get_by_service_id(const char *id);
  51. static const char *rend_service_escaped_dir(
  52. const struct rend_service_t *s);
  53. static ssize_t rend_service_parse_intro_for_v0_or_v1(
  54. rend_intro_cell_t *intro,
  55. const uint8_t *buf,
  56. size_t plaintext_len,
  57. char **err_msg_out);
  58. static ssize_t rend_service_parse_intro_for_v2(
  59. rend_intro_cell_t *intro,
  60. const uint8_t *buf,
  61. size_t plaintext_len,
  62. char **err_msg_out);
  63. static ssize_t rend_service_parse_intro_for_v3(
  64. rend_intro_cell_t *intro,
  65. const uint8_t *buf,
  66. size_t plaintext_len,
  67. char **err_msg_out);
  68. static int rend_service_check_private_dir(const or_options_t *options,
  69. const rend_service_t *s,
  70. int create);
  71. static int rend_service_check_private_dir_impl(const or_options_t *options,
  72. const rend_service_t *s,
  73. int create);
  74. static const smartlist_t* rend_get_service_list(
  75. const smartlist_t* substitute_service_list);
  76. static smartlist_t* rend_get_service_list_mutable(
  77. smartlist_t* substitute_service_list);
  78. /** Represents the mapping from a virtual port of a rendezvous service to
  79. * a real port on some IP.
  80. */
  81. struct rend_service_port_config_s {
  82. /* The incoming HS virtual port we're mapping */
  83. uint16_t virtual_port;
  84. /* Is this an AF_UNIX port? */
  85. unsigned int is_unix_addr:1;
  86. /* The outgoing TCP port to use, if !is_unix_addr */
  87. uint16_t real_port;
  88. /* The outgoing IPv4 or IPv6 address to use, if !is_unix_addr */
  89. tor_addr_t real_addr;
  90. /* The socket path to connect to, if is_unix_addr */
  91. char unix_addr[FLEXIBLE_ARRAY_MEMBER];
  92. };
  93. /** Try to maintain this many intro points per service by default. */
  94. #define NUM_INTRO_POINTS_DEFAULT 3
  95. /** Maximum number of intro points per service. */
  96. #define NUM_INTRO_POINTS_MAX 10
  97. /** Number of extra intro points we launch if our set of intro nodes is
  98. * empty. See proposal 155, section 4. */
  99. #define NUM_INTRO_POINTS_EXTRA 2
  100. /** If we can't build our intro circuits, don't retry for this long. */
  101. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  102. /** Don't try to build more than this many circuits before giving up
  103. * for a while.*/
  104. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  105. /** How many times will a hidden service operator attempt to connect to
  106. * a requested rendezvous point before giving up? */
  107. #define MAX_REND_FAILURES 1
  108. /** How many seconds should we spend trying to connect to a requested
  109. * rendezvous point before giving up? */
  110. #define MAX_REND_TIMEOUT 30
  111. /* Hidden service directory file names:
  112. * new file names should be added to rend_service_add_filenames_to_list()
  113. * for sandboxing purposes. */
  114. static const char *private_key_fname = "private_key";
  115. static const char *hostname_fname = "hostname";
  116. static const char *client_keys_fname = "client_keys";
  117. static const char *sos_poison_fname = "onion_service_non_anonymous";
  118. /** A list of rend_service_t's for services run on this OP.
  119. */
  120. static smartlist_t *rend_service_list = NULL;
  121. /* Like rend_get_service_list_mutable, but returns a read-only list. */
  122. static const smartlist_t*
  123. rend_get_service_list(const smartlist_t* substitute_service_list)
  124. {
  125. /* It is safe to cast away the const here, because
  126. * rend_get_service_list_mutable does not actually modify the list */
  127. return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
  128. }
  129. /* Return a mutable list of hidden services.
  130. * If substitute_service_list is not NULL, return it.
  131. * Otherwise, check if the global rend_service_list is non-NULL, and if so,
  132. * return it.
  133. * Otherwise, log a BUG message and return NULL.
  134. * */
  135. static smartlist_t*
  136. rend_get_service_list_mutable(smartlist_t* substitute_service_list)
  137. {
  138. if (substitute_service_list) {
  139. return substitute_service_list;
  140. }
  141. /* If no special service list is provided, then just use the global one. */
  142. if (BUG(!rend_service_list)) {
  143. /* No global HS list, which is a programmer error. */
  144. return NULL;
  145. }
  146. return rend_service_list;
  147. }
  148. /** Tells if onion service <b>s</b> is ephemeral.
  149. */
  150. static unsigned int
  151. rend_service_is_ephemeral(const struct rend_service_t *s)
  152. {
  153. return (s->directory == NULL);
  154. }
  155. /** Returns a escaped string representation of the service, <b>s</b>.
  156. */
  157. static const char *
  158. rend_service_escaped_dir(const struct rend_service_t *s)
  159. {
  160. return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
  161. }
  162. /** Return the number of rendezvous services we have configured. */
  163. int
  164. num_rend_services(void)
  165. {
  166. if (!rend_service_list)
  167. return 0;
  168. return smartlist_len(rend_service_list);
  169. }
  170. /** Helper: free storage held by a single service authorized client entry. */
  171. void
  172. rend_authorized_client_free(rend_authorized_client_t *client)
  173. {
  174. if (!client)
  175. return;
  176. if (client->client_key)
  177. crypto_pk_free(client->client_key);
  178. if (client->client_name)
  179. memwipe(client->client_name, 0, strlen(client->client_name));
  180. tor_free(client->client_name);
  181. memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
  182. tor_free(client);
  183. }
  184. /** Helper for strmap_free. */
  185. static void
  186. rend_authorized_client_strmap_item_free(void *authorized_client)
  187. {
  188. rend_authorized_client_free(authorized_client);
  189. }
  190. /** Release the storage held by <b>service</b>.
  191. */
  192. STATIC void
  193. rend_service_free(rend_service_t *service)
  194. {
  195. if (!service)
  196. return;
  197. tor_free(service->directory);
  198. if (service->ports) {
  199. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
  200. rend_service_port_config_free(p));
  201. smartlist_free(service->ports);
  202. }
  203. if (service->private_key)
  204. crypto_pk_free(service->private_key);
  205. if (service->intro_nodes) {
  206. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  207. rend_intro_point_free(intro););
  208. smartlist_free(service->intro_nodes);
  209. }
  210. if (service->expiring_nodes) {
  211. SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
  212. rend_intro_point_free(intro););
  213. smartlist_free(service->expiring_nodes);
  214. }
  215. rend_service_descriptor_free(service->desc);
  216. if (service->clients) {
  217. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  218. rend_authorized_client_free(c););
  219. smartlist_free(service->clients);
  220. }
  221. if (service->accepted_intro_dh_parts) {
  222. replaycache_free(service->accepted_intro_dh_parts);
  223. }
  224. tor_free(service);
  225. }
  226. /** Release all the storage held in rend_service_list.
  227. */
  228. void
  229. rend_service_free_all(void)
  230. {
  231. if (!rend_service_list)
  232. return;
  233. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  234. rend_service_free(ptr));
  235. smartlist_free(rend_service_list);
  236. rend_service_list = NULL;
  237. }
  238. /** Validate <b>service</b> and add it to <b>service_list</b>, or to
  239. * the global rend_service_list if <b>service_list</b> is NULL.
  240. * Return 0 on success. On failure, free <b>service</b> and return -1.
  241. * Takes ownership of <b>service</b>.
  242. */
  243. static int
  244. rend_add_service(smartlist_t *service_list, rend_service_t *service)
  245. {
  246. int i;
  247. rend_service_port_config_t *p;
  248. tor_assert(service);
  249. smartlist_t *s_list = rend_get_service_list_mutable(service_list);
  250. /* We must have a service list, even if it's a temporary one, so we can
  251. * check for duplicate services */
  252. if (BUG(!s_list)) {
  253. return -1;
  254. }
  255. service->intro_nodes = smartlist_new();
  256. service->expiring_nodes = smartlist_new();
  257. if (service->max_streams_per_circuit < 0) {
  258. log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
  259. "streams per circuit.",
  260. rend_service_escaped_dir(service));
  261. rend_service_free(service);
  262. return -1;
  263. }
  264. if (service->max_streams_close_circuit < 0 ||
  265. service->max_streams_close_circuit > 1) {
  266. log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
  267. "max streams handling.",
  268. rend_service_escaped_dir(service));
  269. rend_service_free(service);
  270. return -1;
  271. }
  272. if (service->auth_type != REND_NO_AUTH &&
  273. (!service->clients ||
  274. smartlist_len(service->clients) == 0)) {
  275. log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but no "
  276. "clients.",
  277. rend_service_escaped_dir(service));
  278. rend_service_free(service);
  279. return -1;
  280. }
  281. if (!service->ports || !smartlist_len(service->ports)) {
  282. log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
  283. rend_service_escaped_dir(service));
  284. rend_service_free(service);
  285. return -1;
  286. } else {
  287. int dupe = 0;
  288. /* XXX This duplicate check has two problems:
  289. *
  290. * a) It's O(n^2), but the same comment from the bottom of
  291. * rend_config_services() should apply.
  292. *
  293. * b) We only compare directory paths as strings, so we can't
  294. * detect two distinct paths that specify the same directory
  295. * (which can arise from symlinks, case-insensitivity, bind
  296. * mounts, etc.).
  297. *
  298. * It also can't detect that two separate Tor instances are trying
  299. * to use the same HiddenServiceDir; for that, we would need a
  300. * lock file. But this is enough to detect a simple mistake that
  301. * at least one person has actually made.
  302. */
  303. tor_assert(s_list);
  304. if (!rend_service_is_ephemeral(service)) {
  305. /* Skip dupe for ephemeral services. */
  306. SMARTLIST_FOREACH(s_list, rend_service_t*, ptr,
  307. dupe = dupe ||
  308. !strcmp(ptr->directory, service->directory));
  309. if (dupe) {
  310. log_warn(LD_REND, "Another hidden service is already configured for "
  311. "directory %s.",
  312. rend_service_escaped_dir(service));
  313. rend_service_free(service);
  314. return -1;
  315. }
  316. }
  317. log_debug(LD_REND,"Configuring service with directory %s",
  318. rend_service_escaped_dir(service));
  319. for (i = 0; i < smartlist_len(service->ports); ++i) {
  320. p = smartlist_get(service->ports, i);
  321. if (!(p->is_unix_addr)) {
  322. log_debug(LD_REND,
  323. "Service maps port %d to %s",
  324. p->virtual_port,
  325. fmt_addrport(&p->real_addr, p->real_port));
  326. } else {
  327. #ifdef HAVE_SYS_UN_H
  328. log_debug(LD_REND,
  329. "Service maps port %d to socket at \"%s\"",
  330. p->virtual_port, p->unix_addr);
  331. #else
  332. log_warn(LD_BUG,
  333. "Service maps port %d to an AF_UNIX socket, but we "
  334. "have no AF_UNIX support on this platform. This is "
  335. "probably a bug.",
  336. p->virtual_port);
  337. rend_service_free(service);
  338. return -1;
  339. #endif /* defined(HAVE_SYS_UN_H) */
  340. }
  341. }
  342. /* The service passed all the checks */
  343. tor_assert(s_list);
  344. smartlist_add(s_list, service);
  345. return 0;
  346. }
  347. /* NOTREACHED */
  348. }
  349. /** Return a new rend_service_port_config_t with its path set to
  350. * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
  351. static rend_service_port_config_t *
  352. rend_service_port_config_new(const char *socket_path)
  353. {
  354. if (!socket_path)
  355. return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
  356. const size_t pathlen = strlen(socket_path) + 1;
  357. rend_service_port_config_t *conf =
  358. tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
  359. memcpy(conf->unix_addr, socket_path, pathlen);
  360. conf->is_unix_addr = 1;
  361. return conf;
  362. }
  363. /** Parses a virtual-port to real-port/socket mapping separated by
  364. * the provided separator and returns a new rend_service_port_config_t,
  365. * or NULL and an optional error string on failure.
  366. *
  367. * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
  368. *
  369. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  370. */
  371. rend_service_port_config_t *
  372. rend_service_parse_port_config(const char *string, const char *sep,
  373. char **err_msg_out)
  374. {
  375. smartlist_t *sl;
  376. int virtport;
  377. int realport = 0;
  378. uint16_t p;
  379. tor_addr_t addr;
  380. rend_service_port_config_t *result = NULL;
  381. unsigned int is_unix_addr = 0;
  382. const char *socket_path = NULL;
  383. char *err_msg = NULL;
  384. char *addrport = NULL;
  385. sl = smartlist_new();
  386. smartlist_split_string(sl, string, sep,
  387. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  388. if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
  389. err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
  390. goto err;
  391. }
  392. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  393. if (!virtport) {
  394. tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
  395. "port configuration", escaped(smartlist_get(sl,0)));
  396. goto err;
  397. }
  398. if (smartlist_len(sl) == 1) {
  399. /* No addr:port part; use default. */
  400. realport = virtport;
  401. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  402. } else {
  403. int ret;
  404. const char *addrport_element = smartlist_get(sl,1);
  405. const char *rest = NULL;
  406. int is_unix;
  407. ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
  408. &is_unix, &rest);
  409. if (ret < 0) {
  410. tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
  411. "service configuration", addrport_element);
  412. goto err;
  413. }
  414. if (is_unix) {
  415. socket_path = addrport;
  416. is_unix_addr = 1;
  417. } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
  418. /* else try it as an IP:port pair if it has a : or . in it */
  419. if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
  420. err_msg = tor_strdup("Unparseable address in hidden service port "
  421. "configuration.");
  422. goto err;
  423. }
  424. realport = p?p:virtport;
  425. } else {
  426. /* No addr:port, no addr -- must be port. */
  427. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  428. if (!realport) {
  429. tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
  430. "hidden service port configuration.",
  431. escaped(addrport));
  432. goto err;
  433. }
  434. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  435. }
  436. }
  437. /* Allow room for unix_addr */
  438. result = rend_service_port_config_new(socket_path);
  439. result->virtual_port = virtport;
  440. result->is_unix_addr = is_unix_addr;
  441. if (!is_unix_addr) {
  442. result->real_port = realport;
  443. tor_addr_copy(&result->real_addr, &addr);
  444. result->unix_addr[0] = '\0';
  445. }
  446. err:
  447. tor_free(addrport);
  448. if (err_msg_out != NULL) {
  449. *err_msg_out = err_msg;
  450. } else {
  451. tor_free(err_msg);
  452. }
  453. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  454. smartlist_free(sl);
  455. return result;
  456. }
  457. /** Release all storage held in a rend_service_port_config_t. */
  458. void
  459. rend_service_port_config_free(rend_service_port_config_t *p)
  460. {
  461. tor_free(p);
  462. }
  463. /* Check the directory for <b>service</b>, and add the service to
  464. * <b>service_list</b>, or to the global list if <b>service_list</b> is NULL.
  465. * Only add the service to the list if <b>validate_only</b> is false.
  466. * If <b>validate_only</b> is true, free the service.
  467. * If <b>service</b> is NULL, ignore it, and return 0.
  468. * Returns 0 on success, and -1 on failure.
  469. * Takes ownership of <b>service</b>, either freeing it, or adding it to the
  470. * global service list.
  471. */
  472. STATIC int
  473. rend_service_check_dir_and_add(smartlist_t *service_list,
  474. const or_options_t *options,
  475. rend_service_t *service,
  476. int validate_only)
  477. {
  478. if (!service) {
  479. /* It is ok for a service to be NULL, this means there are no services */
  480. return 0;
  481. }
  482. if (rend_service_check_private_dir(options, service, !validate_only)
  483. < 0) {
  484. rend_service_free(service);
  485. return -1;
  486. }
  487. smartlist_t *s_list = rend_get_service_list_mutable(service_list);
  488. /* We must have a service list, even if it's a temporary one, so we can
  489. * check for duplicate services */
  490. if (BUG(!s_list)) {
  491. return -1;
  492. }
  493. return rend_add_service(s_list, service);
  494. }
  495. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  496. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  497. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  498. * normal, but don't actually change the configured services.)
  499. */
  500. int
  501. rend_config_services(const or_options_t *options, int validate_only)
  502. {
  503. config_line_t *line;
  504. rend_service_t *service = NULL;
  505. rend_service_port_config_t *portcfg;
  506. smartlist_t *old_service_list = NULL;
  507. smartlist_t *temp_service_list = NULL;
  508. int ok = 0;
  509. /* Use a temporary service list, so that we can check the new services'
  510. * consistency with each other */
  511. temp_service_list = smartlist_new();
  512. for (line = options->RendConfigLines; line; line = line->next) {
  513. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  514. /* register the service we just finished parsing
  515. * this code registers every service except the last one parsed,
  516. * which is registered below the loop */
  517. if (rend_service_check_dir_and_add(temp_service_list, options, service,
  518. validate_only) < 0) {
  519. return -1;
  520. }
  521. service = tor_malloc_zero(sizeof(rend_service_t));
  522. service->directory = tor_strdup(line->value);
  523. service->ports = smartlist_new();
  524. service->intro_period_started = time(NULL);
  525. service->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
  526. continue;
  527. }
  528. if (!service) {
  529. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  530. line->key);
  531. rend_service_free(service);
  532. return -1;
  533. }
  534. if (!strcasecmp(line->key, "HiddenServicePort")) {
  535. char *err_msg = NULL;
  536. portcfg = rend_service_parse_port_config(line->value, " ", &err_msg);
  537. if (!portcfg) {
  538. if (err_msg)
  539. log_warn(LD_CONFIG, "%s", err_msg);
  540. tor_free(err_msg);
  541. rend_service_free(service);
  542. return -1;
  543. }
  544. tor_assert(!err_msg);
  545. smartlist_add(service->ports, portcfg);
  546. } else if (!strcasecmp(line->key, "HiddenServiceAllowUnknownPorts")) {
  547. service->allow_unknown_ports = (int)tor_parse_long(line->value,
  548. 10, 0, 1, &ok, NULL);
  549. if (!ok) {
  550. log_warn(LD_CONFIG,
  551. "HiddenServiceAllowUnknownPorts should be 0 or 1, not %s",
  552. line->value);
  553. rend_service_free(service);
  554. return -1;
  555. }
  556. log_info(LD_CONFIG,
  557. "HiddenServiceAllowUnknownPorts=%d for %s",
  558. (int)service->allow_unknown_ports,
  559. rend_service_escaped_dir(service));
  560. } else if (!strcasecmp(line->key,
  561. "HiddenServiceDirGroupReadable")) {
  562. service->dir_group_readable = (int)tor_parse_long(line->value,
  563. 10, 0, 1, &ok, NULL);
  564. if (!ok) {
  565. log_warn(LD_CONFIG,
  566. "HiddenServiceDirGroupReadable should be 0 or 1, not %s",
  567. line->value);
  568. rend_service_free(service);
  569. return -1;
  570. }
  571. log_info(LD_CONFIG,
  572. "HiddenServiceDirGroupReadable=%d for %s",
  573. service->dir_group_readable,
  574. rend_service_escaped_dir(service));
  575. } else if (!strcasecmp(line->key, "HiddenServiceMaxStreams")) {
  576. service->max_streams_per_circuit = (int)tor_parse_long(line->value,
  577. 10, 0, 65535, &ok, NULL);
  578. if (!ok) {
  579. log_warn(LD_CONFIG,
  580. "HiddenServiceMaxStreams should be between 0 and %d, not %s",
  581. 65535, line->value);
  582. rend_service_free(service);
  583. return -1;
  584. }
  585. log_info(LD_CONFIG,
  586. "HiddenServiceMaxStreams=%d for %s",
  587. service->max_streams_per_circuit,
  588. rend_service_escaped_dir(service));
  589. } else if (!strcasecmp(line->key, "HiddenServiceMaxStreamsCloseCircuit")) {
  590. service->max_streams_close_circuit = (int)tor_parse_long(line->value,
  591. 10, 0, 1, &ok, NULL);
  592. if (!ok) {
  593. log_warn(LD_CONFIG,
  594. "HiddenServiceMaxStreamsCloseCircuit should be 0 or 1, "
  595. "not %s",
  596. line->value);
  597. rend_service_free(service);
  598. return -1;
  599. }
  600. log_info(LD_CONFIG,
  601. "HiddenServiceMaxStreamsCloseCircuit=%d for %s",
  602. (int)service->max_streams_close_circuit,
  603. rend_service_escaped_dir(service));
  604. } else if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
  605. service->n_intro_points_wanted =
  606. (unsigned int) tor_parse_long(line->value, 10,
  607. NUM_INTRO_POINTS_DEFAULT,
  608. NUM_INTRO_POINTS_MAX, &ok, NULL);
  609. if (!ok) {
  610. log_warn(LD_CONFIG,
  611. "HiddenServiceNumIntroductionPoints "
  612. "should be between %d and %d, not %s",
  613. NUM_INTRO_POINTS_DEFAULT, NUM_INTRO_POINTS_MAX,
  614. line->value);
  615. rend_service_free(service);
  616. return -1;
  617. }
  618. log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
  619. service->n_intro_points_wanted,
  620. rend_service_escaped_dir(service));
  621. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  622. /* Parse auth type and comma-separated list of client names and add a
  623. * rend_authorized_client_t for each client to the service's list
  624. * of authorized clients. */
  625. smartlist_t *type_names_split, *clients;
  626. const char *authname;
  627. int num_clients;
  628. if (service->auth_type != REND_NO_AUTH) {
  629. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  630. "lines for a single service.");
  631. rend_service_free(service);
  632. return -1;
  633. }
  634. type_names_split = smartlist_new();
  635. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  636. if (smartlist_len(type_names_split) < 1) {
  637. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  638. "should have been prevented when parsing the "
  639. "configuration.");
  640. smartlist_free(type_names_split);
  641. rend_service_free(service);
  642. return -1;
  643. }
  644. authname = smartlist_get(type_names_split, 0);
  645. if (!strcasecmp(authname, "basic")) {
  646. service->auth_type = REND_BASIC_AUTH;
  647. } else if (!strcasecmp(authname, "stealth")) {
  648. service->auth_type = REND_STEALTH_AUTH;
  649. } else {
  650. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  651. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  652. "are recognized.",
  653. (char *) smartlist_get(type_names_split, 0));
  654. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  655. smartlist_free(type_names_split);
  656. rend_service_free(service);
  657. return -1;
  658. }
  659. service->clients = smartlist_new();
  660. if (smartlist_len(type_names_split) < 2) {
  661. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  662. "auth-type '%s', but no client names.",
  663. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  664. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  665. smartlist_free(type_names_split);
  666. continue;
  667. }
  668. clients = smartlist_new();
  669. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  670. ",", SPLIT_SKIP_SPACE, 0);
  671. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  672. smartlist_free(type_names_split);
  673. /* Remove duplicate client names. */
  674. num_clients = smartlist_len(clients);
  675. smartlist_sort_strings(clients);
  676. smartlist_uniq_strings(clients);
  677. if (smartlist_len(clients) < num_clients) {
  678. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  679. "duplicate client name(s); removing.",
  680. num_clients - smartlist_len(clients));
  681. num_clients = smartlist_len(clients);
  682. }
  683. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  684. {
  685. rend_authorized_client_t *client;
  686. if (!rend_valid_client_name(client_name)) {
  687. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  688. "illegal client name: '%s'. Names must be "
  689. "between 1 and %d characters and contain "
  690. "only [A-Za-z0-9+_-].",
  691. client_name, REND_CLIENTNAME_MAX_LEN);
  692. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  693. smartlist_free(clients);
  694. rend_service_free(service);
  695. return -1;
  696. }
  697. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  698. client->client_name = tor_strdup(client_name);
  699. smartlist_add(service->clients, client);
  700. log_debug(LD_REND, "Adding client name '%s'", client_name);
  701. }
  702. SMARTLIST_FOREACH_END(client_name);
  703. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  704. smartlist_free(clients);
  705. /* Ensure maximum number of clients. */
  706. if ((service->auth_type == REND_BASIC_AUTH &&
  707. smartlist_len(service->clients) > 512) ||
  708. (service->auth_type == REND_STEALTH_AUTH &&
  709. smartlist_len(service->clients) > 16)) {
  710. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  711. "client authorization entries, but only a "
  712. "maximum of %d entries is allowed for "
  713. "authorization type '%s'.",
  714. smartlist_len(service->clients),
  715. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  716. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  717. rend_service_free(service);
  718. return -1;
  719. }
  720. } else {
  721. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  722. if (strcmp(line->value, "2")) {
  723. log_warn(LD_CONFIG,
  724. "The only supported HiddenServiceVersion is 2.");
  725. rend_service_free(service);
  726. return -1;
  727. }
  728. }
  729. }
  730. /* register the final service after we have finished parsing all services
  731. * this code only registers the last service, other services are registered
  732. * within the loop. It is ok for this service to be NULL, it is ignored. */
  733. if (rend_service_check_dir_and_add(temp_service_list, options, service,
  734. validate_only) < 0) {
  735. return -1;
  736. }
  737. /* Free the newly added services if validating */
  738. if (validate_only) {
  739. SMARTLIST_FOREACH(temp_service_list, rend_service_t *, ptr,
  740. rend_service_free(ptr));
  741. smartlist_free(temp_service_list);
  742. temp_service_list = NULL;
  743. return 0;
  744. }
  745. /* Otherwise, use the newly added services as the new service list
  746. * Since we have now replaced the global service list, from this point on we
  747. * must succeed, or die trying. */
  748. old_service_list = rend_service_list;
  749. rend_service_list = temp_service_list;
  750. temp_service_list = NULL;
  751. /* If this is a reload and there were hidden services configured before,
  752. * keep the introduction points that are still needed and close the
  753. * other ones. */
  754. if (old_service_list && !validate_only) {
  755. smartlist_t *surviving_services = smartlist_new();
  756. /* Preserve the existing ephemeral services.
  757. *
  758. * This is the ephemeral service equivalent of the "Copy introduction
  759. * points to new services" block, except there's no copy required since
  760. * the service structure isn't regenerated.
  761. *
  762. * After this is done, all ephemeral services will be:
  763. * * Removed from old_service_list, so the equivalent non-ephemeral code
  764. * will not attempt to preserve them.
  765. * * Added to the new rend_service_list (that previously only had the
  766. * services listed in the configuration).
  767. * * Added to surviving_services, which is the list of services that
  768. * will NOT have their intro point closed.
  769. */
  770. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  771. if (rend_service_is_ephemeral(old)) {
  772. SMARTLIST_DEL_CURRENT(old_service_list, old);
  773. smartlist_add(surviving_services, old);
  774. smartlist_add(rend_service_list, old);
  775. }
  776. });
  777. /* Copy introduction points to new services. */
  778. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  779. * probably ok? */
  780. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, new) {
  781. SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
  782. if (BUG(rend_service_is_ephemeral(new)) ||
  783. BUG(rend_service_is_ephemeral(old))) {
  784. continue;
  785. }
  786. if (BUG(!new->directory) || BUG(!old->directory) ||
  787. strcmp(old->directory, new->directory)) {
  788. continue;
  789. }
  790. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  791. smartlist_clear(old->intro_nodes);
  792. smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
  793. smartlist_clear(old->expiring_nodes);
  794. smartlist_add(surviving_services, old);
  795. break;
  796. } SMARTLIST_FOREACH_END(old);
  797. } SMARTLIST_FOREACH_END(new);
  798. /* Close introduction circuits of services we don't serve anymore. */
  799. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  800. * so we could just iterate over the list of services to close, but
  801. * once again, this isn't critical-path code. */
  802. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  803. if (!circ->marked_for_close &&
  804. circ->state == CIRCUIT_STATE_OPEN &&
  805. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  806. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  807. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  808. int keep_it = 0;
  809. tor_assert(oc->rend_data);
  810. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  811. if (rend_circuit_pk_digest_eq(oc, (uint8_t *) ptr->pk_digest)) {
  812. keep_it = 1;
  813. break;
  814. }
  815. });
  816. if (keep_it)
  817. continue;
  818. log_info(LD_REND, "Closing intro point %s for service %s.",
  819. safe_str_client(extend_info_describe(
  820. oc->build_state->chosen_exit)),
  821. rend_data_get_address(oc->rend_data));
  822. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  823. /* XXXX Is there another reason we should use here? */
  824. }
  825. }
  826. SMARTLIST_FOREACH_END(circ);
  827. smartlist_free(surviving_services);
  828. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  829. rend_service_free(ptr));
  830. smartlist_free(old_service_list);
  831. }
  832. return 0;
  833. }
  834. /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
  835. * client authorization <b>auth_type</b> and an optional list of
  836. * rend_authorized_client_t in <b>auth_clients</b>, with
  837. * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
  838. * and circuit closure on max streams being exceeded set by
  839. * <b>max_streams_close_circuit</b>.
  840. *
  841. * Ownership of pk, ports, and auth_clients is passed to this routine.
  842. * Regardless of success/failure, callers should not touch these values
  843. * after calling this routine, and may assume that correct cleanup has
  844. * been done on failure.
  845. *
  846. * Return an appropriate rend_service_add_ephemeral_status_t.
  847. */
  848. rend_service_add_ephemeral_status_t
  849. rend_service_add_ephemeral(crypto_pk_t *pk,
  850. smartlist_t *ports,
  851. int max_streams_per_circuit,
  852. int max_streams_close_circuit,
  853. rend_auth_type_t auth_type,
  854. smartlist_t *auth_clients,
  855. char **service_id_out)
  856. {
  857. *service_id_out = NULL;
  858. /* Allocate the service structure, and initialize the key, and key derived
  859. * parameters.
  860. */
  861. rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
  862. s->directory = NULL; /* This indicates the service is ephemeral. */
  863. s->private_key = pk;
  864. s->auth_type = auth_type;
  865. s->clients = auth_clients;
  866. s->ports = ports;
  867. s->intro_period_started = time(NULL);
  868. s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
  869. s->max_streams_per_circuit = max_streams_per_circuit;
  870. s->max_streams_close_circuit = max_streams_close_circuit;
  871. if (rend_service_derive_key_digests(s) < 0) {
  872. rend_service_free(s);
  873. return RSAE_BADPRIVKEY;
  874. }
  875. if (!s->ports || smartlist_len(s->ports) == 0) {
  876. log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
  877. rend_service_free(s);
  878. return RSAE_BADVIRTPORT;
  879. }
  880. if (s->auth_type != REND_NO_AUTH &&
  881. (!s->clients || smartlist_len(s->clients) == 0)) {
  882. log_warn(LD_CONFIG, "At least one authorized client must be specified.");
  883. rend_service_free(s);
  884. return RSAE_BADAUTH;
  885. }
  886. /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
  887. * it's not, see #14828.
  888. */
  889. if (rend_service_get_by_pk_digest(s->pk_digest)) {
  890. log_warn(LD_CONFIG, "Onion Service private key collides with an "
  891. "existing service.");
  892. rend_service_free(s);
  893. return RSAE_ADDREXISTS;
  894. }
  895. if (rend_service_get_by_service_id(s->service_id)) {
  896. log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
  897. rend_service_free(s);
  898. return RSAE_ADDREXISTS;
  899. }
  900. /* Initialize the service. */
  901. if (rend_add_service(NULL, s)) {
  902. return RSAE_INTERNAL;
  903. }
  904. *service_id_out = tor_strdup(s->service_id);
  905. log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
  906. return RSAE_OKAY;
  907. }
  908. /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
  909. * success, and -1 on failure.
  910. */
  911. int
  912. rend_service_del_ephemeral(const char *service_id)
  913. {
  914. rend_service_t *s;
  915. if (!rend_valid_service_id(service_id)) {
  916. log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
  917. return -1;
  918. }
  919. if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
  920. log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
  921. "removal.");
  922. return -1;
  923. }
  924. if (!rend_service_is_ephemeral(s)) {
  925. log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
  926. return -1;
  927. }
  928. /* Kill the intro point circuit for the Onion Service, and remove it from
  929. * the list. Closing existing connections is the application's problem.
  930. *
  931. * XXX: As with the comment in rend_config_services(), a nice abstraction
  932. * would be ideal here, but for now just duplicate the code.
  933. */
  934. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  935. if (!circ->marked_for_close &&
  936. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  937. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  938. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  939. tor_assert(oc->rend_data);
  940. if (!rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
  941. continue;
  942. }
  943. log_debug(LD_REND, "Closing intro point %s for service %s.",
  944. safe_str_client(extend_info_describe(
  945. oc->build_state->chosen_exit)),
  946. rend_data_get_address(oc->rend_data));
  947. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  948. }
  949. } SMARTLIST_FOREACH_END(circ);
  950. smartlist_remove(rend_service_list, s);
  951. rend_service_free(s);
  952. log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
  953. return 0;
  954. }
  955. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  956. * the other fields in service.
  957. */
  958. static void
  959. rend_service_update_descriptor(rend_service_t *service)
  960. {
  961. rend_service_descriptor_t *d;
  962. origin_circuit_t *circ;
  963. int i;
  964. rend_service_descriptor_free(service->desc);
  965. service->desc = NULL;
  966. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  967. d->pk = crypto_pk_dup_key(service->private_key);
  968. d->timestamp = time(NULL);
  969. d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
  970. d->intro_nodes = smartlist_new();
  971. /* Support intro protocols 2 and 3. */
  972. d->protocols = (1 << 2) + (1 << 3);
  973. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  974. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  975. rend_intro_point_t *intro_desc;
  976. /* This intro point won't be listed in the descriptor... */
  977. intro_svc->listed_in_last_desc = 0;
  978. circ = find_intro_circuit(intro_svc, service->pk_digest);
  979. if (!circ || circ->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  980. /* This intro point's circuit isn't finished yet. Don't list it. */
  981. continue;
  982. }
  983. /* ...unless this intro point is listed in the descriptor. */
  984. intro_svc->listed_in_last_desc = 1;
  985. /* We have an entirely established intro circuit. Publish it in
  986. * our descriptor. */
  987. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  988. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  989. if (intro_svc->intro_key)
  990. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  991. smartlist_add(d->intro_nodes, intro_desc);
  992. if (intro_svc->time_published == -1) {
  993. /* We are publishing this intro point in a descriptor for the
  994. * first time -- note the current time in the service's copy of
  995. * the intro point. */
  996. intro_svc->time_published = time(NULL);
  997. }
  998. }
  999. }
  1000. /* Allocate and return a string containing the path to file_name in
  1001. * service->directory. Asserts that service has a directory.
  1002. * This function will never return NULL.
  1003. * The caller must free this path. */
  1004. static char *
  1005. rend_service_path(const rend_service_t *service, const char *file_name)
  1006. {
  1007. char *file_path = NULL;
  1008. tor_assert(service->directory);
  1009. /* Can never fail: asserts rather than leaving file_path NULL. */
  1010. tor_asprintf(&file_path, "%s%s%s",
  1011. service->directory, PATH_SEPARATOR, file_name);
  1012. return file_path;
  1013. }
  1014. /* Allocate and return a string containing the path to the single onion
  1015. * service poison file in service->directory. Asserts that service has a
  1016. * directory.
  1017. * The caller must free this path. */
  1018. STATIC char *
  1019. rend_service_sos_poison_path(const rend_service_t *service)
  1020. {
  1021. return rend_service_path(service, sos_poison_fname);
  1022. }
  1023. /** Return True if hidden services <b>service</b> has been poisoned by single
  1024. * onion mode. */
  1025. static int
  1026. service_is_single_onion_poisoned(const rend_service_t *service)
  1027. {
  1028. char *poison_fname = NULL;
  1029. file_status_t fstatus;
  1030. /* Passing a NULL service is a bug */
  1031. if (BUG(!service)) {
  1032. return 0;
  1033. }
  1034. if (rend_service_is_ephemeral(service)) {
  1035. return 0;
  1036. }
  1037. poison_fname = rend_service_sos_poison_path(service);
  1038. fstatus = file_status(poison_fname);
  1039. tor_free(poison_fname);
  1040. /* If this fname is occupied, the hidden service has been poisoned.
  1041. * fstatus can be FN_ERROR if the service directory does not exist, in that
  1042. * case, there is obviously no private key. */
  1043. if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
  1044. return 1;
  1045. }
  1046. return 0;
  1047. }
  1048. /* Return 1 if the private key file for service exists and has a non-zero size,
  1049. * and 0 otherwise. */
  1050. static int
  1051. rend_service_private_key_exists(const rend_service_t *service)
  1052. {
  1053. char *private_key_path = rend_service_path(service, private_key_fname);
  1054. const file_status_t private_key_status = file_status(private_key_path);
  1055. tor_free(private_key_path);
  1056. /* Only non-empty regular private key files could have been used before.
  1057. * fstatus can be FN_ERROR if the service directory does not exist, in that
  1058. * case, there is obviously no private key. */
  1059. return private_key_status == FN_FILE;
  1060. }
  1061. /** Check the single onion service poison state of the directory for s:
  1062. * - If the service is poisoned, and we are in Single Onion Mode,
  1063. * return 0,
  1064. * - If the service is not poisoned, and we are not in Single Onion Mode,
  1065. * return 0,
  1066. * - Otherwise, the poison state is invalid: the service was created in one
  1067. * mode, and is being used in the other, return -1.
  1068. * Hidden service directories without keys are always considered consistent.
  1069. * They will be poisoned after their directory is created (if needed). */
  1070. STATIC int
  1071. rend_service_verify_single_onion_poison(const rend_service_t* s,
  1072. const or_options_t* options)
  1073. {
  1074. /* Passing a NULL service is a bug */
  1075. if (BUG(!s)) {
  1076. return -1;
  1077. }
  1078. /* Ephemeral services are checked at ADD_ONION time */
  1079. if (BUG(rend_service_is_ephemeral(s))) {
  1080. return -1;
  1081. }
  1082. /* Service is expected to have a directory */
  1083. if (BUG(!s->directory)) {
  1084. return -1;
  1085. }
  1086. /* Services without keys are always ok - their keys will only ever be used
  1087. * in the current mode */
  1088. if (!rend_service_private_key_exists(s)) {
  1089. return 0;
  1090. }
  1091. /* The key has been used before in a different mode */
  1092. if (service_is_single_onion_poisoned(s) !=
  1093. rend_service_non_anonymous_mode_enabled(options)) {
  1094. return -1;
  1095. }
  1096. /* The key exists and is consistent with the current mode */
  1097. return 0;
  1098. }
  1099. /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
  1100. * the hidden service directory for s that marks it as a single onion service.
  1101. * Tor must be in single onion mode before calling this function, and the
  1102. * service directory must already have been created.
  1103. * Returns 0 when a directory is successfully poisoned, or if it is already
  1104. * poisoned. Returns -1 on a failure to read the directory or write the poison
  1105. * file, or if there is an existing private key file in the directory. (The
  1106. * service should have been poisoned when the key was created.) */
  1107. static int
  1108. poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
  1109. const or_options_t* options)
  1110. {
  1111. /* Passing a NULL service is a bug */
  1112. if (BUG(!service)) {
  1113. return -1;
  1114. }
  1115. /* We must only poison directories if we're in Single Onion mode */
  1116. tor_assert(rend_service_non_anonymous_mode_enabled(options));
  1117. int fd;
  1118. int retval = -1;
  1119. char *poison_fname = NULL;
  1120. if (rend_service_is_ephemeral(service)) {
  1121. log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
  1122. return 0;
  1123. }
  1124. /* Make sure we're only poisoning new hidden service directories */
  1125. if (rend_service_private_key_exists(service)) {
  1126. log_warn(LD_BUG, "Tried to single onion poison a service directory after "
  1127. "the private key was created.");
  1128. return -1;
  1129. }
  1130. /* Make sure the directory was created before calling this function. */
  1131. if (BUG(rend_service_check_private_dir_impl(options, service, 0) < 0))
  1132. return -1;
  1133. poison_fname = rend_service_sos_poison_path(service);
  1134. switch (file_status(poison_fname)) {
  1135. case FN_DIR:
  1136. case FN_ERROR:
  1137. log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
  1138. poison_fname);
  1139. goto done;
  1140. case FN_FILE: /* single onion poison file already exists. NOP. */
  1141. case FN_EMPTY: /* single onion poison file already exists. NOP. */
  1142. log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
  1143. poison_fname);
  1144. break;
  1145. case FN_NOENT:
  1146. fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
  1147. if (fd < 0) {
  1148. log_warn(LD_FS, "Could not create single onion poison file %s",
  1149. poison_fname);
  1150. goto done;
  1151. }
  1152. close(fd);
  1153. break;
  1154. default:
  1155. tor_assert(0);
  1156. }
  1157. retval = 0;
  1158. done:
  1159. tor_free(poison_fname);
  1160. return retval;
  1161. }
  1162. /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
  1163. * hidden services. If s is new, we should mark its hidden service
  1164. * directory appropriately so that it is never launched as a location-private
  1165. * hidden service. (New directories don't have private key files.)
  1166. * Return 0 on success, -1 on fail. */
  1167. STATIC int
  1168. rend_service_poison_new_single_onion_dir(const rend_service_t *s,
  1169. const or_options_t* options)
  1170. {
  1171. /* Passing a NULL service is a bug */
  1172. if (BUG(!s)) {
  1173. return -1;
  1174. }
  1175. /* We must only poison directories if we're in Single Onion mode */
  1176. tor_assert(rend_service_non_anonymous_mode_enabled(options));
  1177. /* Ephemeral services aren't allowed in non-anonymous mode */
  1178. if (BUG(rend_service_is_ephemeral(s))) {
  1179. return -1;
  1180. }
  1181. /* Service is expected to have a directory */
  1182. if (BUG(!s->directory)) {
  1183. return -1;
  1184. }
  1185. if (!rend_service_private_key_exists(s)) {
  1186. if (poison_new_single_onion_hidden_service_dir_impl(s, options)
  1187. < 0) {
  1188. return -1;
  1189. }
  1190. }
  1191. return 0;
  1192. }
  1193. /** Load and/or generate private keys for all hidden services, possibly
  1194. * including keys for client authorization.
  1195. * If a <b>service_list</b> is provided, treat it as the list of hidden
  1196. * services (used in unittests). Otherwise, require that rend_service_list is
  1197. * not NULL.
  1198. * Return 0 on success, -1 on failure. */
  1199. int
  1200. rend_service_load_all_keys(const smartlist_t *service_list)
  1201. {
  1202. /* Use service_list for unit tests */
  1203. const smartlist_t *s_list = rend_get_service_list(service_list);
  1204. if (BUG(!s_list)) {
  1205. return -1;
  1206. }
  1207. SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
  1208. if (s->private_key)
  1209. continue;
  1210. log_info(LD_REND, "Loading hidden-service keys from %s",
  1211. rend_service_escaped_dir(s));
  1212. if (rend_service_load_keys(s) < 0)
  1213. return -1;
  1214. } SMARTLIST_FOREACH_END(s);
  1215. return 0;
  1216. }
  1217. /** Add to <b>lst</b> every filename used by <b>s</b>. */
  1218. static void
  1219. rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
  1220. {
  1221. tor_assert(lst);
  1222. tor_assert(s);
  1223. tor_assert(s->directory);
  1224. smartlist_add(lst, rend_service_path(s, private_key_fname));
  1225. smartlist_add(lst, rend_service_path(s, hostname_fname));
  1226. smartlist_add(lst, rend_service_path(s, client_keys_fname));
  1227. smartlist_add(lst, rend_service_sos_poison_path(s));
  1228. }
  1229. /** Add to <b>open_lst</b> every filename used by a configured hidden service,
  1230. * and to <b>stat_lst</b> every directory used by a configured hidden
  1231. * service */
  1232. void
  1233. rend_services_add_filenames_to_lists(smartlist_t *open_lst,
  1234. smartlist_t *stat_lst)
  1235. {
  1236. if (!rend_service_list)
  1237. return;
  1238. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  1239. if (!rend_service_is_ephemeral(s)) {
  1240. rend_service_add_filenames_to_list(open_lst, s);
  1241. smartlist_add_strdup(stat_lst, s->directory);
  1242. }
  1243. } SMARTLIST_FOREACH_END(s);
  1244. }
  1245. /** Derive all rend_service_t internal material based on the service's key.
  1246. * Returns 0 on sucess, -1 on failure.
  1247. */
  1248. static int
  1249. rend_service_derive_key_digests(struct rend_service_t *s)
  1250. {
  1251. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  1252. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  1253. return -1;
  1254. }
  1255. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  1256. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  1257. return -1;
  1258. }
  1259. return 0;
  1260. }
  1261. /* Implements the directory check from rend_service_check_private_dir,
  1262. * without doing the single onion poison checks. */
  1263. static int
  1264. rend_service_check_private_dir_impl(const or_options_t *options,
  1265. const rend_service_t *s,
  1266. int create)
  1267. {
  1268. cpd_check_t check_opts = CPD_NONE;
  1269. if (create) {
  1270. check_opts |= CPD_CREATE;
  1271. } else {
  1272. check_opts |= CPD_CHECK_MODE_ONLY;
  1273. check_opts |= CPD_CHECK;
  1274. }
  1275. if (s->dir_group_readable) {
  1276. check_opts |= CPD_GROUP_READ;
  1277. }
  1278. /* Check/create directory */
  1279. if (check_private_dir(s->directory, check_opts, options->User) < 0) {
  1280. log_warn(LD_REND, "Checking service directory %s failed.", s->directory);
  1281. return -1;
  1282. }
  1283. return 0;
  1284. }
  1285. /** Make sure that the directory for <b>s</b> is private, using the config in
  1286. * <b>options</b>.
  1287. * If <b>create</b> is true:
  1288. * - if the directory exists, change permissions if needed,
  1289. * - if the directory does not exist, create it with the correct permissions.
  1290. * If <b>create</b> is false:
  1291. * - if the directory exists, check permissions,
  1292. * - if the directory does not exist, check if we think we can create it.
  1293. * Return 0 on success, -1 on failure. */
  1294. static int
  1295. rend_service_check_private_dir(const or_options_t *options,
  1296. const rend_service_t *s,
  1297. int create)
  1298. {
  1299. /* Passing a NULL service is a bug */
  1300. if (BUG(!s)) {
  1301. return -1;
  1302. }
  1303. /* Check/create directory */
  1304. if (rend_service_check_private_dir_impl(options, s, create) < 0) {
  1305. return -1;
  1306. }
  1307. /* Check if the hidden service key exists, and was created in a different
  1308. * single onion service mode, and refuse to launch if it has.
  1309. * This is safe to call even when create is false, as it ignores missing
  1310. * keys and directories: they are always valid.
  1311. */
  1312. if (rend_service_verify_single_onion_poison(s, options) < 0) {
  1313. /* We can't use s->service_id here, as the key may not have been loaded */
  1314. log_warn(LD_GENERAL, "We are configured with "
  1315. "HiddenServiceNonAnonymousMode %d, but the hidden "
  1316. "service key in directory %s was created in %s mode. "
  1317. "This is not allowed.",
  1318. rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
  1319. rend_service_escaped_dir(s),
  1320. rend_service_non_anonymous_mode_enabled(options) ?
  1321. "an anonymous" : "a non-anonymous"
  1322. );
  1323. return -1;
  1324. }
  1325. /* Poison new single onion directories immediately after they are created,
  1326. * so that we never accidentally launch non-anonymous hidden services
  1327. * thinking they are anonymous. Any keys created later will end up with the
  1328. * correct poisoning state.
  1329. */
  1330. if (create && rend_service_non_anonymous_mode_enabled(options)) {
  1331. static int logged_warning = 0;
  1332. if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
  1333. log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
  1334. ".");
  1335. return -1;
  1336. }
  1337. if (!logged_warning) {
  1338. /* The keys for these services are linked to the server IP address */
  1339. log_notice(LD_REND, "The configured onion service directories have been "
  1340. "used in single onion mode. They can not be used for "
  1341. "anonymous hidden services.");
  1342. logged_warning = 1;
  1343. }
  1344. }
  1345. return 0;
  1346. }
  1347. /** Load and/or generate private keys for the hidden service <b>s</b>,
  1348. * possibly including keys for client authorization. Return 0 on success, -1
  1349. * on failure. */
  1350. static int
  1351. rend_service_load_keys(rend_service_t *s)
  1352. {
  1353. char *fname = NULL;
  1354. char buf[128];
  1355. /* Make sure the directory was created and single onion poisoning was
  1356. * checked before calling this function */
  1357. if (BUG(rend_service_check_private_dir(get_options(), s, 0) < 0))
  1358. goto err;
  1359. /* Load key */
  1360. fname = rend_service_path(s, private_key_fname);
  1361. s->private_key = init_key_from_file(fname, 1, LOG_ERR, 0);
  1362. if (!s->private_key)
  1363. goto err;
  1364. if (rend_service_derive_key_digests(s) < 0)
  1365. goto err;
  1366. tor_free(fname);
  1367. /* Create service file */
  1368. fname = rend_service_path(s, hostname_fname);
  1369. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  1370. if (write_str_to_file(fname,buf,0)<0) {
  1371. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  1372. goto err;
  1373. }
  1374. #ifndef _WIN32
  1375. if (s->dir_group_readable) {
  1376. /* Also verify hostname file created with group read. */
  1377. if (chmod(fname, 0640))
  1378. log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
  1379. fname);
  1380. }
  1381. #endif
  1382. /* If client authorization is configured, load or generate keys. */
  1383. if (s->auth_type != REND_NO_AUTH) {
  1384. if (rend_service_load_auth_keys(s, fname) < 0) {
  1385. goto err;
  1386. }
  1387. }
  1388. int r = 0;
  1389. goto done;
  1390. err:
  1391. r = -1;
  1392. done:
  1393. memwipe(buf, 0, sizeof(buf));
  1394. tor_free(fname);
  1395. return r;
  1396. }
  1397. /** Load and/or generate client authorization keys for the hidden service
  1398. * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
  1399. * -1 on failure. */
  1400. static int
  1401. rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
  1402. {
  1403. int r = 0;
  1404. char *cfname = NULL;
  1405. char *client_keys_str = NULL;
  1406. strmap_t *parsed_clients = strmap_new();
  1407. FILE *cfile, *hfile;
  1408. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  1409. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  1410. char service_id[16+1];
  1411. char buf[1500];
  1412. /* Load client keys and descriptor cookies, if available. */
  1413. cfname = rend_service_path(s, client_keys_fname);
  1414. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  1415. if (client_keys_str) {
  1416. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  1417. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  1418. "be parsed.");
  1419. goto err;
  1420. } else {
  1421. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  1422. strmap_size(parsed_clients));
  1423. }
  1424. }
  1425. /* Prepare client_keys and hostname files. */
  1426. if (!(cfile = start_writing_to_stdio_file(cfname,
  1427. OPEN_FLAGS_REPLACE | O_TEXT,
  1428. 0600, &open_cfile))) {
  1429. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  1430. escaped(cfname));
  1431. goto err;
  1432. }
  1433. if (!(hfile = start_writing_to_stdio_file(hfname,
  1434. OPEN_FLAGS_REPLACE | O_TEXT,
  1435. 0600, &open_hfile))) {
  1436. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
  1437. goto err;
  1438. }
  1439. /* Either use loaded keys for configured clients or generate new
  1440. * ones if a client is new. */
  1441. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
  1442. rend_authorized_client_t *parsed =
  1443. strmap_get(parsed_clients, client->client_name);
  1444. int written;
  1445. size_t len;
  1446. /* Copy descriptor cookie from parsed entry or create new one. */
  1447. if (parsed) {
  1448. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  1449. REND_DESC_COOKIE_LEN);
  1450. } else {
  1451. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1452. }
  1453. /* For compatibility with older tor clients, this does not
  1454. * truncate the padding characters, unlike rend_auth_encode_cookie. */
  1455. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  1456. (char *) client->descriptor_cookie,
  1457. REND_DESC_COOKIE_LEN, 0) < 0) {
  1458. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  1459. goto err;
  1460. }
  1461. /* Copy client key from parsed entry or create new one if required. */
  1462. if (parsed && parsed->client_key) {
  1463. client->client_key = crypto_pk_dup_key(parsed->client_key);
  1464. } else if (s->auth_type == REND_STEALTH_AUTH) {
  1465. /* Create private key for client. */
  1466. crypto_pk_t *prkey = NULL;
  1467. if (!(prkey = crypto_pk_new())) {
  1468. log_warn(LD_BUG,"Error constructing client key");
  1469. goto err;
  1470. }
  1471. if (crypto_pk_generate_key(prkey)) {
  1472. log_warn(LD_BUG,"Error generating client key");
  1473. crypto_pk_free(prkey);
  1474. goto err;
  1475. }
  1476. if (crypto_pk_check_key(prkey) <= 0) {
  1477. log_warn(LD_BUG,"Generated client key seems invalid");
  1478. crypto_pk_free(prkey);
  1479. goto err;
  1480. }
  1481. client->client_key = prkey;
  1482. }
  1483. /* Add entry to client_keys file. */
  1484. written = tor_snprintf(buf, sizeof(buf),
  1485. "client-name %s\ndescriptor-cookie %s\n",
  1486. client->client_name, desc_cook_out);
  1487. if (written < 0) {
  1488. log_warn(LD_BUG, "Could not write client entry.");
  1489. goto err;
  1490. }
  1491. if (client->client_key) {
  1492. char *client_key_out = NULL;
  1493. if (crypto_pk_write_private_key_to_string(client->client_key,
  1494. &client_key_out, &len) != 0) {
  1495. log_warn(LD_BUG, "Internal error: "
  1496. "crypto_pk_write_private_key_to_string() failed.");
  1497. goto err;
  1498. }
  1499. if (rend_get_service_id(client->client_key, service_id)<0) {
  1500. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  1501. /*
  1502. * len is string length, not buffer length, but last byte is NUL
  1503. * anyway.
  1504. */
  1505. memwipe(client_key_out, 0, len);
  1506. tor_free(client_key_out);
  1507. goto err;
  1508. }
  1509. written = tor_snprintf(buf + written, sizeof(buf) - written,
  1510. "client-key\n%s", client_key_out);
  1511. memwipe(client_key_out, 0, len);
  1512. tor_free(client_key_out);
  1513. if (written < 0) {
  1514. log_warn(LD_BUG, "Could not write client entry.");
  1515. goto err;
  1516. }
  1517. } else {
  1518. strlcpy(service_id, s->service_id, sizeof(service_id));
  1519. }
  1520. if (fputs(buf, cfile) < 0) {
  1521. log_warn(LD_FS, "Could not append client entry to file: %s",
  1522. strerror(errno));
  1523. goto err;
  1524. }
  1525. /* Add line to hostname file. This is not the same encoding as in
  1526. * client_keys. */
  1527. char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
  1528. s->auth_type);
  1529. if (!encoded_cookie) {
  1530. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  1531. goto err;
  1532. }
  1533. tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
  1534. service_id, encoded_cookie, client->client_name);
  1535. memwipe(encoded_cookie, 0, strlen(encoded_cookie));
  1536. tor_free(encoded_cookie);
  1537. if (fputs(buf, hfile)<0) {
  1538. log_warn(LD_FS, "Could not append host entry to file: %s",
  1539. strerror(errno));
  1540. goto err;
  1541. }
  1542. } SMARTLIST_FOREACH_END(client);
  1543. finish_writing_to_file(open_cfile);
  1544. finish_writing_to_file(open_hfile);
  1545. goto done;
  1546. err:
  1547. r = -1;
  1548. if (open_cfile)
  1549. abort_writing_to_file(open_cfile);
  1550. if (open_hfile)
  1551. abort_writing_to_file(open_hfile);
  1552. done:
  1553. if (client_keys_str) {
  1554. memwipe(client_keys_str, 0, strlen(client_keys_str));
  1555. tor_free(client_keys_str);
  1556. }
  1557. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  1558. if (cfname) {
  1559. memwipe(cfname, 0, strlen(cfname));
  1560. tor_free(cfname);
  1561. }
  1562. /* Clear stack buffers that held key-derived material. */
  1563. memwipe(buf, 0, sizeof(buf));
  1564. memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
  1565. memwipe(service_id, 0, sizeof(service_id));
  1566. return r;
  1567. }
  1568. /** Return the service whose public key has a digest of <b>digest</b>, or
  1569. * NULL if no such service exists.
  1570. */
  1571. static rend_service_t *
  1572. rend_service_get_by_pk_digest(const char* digest)
  1573. {
  1574. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  1575. if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
  1576. return s);
  1577. return NULL;
  1578. }
  1579. /** Return the service whose service id is <b>id</b>, or NULL if no such
  1580. * service exists.
  1581. */
  1582. static struct rend_service_t *
  1583. rend_service_get_by_service_id(const char *id)
  1584. {
  1585. tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
  1586. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
  1587. if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
  1588. return s;
  1589. });
  1590. return NULL;
  1591. }
  1592. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  1593. * to have good uptime. Else return 0.
  1594. */
  1595. static int
  1596. rend_service_requires_uptime(rend_service_t *service)
  1597. {
  1598. int i;
  1599. rend_service_port_config_t *p;
  1600. for (i=0; i < smartlist_len(service->ports); ++i) {
  1601. p = smartlist_get(service->ports, i);
  1602. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  1603. p->virtual_port))
  1604. return 1;
  1605. }
  1606. return 0;
  1607. }
  1608. /** Check client authorization of a given <b>descriptor_cookie</b> of
  1609. * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
  1610. * and 0 for failure. */
  1611. static int
  1612. rend_check_authorization(rend_service_t *service,
  1613. const char *descriptor_cookie,
  1614. size_t cookie_len)
  1615. {
  1616. rend_authorized_client_t *auth_client = NULL;
  1617. tor_assert(service);
  1618. tor_assert(descriptor_cookie);
  1619. if (!service->clients) {
  1620. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  1621. "authorized clients configured.");
  1622. return 0;
  1623. }
  1624. if (cookie_len != REND_DESC_COOKIE_LEN) {
  1625. log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
  1626. "%lu bytes. Dropping cell.",
  1627. (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
  1628. return 0;
  1629. }
  1630. /* Look up client authorization by descriptor cookie. */
  1631. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  1632. if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
  1633. REND_DESC_COOKIE_LEN)) {
  1634. auth_client = client;
  1635. break;
  1636. }
  1637. });
  1638. if (!auth_client) {
  1639. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  1640. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  1641. descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
  1642. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  1643. "Dropping cell!",
  1644. descriptor_cookie_base64);
  1645. return 0;
  1646. }
  1647. /* Allow the request. */
  1648. log_info(LD_REND, "Client %s authorized for service %s.",
  1649. auth_client->client_name, service->service_id);
  1650. return 1;
  1651. }
  1652. /* Can this service make a direct connection to ei?
  1653. * It must be a single onion service, and the firewall rules must allow ei. */
  1654. static int
  1655. rend_service_use_direct_connection(const or_options_t* options,
  1656. const extend_info_t* ei)
  1657. {
  1658. /* We'll connect directly all reachable addresses, whether preferred or not.
  1659. * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
  1660. * ignored, because pref_only is 0. */
  1661. return (rend_service_allow_non_anonymous_connection(options) &&
  1662. fascist_firewall_allows_address_addr(&ei->addr, ei->port,
  1663. FIREWALL_OR_CONNECTION, 0, 0));
  1664. }
  1665. /* Like rend_service_use_direct_connection, but to a node. */
  1666. static int
  1667. rend_service_use_direct_connection_node(const or_options_t* options,
  1668. const node_t* node)
  1669. {
  1670. /* We'll connect directly all reachable addresses, whether preferred or not.
  1671. */
  1672. return (rend_service_allow_non_anonymous_connection(options) &&
  1673. fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
  1674. }
  1675. /******
  1676. * Handle cells
  1677. ******/
  1678. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  1679. * rendezvous point.
  1680. */
  1681. int
  1682. rend_service_receive_introduction(origin_circuit_t *circuit,
  1683. const uint8_t *request,
  1684. size_t request_len)
  1685. {
  1686. /* Global status stuff */
  1687. int status = 0, result;
  1688. const or_options_t *options = get_options();
  1689. char *err_msg = NULL;
  1690. int err_msg_severity = LOG_WARN;
  1691. const char *stage_descr = NULL, *rend_pk_digest;
  1692. int reason = END_CIRC_REASON_TORPROTOCOL;
  1693. /* Service/circuit/key stuff we can learn before parsing */
  1694. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1695. rend_service_t *service = NULL;
  1696. rend_intro_point_t *intro_point = NULL;
  1697. crypto_pk_t *intro_key = NULL;
  1698. /* Parsed cell */
  1699. rend_intro_cell_t *parsed_req = NULL;
  1700. /* Rendezvous point */
  1701. extend_info_t *rp = NULL;
  1702. /* XXX not handled yet */
  1703. char buf[RELAY_PAYLOAD_SIZE];
  1704. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  1705. int i;
  1706. crypto_dh_t *dh = NULL;
  1707. origin_circuit_t *launched = NULL;
  1708. crypt_path_t *cpath = NULL;
  1709. char hexcookie[9];
  1710. int circ_needs_uptime;
  1711. time_t now = time(NULL);
  1712. time_t elapsed;
  1713. int replay;
  1714. /* Do some initial validation and logging before we parse the cell */
  1715. if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1716. log_warn(LD_PROTOCOL,
  1717. "Got an INTRODUCE2 over a non-introduction circuit %u.",
  1718. (unsigned) circuit->base_.n_circ_id);
  1719. goto err;
  1720. }
  1721. assert_circ_anonymity_ok(circuit, options);
  1722. tor_assert(circuit->rend_data);
  1723. /* XXX: This is version 2 specific (only one supported). */
  1724. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  1725. /* We'll use this in a bazillion log messages */
  1726. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1727. rend_pk_digest, REND_SERVICE_ID_LEN);
  1728. /* look up service depending on circuit. */
  1729. service = rend_service_get_by_pk_digest(rend_pk_digest);
  1730. if (!service) {
  1731. log_warn(LD_BUG,
  1732. "Internal error: Got an INTRODUCE2 cell on an intro "
  1733. "circ for an unrecognized service %s.",
  1734. escaped(serviceid));
  1735. goto err;
  1736. }
  1737. intro_point = find_intro_point(circuit);
  1738. if (intro_point == NULL) {
  1739. intro_point = find_expiring_intro_point(service, circuit);
  1740. if (intro_point == NULL) {
  1741. log_warn(LD_BUG,
  1742. "Internal error: Got an INTRODUCE2 cell on an "
  1743. "intro circ (for service %s) with no corresponding "
  1744. "rend_intro_point_t.",
  1745. escaped(serviceid));
  1746. goto err;
  1747. }
  1748. }
  1749. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
  1750. escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
  1751. /* use intro key instead of service key. */
  1752. intro_key = circuit->intro_key;
  1753. tor_free(err_msg);
  1754. stage_descr = NULL;
  1755. stage_descr = "early parsing";
  1756. /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
  1757. parsed_req =
  1758. rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
  1759. if (!parsed_req) {
  1760. goto log_error;
  1761. } else if (err_msg) {
  1762. log_info(LD_REND, "%s on circ %u.", err_msg,
  1763. (unsigned)circuit->base_.n_circ_id);
  1764. tor_free(err_msg);
  1765. }
  1766. /* make sure service replay caches are present */
  1767. if (!service->accepted_intro_dh_parts) {
  1768. service->accepted_intro_dh_parts =
  1769. replaycache_new(REND_REPLAY_TIME_INTERVAL,
  1770. REND_REPLAY_TIME_INTERVAL);
  1771. }
  1772. if (!intro_point->accepted_intro_rsa_parts) {
  1773. intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
  1774. }
  1775. /* check for replay of PK-encrypted portion. */
  1776. replay = replaycache_add_test_and_elapsed(
  1777. intro_point->accepted_intro_rsa_parts,
  1778. parsed_req->ciphertext, parsed_req->ciphertext_len,
  1779. &elapsed);
  1780. if (replay) {
  1781. log_warn(LD_REND,
  1782. "Possible replay detected! We received an "
  1783. "INTRODUCE2 cell with same PK-encrypted part %d "
  1784. "seconds ago. Dropping cell.",
  1785. (int)elapsed);
  1786. goto err;
  1787. }
  1788. stage_descr = "decryption";
  1789. /* Now try to decrypt it */
  1790. result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
  1791. if (result < 0) {
  1792. goto log_error;
  1793. } else if (err_msg) {
  1794. log_info(LD_REND, "%s on circ %u.", err_msg,
  1795. (unsigned)circuit->base_.n_circ_id);
  1796. tor_free(err_msg);
  1797. }
  1798. stage_descr = "late parsing";
  1799. /* Parse the plaintext */
  1800. result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
  1801. if (result < 0) {
  1802. goto log_error;
  1803. } else if (err_msg) {
  1804. log_info(LD_REND, "%s on circ %u.", err_msg,
  1805. (unsigned)circuit->base_.n_circ_id);
  1806. tor_free(err_msg);
  1807. }
  1808. stage_descr = "late validation";
  1809. /* Validate the parsed plaintext parts */
  1810. result = rend_service_validate_intro_late(parsed_req, &err_msg);
  1811. if (result < 0) {
  1812. goto log_error;
  1813. } else if (err_msg) {
  1814. log_info(LD_REND, "%s on circ %u.", err_msg,
  1815. (unsigned)circuit->base_.n_circ_id);
  1816. tor_free(err_msg);
  1817. }
  1818. stage_descr = NULL;
  1819. /* Increment INTRODUCE2 counter */
  1820. ++(intro_point->accepted_introduce2_count);
  1821. /* Find the rendezvous point */
  1822. rp = find_rp_for_intro(parsed_req, &err_msg);
  1823. if (!rp) {
  1824. err_msg_severity = LOG_PROTOCOL_WARN;
  1825. goto log_error;
  1826. }
  1827. /* Check if we'd refuse to talk to this router */
  1828. if (options->StrictNodes &&
  1829. routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
  1830. log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
  1831. "exclude, and StrictNodes is set. Refusing service.");
  1832. reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
  1833. goto err;
  1834. }
  1835. base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
  1836. /* Check whether there is a past request with the same Diffie-Hellman,
  1837. * part 1. */
  1838. replay = replaycache_add_test_and_elapsed(
  1839. service->accepted_intro_dh_parts,
  1840. parsed_req->dh, DH_KEY_LEN,
  1841. &elapsed);
  1842. if (replay) {
  1843. /* A Tor client will send a new INTRODUCE1 cell with the same rend
  1844. * cookie and DH public key as its previous one if its intro circ
  1845. * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
  1846. * If we received the first INTRODUCE1 cell (the intro-point relay
  1847. * converts it into an INTRODUCE2 cell), we are already trying to
  1848. * connect to that rend point (and may have already succeeded);
  1849. * drop this cell. */
  1850. log_info(LD_REND, "We received an "
  1851. "INTRODUCE2 cell with same first part of "
  1852. "Diffie-Hellman handshake %d seconds ago. Dropping "
  1853. "cell.",
  1854. (int) elapsed);
  1855. goto err;
  1856. }
  1857. /* If the service performs client authorization, check included auth data. */
  1858. if (service->clients) {
  1859. if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
  1860. if (rend_check_authorization(service,
  1861. (const char*)parsed_req->u.v3.auth_data,
  1862. parsed_req->u.v3.auth_len)) {
  1863. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1864. } else {
  1865. log_info(LD_REND, "The authorization data that are contained in "
  1866. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1867. reason = END_CIRC_REASON_CONNECTFAILED;
  1868. goto err;
  1869. }
  1870. } else {
  1871. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1872. "data, but we require client authorization. Dropping cell.");
  1873. reason = END_CIRC_REASON_CONNECTFAILED;
  1874. goto err;
  1875. }
  1876. }
  1877. /* Try DH handshake... */
  1878. dh = crypto_dh_new(DH_TYPE_REND);
  1879. if (!dh || crypto_dh_generate_public(dh)<0) {
  1880. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1881. "or generate public key.");
  1882. reason = END_CIRC_REASON_INTERNAL;
  1883. goto err;
  1884. }
  1885. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
  1886. (char *)(parsed_req->dh),
  1887. DH_KEY_LEN, keys,
  1888. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1889. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1890. reason = END_CIRC_REASON_INTERNAL;
  1891. goto err;
  1892. }
  1893. circ_needs_uptime = rend_service_requires_uptime(service);
  1894. /* help predict this next time */
  1895. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1896. /* Launch a circuit to the client's chosen rendezvous point.
  1897. */
  1898. for (i=0;i<MAX_REND_FAILURES;i++) {
  1899. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1900. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1901. /* A Single Onion Service only uses a direct connection if its
  1902. * firewall rules permit direct connections to the address. */
  1903. if (rend_service_use_direct_connection(options, rp)) {
  1904. flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
  1905. }
  1906. launched = circuit_launch_by_extend_info(
  1907. CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
  1908. if (launched)
  1909. break;
  1910. }
  1911. if (!launched) { /* give up */
  1912. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1913. "point %s for service %s.",
  1914. safe_str_client(extend_info_describe(rp)),
  1915. serviceid);
  1916. reason = END_CIRC_REASON_CONNECTFAILED;
  1917. goto err;
  1918. }
  1919. log_info(LD_REND,
  1920. "Accepted intro; launching circuit to %s "
  1921. "(cookie %s) for service %s.",
  1922. safe_str_client(extend_info_describe(rp)),
  1923. hexcookie, serviceid);
  1924. tor_assert(launched->build_state);
  1925. /* Fill in the circuit's state. */
  1926. launched->rend_data =
  1927. rend_data_service_create(service->service_id, rend_pk_digest,
  1928. parsed_req->rc, service->auth_type);
  1929. launched->build_state->service_pending_final_cpath_ref =
  1930. tor_malloc_zero(sizeof(crypt_path_reference_t));
  1931. launched->build_state->service_pending_final_cpath_ref->refcount = 1;
  1932. launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
  1933. tor_malloc_zero(sizeof(crypt_path_t));
  1934. cpath->magic = CRYPT_PATH_MAGIC;
  1935. launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
  1936. cpath->rend_dh_handshake_state = dh;
  1937. dh = NULL;
  1938. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1939. goto err;
  1940. memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
  1941. goto done;
  1942. log_error:
  1943. if (!err_msg) {
  1944. if (stage_descr) {
  1945. tor_asprintf(&err_msg,
  1946. "unknown %s error for INTRODUCE2", stage_descr);
  1947. } else {
  1948. err_msg = tor_strdup("unknown error for INTRODUCE2");
  1949. }
  1950. }
  1951. log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
  1952. (unsigned)circuit->base_.n_circ_id);
  1953. err:
  1954. status = -1;
  1955. if (dh) crypto_dh_free(dh);
  1956. if (launched) {
  1957. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1958. }
  1959. tor_free(err_msg);
  1960. done:
  1961. memwipe(keys, 0, sizeof(keys));
  1962. memwipe(buf, 0, sizeof(buf));
  1963. memwipe(serviceid, 0, sizeof(serviceid));
  1964. memwipe(hexcookie, 0, sizeof(hexcookie));
  1965. /* Free the parsed cell */
  1966. rend_service_free_intro(parsed_req);
  1967. /* Free rp */
  1968. extend_info_free(rp);
  1969. return status;
  1970. }
  1971. /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
  1972. * return NULL and an error string if we can't. Return a newly allocated
  1973. * extend_info_t* for the rendezvous point. */
  1974. static extend_info_t *
  1975. find_rp_for_intro(const rend_intro_cell_t *intro,
  1976. char **err_msg_out)
  1977. {
  1978. extend_info_t *rp = NULL;
  1979. char *err_msg = NULL;
  1980. const char *rp_nickname = NULL;
  1981. const node_t *node = NULL;
  1982. if (!intro) {
  1983. if (err_msg_out)
  1984. err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
  1985. goto err;
  1986. }
  1987. if (intro->version == 0 || intro->version == 1) {
  1988. rp_nickname = (const char *)(intro->u.v0_v1.rp);
  1989. node = node_get_by_nickname(rp_nickname, 0);
  1990. if (!node) {
  1991. if (err_msg_out) {
  1992. tor_asprintf(&err_msg,
  1993. "Couldn't find router %s named in INTRODUCE2 cell",
  1994. escaped_safe_str_client(rp_nickname));
  1995. }
  1996. goto err;
  1997. }
  1998. /* Are we in single onion mode? */
  1999. const int allow_direct = rend_service_allow_non_anonymous_connection(
  2000. get_options());
  2001. rp = extend_info_from_node(node, allow_direct);
  2002. if (!rp) {
  2003. if (err_msg_out) {
  2004. tor_asprintf(&err_msg,
  2005. "Couldn't build extend_info_t for router %s named "
  2006. "in INTRODUCE2 cell",
  2007. escaped_safe_str_client(rp_nickname));
  2008. }
  2009. goto err;
  2010. }
  2011. } else if (intro->version == 2) {
  2012. rp = extend_info_dup(intro->u.v2.extend_info);
  2013. } else if (intro->version == 3) {
  2014. rp = extend_info_dup(intro->u.v3.extend_info);
  2015. } else {
  2016. if (err_msg_out) {
  2017. tor_asprintf(&err_msg,
  2018. "Unknown version %d in INTRODUCE2 cell",
  2019. (int)(intro->version));
  2020. }
  2021. goto err;
  2022. }
  2023. /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
  2024. * the other cases goto err. */
  2025. tor_assert(rp);
  2026. /* Make sure the RP we are being asked to connect to is _not_ a private
  2027. * address unless it's allowed. Let's avoid to build a circuit to our
  2028. * second middle node and fail right after when extending to the RP. */
  2029. if (!extend_info_addr_is_allowed(&rp->addr)) {
  2030. if (err_msg_out) {
  2031. tor_asprintf(&err_msg,
  2032. "Relay IP in INTRODUCE2 cell is private address.");
  2033. }
  2034. extend_info_free(rp);
  2035. rp = NULL;
  2036. goto err;
  2037. }
  2038. goto done;
  2039. err:
  2040. if (err_msg_out)
  2041. *err_msg_out = err_msg;
  2042. else
  2043. tor_free(err_msg);
  2044. done:
  2045. return rp;
  2046. }
  2047. /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
  2048. * rend_service_parse_intro().
  2049. */
  2050. void
  2051. rend_service_free_intro(rend_intro_cell_t *request)
  2052. {
  2053. if (!request) {
  2054. return;
  2055. }
  2056. /* Free ciphertext */
  2057. tor_free(request->ciphertext);
  2058. request->ciphertext_len = 0;
  2059. /* Have plaintext? */
  2060. if (request->plaintext) {
  2061. /* Zero it out just to be safe */
  2062. memwipe(request->plaintext, 0, request->plaintext_len);
  2063. tor_free(request->plaintext);
  2064. request->plaintext_len = 0;
  2065. }
  2066. /* Have parsed plaintext? */
  2067. if (request->parsed) {
  2068. switch (request->version) {
  2069. case 0:
  2070. case 1:
  2071. /*
  2072. * Nothing more to do; these formats have no further pointers
  2073. * in them.
  2074. */
  2075. break;
  2076. case 2:
  2077. extend_info_free(request->u.v2.extend_info);
  2078. request->u.v2.extend_info = NULL;
  2079. break;
  2080. case 3:
  2081. if (request->u.v3.auth_data) {
  2082. memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
  2083. tor_free(request->u.v3.auth_data);
  2084. }
  2085. extend_info_free(request->u.v3.extend_info);
  2086. request->u.v3.extend_info = NULL;
  2087. break;
  2088. default:
  2089. log_info(LD_BUG,
  2090. "rend_service_free_intro() saw unknown protocol "
  2091. "version %d.",
  2092. request->version);
  2093. }
  2094. }
  2095. /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
  2096. memwipe(request, 0, sizeof(*request));
  2097. tor_free(request);
  2098. }
  2099. /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
  2100. * rend_intro_cell_t structure. Free it with rend_service_free_intro()
  2101. * when finished. The type parameter should be 1 or 2 to indicate whether
  2102. * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
  2103. * parts; after this, call rend_service_decrypt_intro() with a key, then
  2104. * rend_service_parse_intro_plaintext() to finish parsing. The optional
  2105. * err_msg_out parameter is set to a string suitable for log output
  2106. * if parsing fails. This function does some validation, but only
  2107. * that which depends solely on the contents of the cell and the
  2108. * key; it can be unit-tested. Further validation is done in
  2109. * rend_service_validate_intro().
  2110. */
  2111. rend_intro_cell_t *
  2112. rend_service_begin_parse_intro(const uint8_t *request,
  2113. size_t request_len,
  2114. uint8_t type,
  2115. char **err_msg_out)
  2116. {
  2117. rend_intro_cell_t *rv = NULL;
  2118. char *err_msg = NULL;
  2119. if (!request || request_len <= 0) goto err;
  2120. if (!(type == 1 || type == 2)) goto err;
  2121. /* First, check that the cell is long enough to be a sensible INTRODUCE */
  2122. /* min key length plus digest length plus nickname length */
  2123. if (request_len <
  2124. (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
  2125. DH_KEY_LEN + 42)) {
  2126. if (err_msg_out) {
  2127. tor_asprintf(&err_msg,
  2128. "got a truncated INTRODUCE%d cell",
  2129. (int)type);
  2130. }
  2131. goto err;
  2132. }
  2133. /* Allocate a new parsed cell structure */
  2134. rv = tor_malloc_zero(sizeof(*rv));
  2135. /* Set the type */
  2136. rv->type = type;
  2137. /* Copy in the ID */
  2138. memcpy(rv->pk, request, DIGEST_LEN);
  2139. /* Copy in the ciphertext */
  2140. rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
  2141. memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
  2142. rv->ciphertext_len = request_len - DIGEST_LEN;
  2143. goto done;
  2144. err:
  2145. rend_service_free_intro(rv);
  2146. rv = NULL;
  2147. if (err_msg_out && !err_msg) {
  2148. tor_asprintf(&err_msg,
  2149. "unknown INTRODUCE%d error",
  2150. (int)type);
  2151. }
  2152. done:
  2153. if (err_msg_out) *err_msg_out = err_msg;
  2154. else tor_free(err_msg);
  2155. return rv;
  2156. }
  2157. /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
  2158. * cell
  2159. */
  2160. static ssize_t
  2161. rend_service_parse_intro_for_v0_or_v1(
  2162. rend_intro_cell_t *intro,
  2163. const uint8_t *buf,
  2164. size_t plaintext_len,
  2165. char **err_msg_out)
  2166. {
  2167. const char *rp_nickname, *endptr;
  2168. size_t nickname_field_len, ver_specific_len;
  2169. if (intro->version == 1) {
  2170. ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
  2171. rp_nickname = ((const char *)buf) + 1;
  2172. nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
  2173. } else if (intro->version == 0) {
  2174. ver_specific_len = MAX_NICKNAME_LEN + 1;
  2175. rp_nickname = (const char *)buf;
  2176. nickname_field_len = MAX_NICKNAME_LEN + 1;
  2177. } else {
  2178. if (err_msg_out)
  2179. tor_asprintf(err_msg_out,
  2180. "rend_service_parse_intro_for_v0_or_v1() called with "
  2181. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2182. intro->version,
  2183. (int)(intro->type));
  2184. goto err;
  2185. }
  2186. if (plaintext_len < ver_specific_len) {
  2187. if (err_msg_out)
  2188. tor_asprintf(err_msg_out,
  2189. "short plaintext of encrypted part in v1 INTRODUCE%d "
  2190. "cell (%lu bytes, needed %lu)",
  2191. (int)(intro->type),
  2192. (unsigned long)plaintext_len,
  2193. (unsigned long)ver_specific_len);
  2194. goto err;
  2195. }
  2196. endptr = memchr(rp_nickname, 0, nickname_field_len);
  2197. if (!endptr || endptr == rp_nickname) {
  2198. if (err_msg_out) {
  2199. tor_asprintf(err_msg_out,
  2200. "couldn't find a nul-padded nickname in "
  2201. "INTRODUCE%d cell",
  2202. (int)(intro->type));
  2203. }
  2204. goto err;
  2205. }
  2206. if ((intro->version == 0 &&
  2207. !is_legal_nickname(rp_nickname)) ||
  2208. (intro->version == 1 &&
  2209. !is_legal_nickname_or_hexdigest(rp_nickname))) {
  2210. if (err_msg_out) {
  2211. tor_asprintf(err_msg_out,
  2212. "bad nickname in INTRODUCE%d cell",
  2213. (int)(intro->type));
  2214. }
  2215. goto err;
  2216. }
  2217. memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
  2218. return ver_specific_len;
  2219. err:
  2220. return -1;
  2221. }
  2222. /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
  2223. */
  2224. static ssize_t
  2225. rend_service_parse_intro_for_v2(
  2226. rend_intro_cell_t *intro,
  2227. const uint8_t *buf,
  2228. size_t plaintext_len,
  2229. char **err_msg_out)
  2230. {
  2231. unsigned int klen;
  2232. extend_info_t *extend_info = NULL;
  2233. ssize_t ver_specific_len;
  2234. /*
  2235. * We accept version 3 too so that the v3 parser can call this with
  2236. * an adjusted buffer for the latter part of a v3 cell, which is
  2237. * identical to a v2 cell.
  2238. */
  2239. if (!(intro->version == 2 ||
  2240. intro->version == 3)) {
  2241. if (err_msg_out)
  2242. tor_asprintf(err_msg_out,
  2243. "rend_service_parse_intro_for_v2() called with "
  2244. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2245. intro->version,
  2246. (int)(intro->type));
  2247. goto err;
  2248. }
  2249. /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
  2250. if (plaintext_len < 7 + DIGEST_LEN + 2) {
  2251. if (err_msg_out) {
  2252. tor_asprintf(err_msg_out,
  2253. "truncated plaintext of encrypted parted of "
  2254. "version %d INTRODUCE%d cell",
  2255. intro->version,
  2256. (int)(intro->type));
  2257. }
  2258. goto err;
  2259. }
  2260. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  2261. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
  2262. extend_info->port = ntohs(get_uint16(buf + 5));
  2263. memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
  2264. extend_info->nickname[0] = '$';
  2265. base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
  2266. extend_info->identity_digest, DIGEST_LEN);
  2267. klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
  2268. /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
  2269. if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
  2270. if (err_msg_out) {
  2271. tor_asprintf(err_msg_out,
  2272. "truncated plaintext of encrypted parted of "
  2273. "version %d INTRODUCE%d cell",
  2274. intro->version,
  2275. (int)(intro->type));
  2276. }
  2277. goto err;
  2278. }
  2279. extend_info->onion_key =
  2280. crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
  2281. if (!extend_info->onion_key) {
  2282. if (err_msg_out) {
  2283. tor_asprintf(err_msg_out,
  2284. "error decoding onion key in version %d "
  2285. "INTRODUCE%d cell",
  2286. intro->version,
  2287. (intro->type));
  2288. }
  2289. goto err;
  2290. }
  2291. if (128 != crypto_pk_keysize(extend_info->onion_key)) {
  2292. if (err_msg_out) {
  2293. tor_asprintf(err_msg_out,
  2294. "invalid onion key size in version %d INTRODUCE%d cell",
  2295. intro->version,
  2296. (intro->type));
  2297. }
  2298. goto err;
  2299. }
  2300. ver_specific_len = 7+DIGEST_LEN+2+klen;
  2301. if (intro->version == 2) intro->u.v2.extend_info = extend_info;
  2302. else intro->u.v3.extend_info = extend_info;
  2303. return ver_specific_len;
  2304. err:
  2305. extend_info_free(extend_info);
  2306. return -1;
  2307. }
  2308. /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
  2309. */
  2310. static ssize_t
  2311. rend_service_parse_intro_for_v3(
  2312. rend_intro_cell_t *intro,
  2313. const uint8_t *buf,
  2314. size_t plaintext_len,
  2315. char **err_msg_out)
  2316. {
  2317. ssize_t adjust, v2_ver_specific_len, ts_offset;
  2318. /* This should only be called on v3 cells */
  2319. if (intro->version != 3) {
  2320. if (err_msg_out)
  2321. tor_asprintf(err_msg_out,
  2322. "rend_service_parse_intro_for_v3() called with "
  2323. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2324. intro->version,
  2325. (int)(intro->type));
  2326. goto err;
  2327. }
  2328. /*
  2329. * Check that we have at least enough to get auth_len:
  2330. *
  2331. * 1 octet for version, 1 for auth_type, 2 for auth_len
  2332. */
  2333. if (plaintext_len < 4) {
  2334. if (err_msg_out) {
  2335. tor_asprintf(err_msg_out,
  2336. "truncated plaintext of encrypted parted of "
  2337. "version %d INTRODUCE%d cell",
  2338. intro->version,
  2339. (int)(intro->type));
  2340. }
  2341. goto err;
  2342. }
  2343. /*
  2344. * The rend_client_send_introduction() function over in rendclient.c is
  2345. * broken (i.e., fails to match the spec) in such a way that we can't
  2346. * change it without breaking the protocol. Specifically, it doesn't
  2347. * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
  2348. * by two bytes after that. Calculate ts_offset and do everything from
  2349. * the timestamp on relative to that to handle this dain bramage.
  2350. */
  2351. intro->u.v3.auth_type = buf[1];
  2352. if (intro->u.v3.auth_type != REND_NO_AUTH) {
  2353. intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
  2354. ts_offset = 4 + intro->u.v3.auth_len;
  2355. } else {
  2356. intro->u.v3.auth_len = 0;
  2357. ts_offset = 2;
  2358. }
  2359. /* Check that auth len makes sense for this auth type */
  2360. if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
  2361. intro->u.v3.auth_type == REND_STEALTH_AUTH) {
  2362. if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
  2363. if (err_msg_out) {
  2364. tor_asprintf(err_msg_out,
  2365. "wrong auth data size %d for INTRODUCE%d cell, "
  2366. "should be %d",
  2367. (int)(intro->u.v3.auth_len),
  2368. (int)(intro->type),
  2369. REND_DESC_COOKIE_LEN);
  2370. }
  2371. goto err;
  2372. }
  2373. }
  2374. /* Check that we actually have everything up through the timestamp */
  2375. if (plaintext_len < (size_t)(ts_offset)+4) {
  2376. if (err_msg_out) {
  2377. tor_asprintf(err_msg_out,
  2378. "truncated plaintext of encrypted parted of "
  2379. "version %d INTRODUCE%d cell",
  2380. intro->version,
  2381. (int)(intro->type));
  2382. }
  2383. goto err;
  2384. }
  2385. if (intro->u.v3.auth_type != REND_NO_AUTH &&
  2386. intro->u.v3.auth_len > 0) {
  2387. /* Okay, we can go ahead and copy auth_data */
  2388. intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
  2389. /*
  2390. * We know we had an auth_len field in this case, so 4 is
  2391. * always right.
  2392. */
  2393. memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
  2394. }
  2395. /*
  2396. * From here on, the format is as in v2, so we call the v2 parser with
  2397. * adjusted buffer and length. We are 4 + ts_offset octets in, but the
  2398. * v2 parser expects to skip over a version byte at the start, so we
  2399. * adjust by 3 + ts_offset.
  2400. */
  2401. adjust = 3 + ts_offset;
  2402. v2_ver_specific_len =
  2403. rend_service_parse_intro_for_v2(intro,
  2404. buf + adjust, plaintext_len - adjust,
  2405. err_msg_out);
  2406. /* Success in v2 parser */
  2407. if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
  2408. /* Failure in v2 parser; it will have provided an err_msg */
  2409. else return v2_ver_specific_len;
  2410. err:
  2411. return -1;
  2412. }
  2413. /** Table of parser functions for version-specific parts of an INTRODUCE2
  2414. * cell.
  2415. */
  2416. static ssize_t
  2417. (*intro_version_handlers[])(
  2418. rend_intro_cell_t *,
  2419. const uint8_t *,
  2420. size_t,
  2421. char **) =
  2422. { rend_service_parse_intro_for_v0_or_v1,
  2423. rend_service_parse_intro_for_v0_or_v1,
  2424. rend_service_parse_intro_for_v2,
  2425. rend_service_parse_intro_for_v3 };
  2426. /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
  2427. * return 0 if successful, or < 0 and write an error message to
  2428. * *err_msg_out if provided.
  2429. */
  2430. int
  2431. rend_service_decrypt_intro(
  2432. rend_intro_cell_t *intro,
  2433. crypto_pk_t *key,
  2434. char **err_msg_out)
  2435. {
  2436. char *err_msg = NULL;
  2437. uint8_t key_digest[DIGEST_LEN];
  2438. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  2439. ssize_t key_len;
  2440. uint8_t buf[RELAY_PAYLOAD_SIZE];
  2441. int result, status = -1;
  2442. if (!intro || !key) {
  2443. if (err_msg_out) {
  2444. err_msg =
  2445. tor_strdup("rend_service_decrypt_intro() called with bad "
  2446. "parameters");
  2447. }
  2448. status = -2;
  2449. goto err;
  2450. }
  2451. /* Make sure we have ciphertext */
  2452. if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
  2453. if (err_msg_out) {
  2454. tor_asprintf(&err_msg,
  2455. "rend_intro_cell_t was missing ciphertext for "
  2456. "INTRODUCE%d cell",
  2457. (int)(intro->type));
  2458. }
  2459. status = -3;
  2460. goto err;
  2461. }
  2462. /* Check that this cell actually matches this service key */
  2463. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  2464. crypto_pk_get_digest(key, (char *)key_digest);
  2465. if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
  2466. if (err_msg_out) {
  2467. base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
  2468. (char*)(intro->pk), REND_SERVICE_ID_LEN);
  2469. tor_asprintf(&err_msg,
  2470. "got an INTRODUCE%d cell for the wrong service (%s)",
  2471. (int)(intro->type),
  2472. escaped(service_id));
  2473. }
  2474. status = -4;
  2475. goto err;
  2476. }
  2477. /* Make sure the encrypted part is long enough to decrypt */
  2478. key_len = crypto_pk_keysize(key);
  2479. if (intro->ciphertext_len < key_len) {
  2480. if (err_msg_out) {
  2481. tor_asprintf(&err_msg,
  2482. "got an INTRODUCE%d cell with a truncated PK-encrypted "
  2483. "part",
  2484. (int)(intro->type));
  2485. }
  2486. status = -5;
  2487. goto err;
  2488. }
  2489. /* Decrypt the encrypted part */
  2490. note_crypto_pk_op(REND_SERVER);
  2491. result =
  2492. crypto_pk_private_hybrid_decrypt(
  2493. key, (char *)buf, sizeof(buf),
  2494. (const char *)(intro->ciphertext), intro->ciphertext_len,
  2495. PK_PKCS1_OAEP_PADDING, 1);
  2496. if (result < 0) {
  2497. if (err_msg_out) {
  2498. tor_asprintf(&err_msg,
  2499. "couldn't decrypt INTRODUCE%d cell",
  2500. (int)(intro->type));
  2501. }
  2502. status = -6;
  2503. goto err;
  2504. }
  2505. intro->plaintext_len = result;
  2506. intro->plaintext = tor_malloc(intro->plaintext_len);
  2507. memcpy(intro->plaintext, buf, intro->plaintext_len);
  2508. status = 0;
  2509. goto done;
  2510. err:
  2511. if (err_msg_out && !err_msg) {
  2512. tor_asprintf(&err_msg,
  2513. "unknown INTRODUCE%d error decrypting encrypted part",
  2514. intro ? (int)(intro->type) : -1);
  2515. }
  2516. done:
  2517. if (err_msg_out) *err_msg_out = err_msg;
  2518. else tor_free(err_msg);
  2519. /* clean up potentially sensitive material */
  2520. memwipe(buf, 0, sizeof(buf));
  2521. memwipe(key_digest, 0, sizeof(key_digest));
  2522. memwipe(service_id, 0, sizeof(service_id));
  2523. return status;
  2524. }
  2525. /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
  2526. * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
  2527. * message to *err_msg_out if provided.
  2528. */
  2529. int
  2530. rend_service_parse_intro_plaintext(
  2531. rend_intro_cell_t *intro,
  2532. char **err_msg_out)
  2533. {
  2534. char *err_msg = NULL;
  2535. ssize_t ver_specific_len, ver_invariant_len;
  2536. uint8_t version;
  2537. int status = -1;
  2538. if (!intro) {
  2539. if (err_msg_out) {
  2540. err_msg =
  2541. tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
  2542. "rend_intro_cell_t");
  2543. }
  2544. status = -2;
  2545. goto err;
  2546. }
  2547. /* Check that we have plaintext */
  2548. if (!(intro->plaintext) || intro->plaintext_len <= 0) {
  2549. if (err_msg_out) {
  2550. err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
  2551. }
  2552. status = -3;
  2553. goto err;
  2554. }
  2555. /* In all formats except v0, the first byte is a version number */
  2556. version = intro->plaintext[0];
  2557. /* v0 has no version byte (stupid...), so handle it as a fallback */
  2558. if (version > 3) version = 0;
  2559. /* Copy the version into the parsed cell structure */
  2560. intro->version = version;
  2561. /* Call the version-specific parser from the table */
  2562. ver_specific_len =
  2563. intro_version_handlers[version](intro,
  2564. intro->plaintext, intro->plaintext_len,
  2565. &err_msg);
  2566. if (ver_specific_len < 0) {
  2567. status = -4;
  2568. goto err;
  2569. }
  2570. /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
  2571. * and at the end of the plaintext of the encrypted part of the cell.
  2572. */
  2573. ver_invariant_len = intro->plaintext_len - ver_specific_len;
  2574. if (ver_invariant_len < REND_COOKIE_LEN + DH_KEY_LEN) {
  2575. tor_asprintf(&err_msg,
  2576. "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
  2577. (int)(intro->type),
  2578. (long)(intro->plaintext_len));
  2579. status = -5;
  2580. goto err;
  2581. } else if (ver_invariant_len > REND_COOKIE_LEN + DH_KEY_LEN) {
  2582. tor_asprintf(&err_msg,
  2583. "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
  2584. (int)(intro->type),
  2585. (long)(intro->plaintext_len));
  2586. status = -6;
  2587. goto err;
  2588. } else {
  2589. memcpy(intro->rc,
  2590. intro->plaintext + ver_specific_len,
  2591. REND_COOKIE_LEN);
  2592. memcpy(intro->dh,
  2593. intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
  2594. DH_KEY_LEN);
  2595. }
  2596. /* Flag it as being fully parsed */
  2597. intro->parsed = 1;
  2598. status = 0;
  2599. goto done;
  2600. err:
  2601. if (err_msg_out && !err_msg) {
  2602. tor_asprintf(&err_msg,
  2603. "unknown INTRODUCE%d error parsing encrypted part",
  2604. intro ? (int)(intro->type) : -1);
  2605. }
  2606. done:
  2607. if (err_msg_out) *err_msg_out = err_msg;
  2608. else tor_free(err_msg);
  2609. return status;
  2610. }
  2611. /** Do validity checks on a parsed intro cell after decryption; some of
  2612. * these are not done in rend_service_parse_intro_plaintext() itself because
  2613. * they depend on a lot of other state and would make it hard to unit test.
  2614. * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
  2615. * optionally writes out an error message for logging. If an err_msg
  2616. * pointer is provided, it is the caller's responsibility to free any
  2617. * provided message.
  2618. */
  2619. int
  2620. rend_service_validate_intro_late(const rend_intro_cell_t *intro,
  2621. char **err_msg_out)
  2622. {
  2623. int status = 0;
  2624. if (!intro) {
  2625. if (err_msg_out)
  2626. *err_msg_out =
  2627. tor_strdup("NULL intro cell passed to "
  2628. "rend_service_validate_intro_late()");
  2629. status = -1;
  2630. goto err;
  2631. }
  2632. if (intro->version == 3 && intro->parsed) {
  2633. if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
  2634. intro->u.v3.auth_type == REND_BASIC_AUTH ||
  2635. intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
  2636. /* This is an informative message, not an error, as in the old code */
  2637. if (err_msg_out)
  2638. tor_asprintf(err_msg_out,
  2639. "unknown authorization type %d",
  2640. intro->u.v3.auth_type);
  2641. }
  2642. }
  2643. err:
  2644. return status;
  2645. }
  2646. /** Called when we fail building a rendezvous circuit at some point other
  2647. * than the last hop: launches a new circuit to the same rendezvous point.
  2648. */
  2649. void
  2650. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  2651. {
  2652. origin_circuit_t *newcirc;
  2653. cpath_build_state_t *newstate, *oldstate;
  2654. tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  2655. /* Don't relaunch the same rend circ twice. */
  2656. if (oldcirc->hs_service_side_rend_circ_has_been_relaunched) {
  2657. log_info(LD_REND, "Rendezvous circuit to %s has already been relaunched; "
  2658. "not relaunching it again.",
  2659. oldcirc->build_state ?
  2660. safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
  2661. : "*unknown*");
  2662. return;
  2663. }
  2664. oldcirc->hs_service_side_rend_circ_has_been_relaunched = 1;
  2665. if (!oldcirc->build_state ||
  2666. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  2667. oldcirc->build_state->expiry_time < time(NULL)) {
  2668. log_info(LD_REND,
  2669. "Attempt to build circuit to %s for rendezvous has failed "
  2670. "too many times or expired; giving up.",
  2671. oldcirc->build_state ?
  2672. safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
  2673. : "*unknown*");
  2674. return;
  2675. }
  2676. oldstate = oldcirc->build_state;
  2677. tor_assert(oldstate);
  2678. if (oldstate->service_pending_final_cpath_ref == NULL) {
  2679. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  2680. "Initiator will retry.");
  2681. return;
  2682. }
  2683. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  2684. safe_str(extend_info_describe(oldstate->chosen_exit)));
  2685. /* You'd think Single Onion Services would want to retry the rendezvous
  2686. * using a direct connection. But if it's blocked by a firewall, or the
  2687. * service is IPv6-only, or the rend point avoiding becoming a one-hop
  2688. * proxy, we need a 3-hop connection. */
  2689. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  2690. oldstate->chosen_exit,
  2691. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  2692. if (!newcirc) {
  2693. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  2694. safe_str(extend_info_describe(oldstate->chosen_exit)));
  2695. return;
  2696. }
  2697. newstate = newcirc->build_state;
  2698. tor_assert(newstate);
  2699. newstate->failure_count = oldstate->failure_count+1;
  2700. newstate->expiry_time = oldstate->expiry_time;
  2701. newstate->service_pending_final_cpath_ref =
  2702. oldstate->service_pending_final_cpath_ref;
  2703. ++(newstate->service_pending_final_cpath_ref->refcount);
  2704. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  2705. }
  2706. /** Launch a circuit to serve as an introduction point for the service
  2707. * <b>service</b> at the introduction point <b>nickname</b>
  2708. */
  2709. static int
  2710. rend_service_launch_establish_intro(rend_service_t *service,
  2711. rend_intro_point_t *intro)
  2712. {
  2713. origin_circuit_t *launched;
  2714. int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
  2715. const or_options_t *options = get_options();
  2716. extend_info_t *launch_ei = intro->extend_info;
  2717. extend_info_t *direct_ei = NULL;
  2718. /* Are we in single onion mode? */
  2719. if (rend_service_allow_non_anonymous_connection(options)) {
  2720. /* Do we have a descriptor for the node?
  2721. * We've either just chosen it from the consensus, or we've just reviewed
  2722. * our intro points to see which ones are still valid, and deleted the ones
  2723. * that aren't in the consensus any more. */
  2724. const node_t *node = node_get_by_id(launch_ei->identity_digest);
  2725. if (BUG(!node)) {
  2726. /* The service has kept an intro point after it went missing from the
  2727. * consensus. If we did anything else here, it would be a consensus
  2728. * distinguisher. Which are less of an issue for single onion services,
  2729. * but still a bug. */
  2730. return -1;
  2731. }
  2732. /* Can we connect to the node directly? If so, replace launch_ei
  2733. * (a multi-hop extend_info) with one suitable for direct connection. */
  2734. if (rend_service_use_direct_connection_node(options, node)) {
  2735. direct_ei = extend_info_from_node(node, 1);
  2736. if (BUG(!direct_ei)) {
  2737. /* rend_service_use_direct_connection_node and extend_info_from_node
  2738. * disagree about which addresses on this node are permitted. This
  2739. * should never happen. Avoiding the connection is a safe response. */
  2740. return -1;
  2741. }
  2742. flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
  2743. launch_ei = direct_ei;
  2744. }
  2745. }
  2746. /* launch_ei is either intro->extend_info, or has been replaced with a valid
  2747. * extend_info for single onion service direct connection. */
  2748. tor_assert(launch_ei);
  2749. /* We must have the same intro when making a direct connection. */
  2750. tor_assert(tor_memeq(intro->extend_info->identity_digest,
  2751. launch_ei->identity_digest,
  2752. DIGEST_LEN));
  2753. log_info(LD_REND,
  2754. "Launching circuit to introduction point %s%s%s for service %s",
  2755. safe_str_client(extend_info_describe(intro->extend_info)),
  2756. direct_ei ? " via direct address " : "",
  2757. direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
  2758. service->service_id);
  2759. rep_hist_note_used_internal(time(NULL), 1, 0);
  2760. ++service->n_intro_circuits_launched;
  2761. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  2762. launch_ei, flags);
  2763. if (!launched) {
  2764. log_info(LD_REND,
  2765. "Can't launch circuit to establish introduction at %s%s%s.",
  2766. safe_str_client(extend_info_describe(intro->extend_info)),
  2767. direct_ei ? " via direct address " : "",
  2768. direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
  2769. );
  2770. extend_info_free(direct_ei);
  2771. return -1;
  2772. }
  2773. /* We must have the same exit node even if cannibalized or direct connection.
  2774. */
  2775. tor_assert(tor_memeq(intro->extend_info->identity_digest,
  2776. launched->build_state->chosen_exit->identity_digest,
  2777. DIGEST_LEN));
  2778. launched->rend_data = rend_data_service_create(service->service_id,
  2779. service->pk_digest, NULL,
  2780. service->auth_type);
  2781. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  2782. if (launched->base_.state == CIRCUIT_STATE_OPEN)
  2783. rend_service_intro_has_opened(launched);
  2784. extend_info_free(direct_ei);
  2785. return 0;
  2786. }
  2787. /** Return the number of introduction points that are established for the
  2788. * given service. */
  2789. static unsigned int
  2790. count_established_intro_points(const rend_service_t *service)
  2791. {
  2792. unsigned int num = 0;
  2793. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  2794. num += intro->circuit_established
  2795. );
  2796. return num;
  2797. }
  2798. /** Return the number of introduction points that are or are being
  2799. * established for the given service. This function iterates over all
  2800. * circuit and count those that are linked to the service and are waiting
  2801. * for the intro point to respond. */
  2802. static unsigned int
  2803. count_intro_point_circuits(const rend_service_t *service)
  2804. {
  2805. unsigned int num_ipos = 0;
  2806. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  2807. if (!circ->marked_for_close &&
  2808. circ->state == CIRCUIT_STATE_OPEN &&
  2809. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  2810. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  2811. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  2812. if (oc->rend_data &&
  2813. rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
  2814. num_ipos++;
  2815. }
  2816. }
  2817. }
  2818. SMARTLIST_FOREACH_END(circ);
  2819. return num_ipos;
  2820. }
  2821. /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
  2822. write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
  2823. as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
  2824. crypto material. On success, fill <b>cell_body_out</b> and return the number
  2825. of bytes written. On fail, return -1.
  2826. */
  2827. STATIC ssize_t
  2828. encode_establish_intro_cell_legacy(char *cell_body_out, crypto_pk_t *intro_key,
  2829. char *rend_circ_nonce)
  2830. {
  2831. int retval = -1;
  2832. int r;
  2833. int len = 0;
  2834. char auth[DIGEST_LEN + 9];
  2835. tor_assert(intro_key);
  2836. tor_assert(rend_circ_nonce);
  2837. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  2838. r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
  2839. RELAY_PAYLOAD_SIZE-2);
  2840. if (r < 0) {
  2841. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  2842. goto err;
  2843. }
  2844. len = r;
  2845. set_uint16(cell_body_out, htons((uint16_t)len));
  2846. len += 2;
  2847. memcpy(auth, rend_circ_nonce, DIGEST_LEN);
  2848. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  2849. if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
  2850. goto err;
  2851. len += 20;
  2852. note_crypto_pk_op(REND_SERVER);
  2853. r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
  2854. sizeof(cell_body_out)-len,
  2855. cell_body_out, len);
  2856. if (r<0) {
  2857. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  2858. goto err;
  2859. }
  2860. len += r;
  2861. retval = len;
  2862. err:
  2863. memwipe(auth, 0, sizeof(auth));
  2864. return retval;
  2865. }
  2866. /** Called when we're done building a circuit to an introduction point:
  2867. * sends a RELAY_ESTABLISH_INTRO cell.
  2868. */
  2869. void
  2870. rend_service_intro_has_opened(origin_circuit_t *circuit)
  2871. {
  2872. rend_service_t *service;
  2873. char buf[RELAY_PAYLOAD_SIZE];
  2874. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  2875. int reason = END_CIRC_REASON_TORPROTOCOL;
  2876. const char *rend_pk_digest;
  2877. tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  2878. assert_circ_anonymity_ok(circuit, get_options());
  2879. tor_assert(circuit->cpath);
  2880. tor_assert(circuit->rend_data);
  2881. /* XXX: This is version 2 specific (only on supported). */
  2882. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  2883. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  2884. rend_pk_digest, REND_SERVICE_ID_LEN);
  2885. service = rend_service_get_by_pk_digest(rend_pk_digest);
  2886. if (!service) {
  2887. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
  2888. safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
  2889. reason = END_CIRC_REASON_NOSUCHSERVICE;
  2890. goto err;
  2891. }
  2892. /* If we already have enough introduction circuits for this service,
  2893. * redefine this one as a general circuit or close it, depending.
  2894. * Substract the amount of expiring nodes here since the circuits are
  2895. * still opened. */
  2896. if ((count_intro_point_circuits(service) -
  2897. smartlist_len(service->expiring_nodes)) >
  2898. service->n_intro_points_wanted) {
  2899. const or_options_t *options = get_options();
  2900. /* Remove the intro point associated with this circuit, it's being
  2901. * repurposed or closed thus cleanup memory. */
  2902. rend_intro_point_t *intro = find_intro_point(circuit);
  2903. if (intro != NULL) {
  2904. smartlist_remove(service->intro_nodes, intro);
  2905. rend_intro_point_free(intro);
  2906. }
  2907. if (options->ExcludeNodes) {
  2908. /* XXXX in some future version, we can test whether the transition is
  2909. allowed or not given the actual nodes in the circuit. But for now,
  2910. this case, we might as well close the thing. */
  2911. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  2912. "circuit, but we already have enough. Closing it.");
  2913. reason = END_CIRC_REASON_NONE;
  2914. goto err;
  2915. } else {
  2916. tor_assert(circuit->build_state->is_internal);
  2917. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  2918. "circuit, but we already have enough. Redefining purpose to "
  2919. "general; leaving as internal.");
  2920. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
  2921. {
  2922. rend_data_free(circuit->rend_data);
  2923. circuit->rend_data = NULL;
  2924. }
  2925. {
  2926. crypto_pk_t *intro_key = circuit->intro_key;
  2927. circuit->intro_key = NULL;
  2928. crypto_pk_free(intro_key);
  2929. }
  2930. circuit_has_opened(circuit);
  2931. goto done;
  2932. }
  2933. }
  2934. log_info(LD_REND,
  2935. "Established circuit %u as introduction point for service %s",
  2936. (unsigned)circuit->base_.n_circ_id, serviceid);
  2937. circuit_log_path(LOG_INFO, LD_REND, circuit);
  2938. /* Send the ESTABLISH_INTRO cell */
  2939. {
  2940. ssize_t len;
  2941. len = encode_establish_intro_cell_legacy(buf, circuit->intro_key,
  2942. circuit->cpath->prev->rend_circ_nonce);
  2943. if (len < 0) {
  2944. reason = END_CIRC_REASON_INTERNAL;
  2945. goto err;
  2946. }
  2947. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  2948. RELAY_COMMAND_ESTABLISH_INTRO,
  2949. buf, len, circuit->cpath->prev)<0) {
  2950. log_info(LD_GENERAL,
  2951. "Couldn't send introduction request for service %s on circuit %u",
  2952. serviceid, (unsigned)circuit->base_.n_circ_id);
  2953. goto done;
  2954. }
  2955. }
  2956. /* We've attempted to use this circuit */
  2957. pathbias_count_use_attempt(circuit);
  2958. goto done;
  2959. err:
  2960. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  2961. done:
  2962. memwipe(buf, 0, sizeof(buf));
  2963. memwipe(serviceid, 0, sizeof(serviceid));
  2964. return;
  2965. }
  2966. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  2967. * live introduction point, and note that the service descriptor is
  2968. * now out-of-date. */
  2969. int
  2970. rend_service_intro_established(origin_circuit_t *circuit,
  2971. const uint8_t *request,
  2972. size_t request_len)
  2973. {
  2974. rend_service_t *service;
  2975. rend_intro_point_t *intro;
  2976. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  2977. (void) request;
  2978. (void) request_len;
  2979. tor_assert(circuit->rend_data);
  2980. /* XXX: This is version 2 specific (only supported one for now). */
  2981. const char *rend_pk_digest =
  2982. (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  2983. if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  2984. log_warn(LD_PROTOCOL,
  2985. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  2986. goto err;
  2987. }
  2988. service = rend_service_get_by_pk_digest(rend_pk_digest);
  2989. if (!service) {
  2990. log_warn(LD_REND, "Unknown service on introduction circuit %u.",
  2991. (unsigned)circuit->base_.n_circ_id);
  2992. goto err;
  2993. }
  2994. /* We've just successfully established a intro circuit to one of our
  2995. * introduction point, account for it. */
  2996. intro = find_intro_point(circuit);
  2997. if (intro == NULL) {
  2998. log_warn(LD_REND,
  2999. "Introduction circuit established without a rend_intro_point_t "
  3000. "object for service %s on circuit %u",
  3001. safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
  3002. goto err;
  3003. }
  3004. intro->circuit_established = 1;
  3005. /* We might not have every introduction point ready but at this point we
  3006. * know that the descriptor needs to be uploaded. */
  3007. service->desc_is_dirty = time(NULL);
  3008. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
  3009. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  3010. rend_pk_digest, REND_SERVICE_ID_LEN);
  3011. log_info(LD_REND,
  3012. "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
  3013. (unsigned)circuit->base_.n_circ_id, serviceid);
  3014. /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
  3015. * used the circ */
  3016. pathbias_mark_use_success(circuit);
  3017. return 0;
  3018. err:
  3019. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  3020. return -1;
  3021. }
  3022. /** Called once a circuit to a rendezvous point is established: sends a
  3023. * RELAY_COMMAND_RENDEZVOUS1 cell.
  3024. */
  3025. void
  3026. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  3027. {
  3028. rend_service_t *service;
  3029. char buf[RELAY_PAYLOAD_SIZE];
  3030. crypt_path_t *hop;
  3031. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3032. char hexcookie[9];
  3033. int reason;
  3034. const char *rend_cookie, *rend_pk_digest;
  3035. tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  3036. tor_assert(circuit->cpath);
  3037. tor_assert(circuit->build_state);
  3038. assert_circ_anonymity_ok(circuit, get_options());
  3039. tor_assert(circuit->rend_data);
  3040. /* XXX: This is version 2 specific (only one supported). */
  3041. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
  3042. NULL);
  3043. rend_cookie = circuit->rend_data->rend_cookie;
  3044. /* Declare the circuit dirty to avoid reuse, and for path-bias */
  3045. if (!circuit->base_.timestamp_dirty)
  3046. circuit->base_.timestamp_dirty = time(NULL);
  3047. /* This may be redundant */
  3048. pathbias_count_use_attempt(circuit);
  3049. hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
  3050. base16_encode(hexcookie,9, rend_cookie,4);
  3051. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  3052. rend_pk_digest, REND_SERVICE_ID_LEN);
  3053. log_info(LD_REND,
  3054. "Done building circuit %u to rendezvous with "
  3055. "cookie %s for service %s",
  3056. (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
  3057. circuit_log_path(LOG_INFO, LD_REND, circuit);
  3058. /* Clear the 'in-progress HS circ has timed out' flag for
  3059. * consistency with what happens on the client side; this line has
  3060. * no effect on Tor's behaviour. */
  3061. circuit->hs_circ_has_timed_out = 0;
  3062. /* If hop is NULL, another rend circ has already connected to this
  3063. * rend point. Close this circ. */
  3064. if (hop == NULL) {
  3065. log_info(LD_REND, "Another rend circ has already reached this rend point; "
  3066. "closing this rend circ.");
  3067. reason = END_CIRC_REASON_NONE;
  3068. goto err;
  3069. }
  3070. /* Remove our final cpath element from the reference, so that no
  3071. * other circuit will try to use it. Store it in
  3072. * pending_final_cpath for now to ensure that it will be freed if
  3073. * our rendezvous attempt fails. */
  3074. circuit->build_state->pending_final_cpath = hop;
  3075. circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
  3076. service = rend_service_get_by_pk_digest(rend_pk_digest);
  3077. if (!service) {
  3078. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  3079. "rendezvous circuit.");
  3080. reason = END_CIRC_REASON_INTERNAL;
  3081. goto err;
  3082. }
  3083. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  3084. memcpy(buf, rend_cookie, REND_COOKIE_LEN);
  3085. if (crypto_dh_get_public(hop->rend_dh_handshake_state,
  3086. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  3087. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  3088. reason = END_CIRC_REASON_INTERNAL;
  3089. goto err;
  3090. }
  3091. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->rend_circ_nonce,
  3092. DIGEST_LEN);
  3093. /* Send the cell */
  3094. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  3095. RELAY_COMMAND_RENDEZVOUS1,
  3096. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  3097. circuit->cpath->prev)<0) {
  3098. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  3099. goto done;
  3100. }
  3101. crypto_dh_free(hop->rend_dh_handshake_state);
  3102. hop->rend_dh_handshake_state = NULL;
  3103. /* Append the cpath entry. */
  3104. hop->state = CPATH_STATE_OPEN;
  3105. /* set the windows to default. these are the windows
  3106. * that the service thinks the client has.
  3107. */
  3108. hop->package_window = circuit_initial_package_window();
  3109. hop->deliver_window = CIRCWINDOW_START;
  3110. onion_append_to_cpath(&circuit->cpath, hop);
  3111. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  3112. /* Change the circuit purpose. */
  3113. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
  3114. goto done;
  3115. err:
  3116. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  3117. done:
  3118. memwipe(buf, 0, sizeof(buf));
  3119. memwipe(serviceid, 0, sizeof(serviceid));
  3120. memwipe(hexcookie, 0, sizeof(hexcookie));
  3121. return;
  3122. }
  3123. /*
  3124. * Manage introduction points
  3125. */
  3126. /** Return the (possibly non-open) introduction circuit ending at
  3127. * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
  3128. * (<b>desc_version</b> is ignored). Return NULL if no such service is
  3129. * found.
  3130. */
  3131. static origin_circuit_t *
  3132. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
  3133. {
  3134. origin_circuit_t *circ = NULL;
  3135. tor_assert(intro);
  3136. while ((circ = circuit_get_next_by_pk_and_purpose(circ,
  3137. (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
  3138. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  3139. intro->extend_info->identity_digest, DIGEST_LEN) &&
  3140. circ->rend_data) {
  3141. return circ;
  3142. }
  3143. }
  3144. circ = NULL;
  3145. while ((circ = circuit_get_next_by_pk_and_purpose(circ,
  3146. (uint8_t *) pk_digest,
  3147. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  3148. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  3149. intro->extend_info->identity_digest, DIGEST_LEN) &&
  3150. circ->rend_data) {
  3151. return circ;
  3152. }
  3153. }
  3154. return NULL;
  3155. }
  3156. /** Return the corresponding introdution point using the circuit <b>circ</b>
  3157. * found in the <b>service</b>. NULL is returned if not found. */
  3158. static rend_intro_point_t *
  3159. find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
  3160. {
  3161. tor_assert(service);
  3162. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  3163. TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  3164. SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
  3165. intro_point,
  3166. if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
  3167. return intro_point;
  3168. });
  3169. return NULL;
  3170. }
  3171. /** Return a pointer to the rend_intro_point_t corresponding to the
  3172. * service-side introduction circuit <b>circ</b>. */
  3173. static rend_intro_point_t *
  3174. find_intro_point(origin_circuit_t *circ)
  3175. {
  3176. const char *serviceid;
  3177. rend_service_t *service = NULL;
  3178. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  3179. TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  3180. tor_assert(circ->rend_data);
  3181. serviceid = rend_data_get_address(circ->rend_data);
  3182. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
  3183. if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
  3184. service = s;
  3185. break;
  3186. });
  3187. if (service == NULL) return NULL;
  3188. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
  3189. if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
  3190. return intro_point;
  3191. });
  3192. return NULL;
  3193. }
  3194. /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
  3195. * associated with the rend_service_descriptor_t <b>renddesc</b> to
  3196. * the responsible hidden service directories OR the hidden service
  3197. * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
  3198. * <b>seconds_valid</b> are only passed for logging purposes.
  3199. */
  3200. void
  3201. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  3202. smartlist_t *descs, smartlist_t *hs_dirs,
  3203. const char *service_id, int seconds_valid)
  3204. {
  3205. int i, j, failed_upload = 0;
  3206. smartlist_t *responsible_dirs = smartlist_new();
  3207. smartlist_t *successful_uploads = smartlist_new();
  3208. routerstatus_t *hs_dir;
  3209. for (i = 0; i < smartlist_len(descs); i++) {
  3210. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  3211. /** If any HSDirs are specified, they should be used instead of
  3212. * the responsible directories */
  3213. if (hs_dirs && smartlist_len(hs_dirs) > 0) {
  3214. smartlist_add_all(responsible_dirs, hs_dirs);
  3215. } else {
  3216. /* Determine responsible dirs. */
  3217. if (hid_serv_get_responsible_directories(responsible_dirs,
  3218. desc->desc_id) < 0) {
  3219. log_warn(LD_REND, "Could not determine the responsible hidden service "
  3220. "directories to post descriptors to.");
  3221. control_event_hs_descriptor_upload(service_id,
  3222. "UNKNOWN",
  3223. "UNKNOWN");
  3224. goto done;
  3225. }
  3226. }
  3227. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  3228. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  3229. char *hs_dir_ip;
  3230. const node_t *node;
  3231. rend_data_t *rend_data;
  3232. hs_dir = smartlist_get(responsible_dirs, j);
  3233. if (smartlist_contains_digest(renddesc->successful_uploads,
  3234. hs_dir->identity_digest))
  3235. /* Don't upload descriptor if we succeeded in doing so last time. */
  3236. continue;
  3237. node = node_get_by_id(hs_dir->identity_digest);
  3238. if (!node || !node_has_descriptor(node)) {
  3239. log_info(LD_REND, "Not launching upload for for v2 descriptor to "
  3240. "hidden service directory %s; we don't have its "
  3241. "router descriptor. Queuing for later upload.",
  3242. safe_str_client(routerstatus_describe(hs_dir)));
  3243. failed_upload = -1;
  3244. continue;
  3245. }
  3246. /* Send publish request. */
  3247. /* We need the service ID to identify which service did the upload
  3248. * request. Lookup is made in rend_service_desc_has_uploaded(). */
  3249. rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
  3250. REND_NO_AUTH);
  3251. directory_initiate_command_routerstatus_rend(hs_dir,
  3252. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  3253. ROUTER_PURPOSE_GENERAL,
  3254. DIRIND_ANONYMOUS, NULL,
  3255. desc->desc_str,
  3256. strlen(desc->desc_str),
  3257. 0, rend_data, NULL);
  3258. rend_data_free(rend_data);
  3259. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  3260. desc->desc_id, DIGEST_LEN);
  3261. hs_dir_ip = tor_dup_ip(hs_dir->addr);
  3262. log_info(LD_REND, "Launching upload for v2 descriptor for "
  3263. "service '%s' with descriptor ID '%s' with validity "
  3264. "of %d seconds to hidden service directory '%s' on "
  3265. "%s:%d.",
  3266. safe_str_client(service_id),
  3267. safe_str_client(desc_id_base32),
  3268. seconds_valid,
  3269. hs_dir->nickname,
  3270. hs_dir_ip,
  3271. hs_dir->or_port);
  3272. control_event_hs_descriptor_upload(service_id,
  3273. hs_dir->identity_digest,
  3274. desc_id_base32);
  3275. tor_free(hs_dir_ip);
  3276. /* Remember successful upload to this router for next time. */
  3277. if (!smartlist_contains_digest(successful_uploads,
  3278. hs_dir->identity_digest))
  3279. smartlist_add(successful_uploads, hs_dir->identity_digest);
  3280. }
  3281. smartlist_clear(responsible_dirs);
  3282. }
  3283. if (!failed_upload) {
  3284. if (renddesc->successful_uploads) {
  3285. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  3286. smartlist_free(renddesc->successful_uploads);
  3287. renddesc->successful_uploads = NULL;
  3288. }
  3289. renddesc->all_uploads_performed = 1;
  3290. } else {
  3291. /* Remember which routers worked this time, so that we don't upload the
  3292. * descriptor to them again. */
  3293. if (!renddesc->successful_uploads)
  3294. renddesc->successful_uploads = smartlist_new();
  3295. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  3296. if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
  3297. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  3298. smartlist_add(renddesc->successful_uploads, hsdir_id);
  3299. }
  3300. });
  3301. }
  3302. done:
  3303. smartlist_free(responsible_dirs);
  3304. smartlist_free(successful_uploads);
  3305. }
  3306. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  3307. * and upload it/them to the responsible hidden service directories.
  3308. */
  3309. static void
  3310. upload_service_descriptor(rend_service_t *service)
  3311. {
  3312. time_t now = time(NULL);
  3313. int rendpostperiod;
  3314. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3315. int uploaded = 0;
  3316. rendpostperiod = get_options()->RendPostPeriod;
  3317. networkstatus_t *c = networkstatus_get_latest_consensus();
  3318. if (c && smartlist_len(c->routerstatus_list) > 0) {
  3319. int seconds_valid, i, j, num_descs;
  3320. smartlist_t *descs = smartlist_new();
  3321. smartlist_t *client_cookies = smartlist_new();
  3322. /* Either upload a single descriptor (including replicas) or one
  3323. * descriptor for each authorized client in case of authorization
  3324. * type 'stealth'. */
  3325. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  3326. smartlist_len(service->clients) : 1;
  3327. for (j = 0; j < num_descs; j++) {
  3328. crypto_pk_t *client_key = NULL;
  3329. rend_authorized_client_t *client = NULL;
  3330. smartlist_clear(client_cookies);
  3331. switch (service->auth_type) {
  3332. case REND_NO_AUTH:
  3333. /* Do nothing here. */
  3334. break;
  3335. case REND_BASIC_AUTH:
  3336. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  3337. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  3338. break;
  3339. case REND_STEALTH_AUTH:
  3340. client = smartlist_get(service->clients, j);
  3341. client_key = client->client_key;
  3342. smartlist_add(client_cookies, client->descriptor_cookie);
  3343. break;
  3344. }
  3345. /* Encode the current descriptor. */
  3346. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  3347. now, 0,
  3348. service->auth_type,
  3349. client_key,
  3350. client_cookies);
  3351. if (seconds_valid < 0) {
  3352. log_warn(LD_BUG, "Internal error: couldn't encode service "
  3353. "descriptor; not uploading.");
  3354. smartlist_free(descs);
  3355. smartlist_free(client_cookies);
  3356. return;
  3357. }
  3358. rend_get_service_id(service->desc->pk, serviceid);
  3359. if (get_options()->PublishHidServDescriptors) {
  3360. /* Post the current descriptors to the hidden service directories. */
  3361. log_info(LD_REND, "Launching upload for hidden service %s",
  3362. serviceid);
  3363. directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
  3364. seconds_valid);
  3365. }
  3366. /* Free memory for descriptors. */
  3367. for (i = 0; i < smartlist_len(descs); i++)
  3368. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  3369. smartlist_clear(descs);
  3370. /* Update next upload time. */
  3371. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  3372. > rendpostperiod)
  3373. service->next_upload_time = now + rendpostperiod;
  3374. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  3375. service->next_upload_time = now + seconds_valid + 1;
  3376. else
  3377. service->next_upload_time = now + seconds_valid -
  3378. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  3379. /* Post also the next descriptors, if necessary. */
  3380. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  3381. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  3382. now, 1,
  3383. service->auth_type,
  3384. client_key,
  3385. client_cookies);
  3386. if (seconds_valid < 0) {
  3387. log_warn(LD_BUG, "Internal error: couldn't encode service "
  3388. "descriptor; not uploading.");
  3389. smartlist_free(descs);
  3390. smartlist_free(client_cookies);
  3391. return;
  3392. }
  3393. if (get_options()->PublishHidServDescriptors) {
  3394. directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
  3395. seconds_valid);
  3396. }
  3397. /* Free memory for descriptors. */
  3398. for (i = 0; i < smartlist_len(descs); i++)
  3399. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  3400. smartlist_clear(descs);
  3401. }
  3402. }
  3403. smartlist_free(descs);
  3404. smartlist_free(client_cookies);
  3405. uploaded = 1;
  3406. if (get_options()->PublishHidServDescriptors) {
  3407. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  3408. } else {
  3409. log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
  3410. }
  3411. }
  3412. /* If not uploaded, try again in one minute. */
  3413. if (!uploaded)
  3414. service->next_upload_time = now + 60;
  3415. /* Unmark dirty flag of this service. */
  3416. service->desc_is_dirty = 0;
  3417. }
  3418. /** Return the number of INTRODUCE2 cells this hidden service has received
  3419. * from this intro point. */
  3420. static int
  3421. intro_point_accepted_intro_count(rend_intro_point_t *intro)
  3422. {
  3423. return intro->accepted_introduce2_count;
  3424. }
  3425. /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
  3426. * should stop publishing it in new descriptors and eventually close
  3427. * it). */
  3428. static int
  3429. intro_point_should_expire_now(rend_intro_point_t *intro,
  3430. time_t now)
  3431. {
  3432. tor_assert(intro != NULL);
  3433. if (intro->time_published == -1) {
  3434. /* Don't expire an intro point if we haven't even published it yet. */
  3435. return 0;
  3436. }
  3437. if (intro_point_accepted_intro_count(intro) >=
  3438. intro->max_introductions) {
  3439. /* This intro point has been used too many times. Expire it now. */
  3440. return 1;
  3441. }
  3442. if (intro->time_to_expire == -1) {
  3443. /* This intro point has been published, but we haven't picked an
  3444. * expiration time for it. Pick one now. */
  3445. int intro_point_lifetime_seconds =
  3446. crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
  3447. INTRO_POINT_LIFETIME_MAX_SECONDS);
  3448. /* Start the expiration timer now, rather than when the intro
  3449. * point was first published. There shouldn't be much of a time
  3450. * difference. */
  3451. intro->time_to_expire = now + intro_point_lifetime_seconds;
  3452. return 0;
  3453. }
  3454. /* This intro point has a time to expire set already. Use it. */
  3455. return (now >= intro->time_to_expire);
  3456. }
  3457. /** Iterate over intro points in the given service and remove the invalid
  3458. * ones. For an intro point object to be considered invalid, the circuit
  3459. * _and_ node need to have disappeared.
  3460. *
  3461. * If the intro point should expire, it's placed into the expiring_nodes
  3462. * list of the service and removed from the active intro nodes list.
  3463. *
  3464. * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
  3465. *
  3466. * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
  3467. * circuit disappeared but the node is still in the consensus. */
  3468. static void
  3469. remove_invalid_intro_points(rend_service_t *service,
  3470. smartlist_t *exclude_nodes,
  3471. smartlist_t *retry_nodes, time_t now)
  3472. {
  3473. tor_assert(service);
  3474. SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
  3475. intro) {
  3476. /* Find the introduction point node object. */
  3477. const node_t *node =
  3478. node_get_by_id(intro->extend_info->identity_digest);
  3479. /* Find the intro circuit, this might be NULL. */
  3480. origin_circuit_t *intro_circ =
  3481. find_intro_circuit(intro, service->pk_digest);
  3482. /* Add the valid node to the exclusion list so we don't try to establish
  3483. * an introduction point to it again. */
  3484. if (node && exclude_nodes) {
  3485. smartlist_add(exclude_nodes, (void*) node);
  3486. }
  3487. /* First, make sure we still have a valid circuit for this intro point.
  3488. * If we dont, we'll give up on it and make a new one. */
  3489. if (intro_circ == NULL) {
  3490. log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
  3491. " (circuit disappeared).",
  3492. safe_str_client(extend_info_describe(intro->extend_info)),
  3493. safe_str_client(service->service_id));
  3494. /* We've lost the circuit for this intro point, flag it so it can be
  3495. * accounted for when considiring uploading a descriptor. */
  3496. intro->circuit_established = 0;
  3497. /* Node is gone or we've reached our maximum circuit creationg retry
  3498. * count, clean up everything, we'll find a new one. */
  3499. if (node == NULL ||
  3500. intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  3501. rend_intro_point_free(intro);
  3502. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  3503. /* We've just killed the intro point, nothing left to do. */
  3504. continue;
  3505. }
  3506. /* The intro point is still alive so let's try to use it again because
  3507. * we have a published descriptor containing it. Keep the intro point
  3508. * in the intro_nodes list because it's still valid, we are rebuilding
  3509. * a circuit to it. */
  3510. if (retry_nodes) {
  3511. smartlist_add(retry_nodes, intro);
  3512. }
  3513. }
  3514. /* else, the circuit is valid so in both cases, node being alive or not,
  3515. * we leave the circuit and intro point object as is. Closing the
  3516. * circuit here would leak new consensus timing and freeing the intro
  3517. * point object would make the intro circuit unusable. */
  3518. /* Now, check if intro point should expire. If it does, queue it so
  3519. * it can be cleaned up once it has been replaced properly. */
  3520. if (intro_point_should_expire_now(intro, now)) {
  3521. log_info(LD_REND, "Expiring %s as intro point for %s.",
  3522. safe_str_client(extend_info_describe(intro->extend_info)),
  3523. safe_str_client(service->service_id));
  3524. smartlist_add(service->expiring_nodes, intro);
  3525. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  3526. /* Intro point is expired, we need a new one thus don't consider it
  3527. * anymore has a valid established intro point. */
  3528. intro->circuit_established = 0;
  3529. }
  3530. } SMARTLIST_FOREACH_END(intro);
  3531. }
  3532. /** A new descriptor has been successfully uploaded for the given
  3533. * <b>rend_data</b>. Remove and free the expiring nodes from the associated
  3534. * service. */
  3535. void
  3536. rend_service_desc_has_uploaded(const rend_data_t *rend_data)
  3537. {
  3538. rend_service_t *service;
  3539. const char *onion_address;
  3540. tor_assert(rend_data);
  3541. onion_address = rend_data_get_address(rend_data);
  3542. service = rend_service_get_by_service_id(onion_address);
  3543. if (service == NULL) {
  3544. return;
  3545. }
  3546. SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
  3547. intro) {
  3548. origin_circuit_t *intro_circ =
  3549. find_intro_circuit(intro, service->pk_digest);
  3550. if (intro_circ != NULL) {
  3551. circuit_mark_for_close(TO_CIRCUIT(intro_circ),
  3552. END_CIRC_REASON_FINISHED);
  3553. }
  3554. SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
  3555. rend_intro_point_free(intro);
  3556. } SMARTLIST_FOREACH_END(intro);
  3557. }
  3558. /** For every service, check how many intro points it currently has, and:
  3559. * - Invalidate introdution points based on specific criteria, see
  3560. * remove_invalid_intro_points comments.
  3561. * - Pick new intro points as necessary.
  3562. * - Launch circuits to any new intro points.
  3563. *
  3564. * This is called once a second by the main loop.
  3565. */
  3566. void
  3567. rend_consider_services_intro_points(void)
  3568. {
  3569. int i;
  3570. time_t now;
  3571. const or_options_t *options = get_options();
  3572. /* Are we in single onion mode? */
  3573. const int allow_direct = rend_service_allow_non_anonymous_connection(
  3574. get_options());
  3575. /* List of nodes we need to _exclude_ when choosing a new node to
  3576. * establish an intro point to. */
  3577. smartlist_t *exclude_nodes;
  3578. /* List of nodes we need to retry to build a circuit on them because the
  3579. * node is valid but circuit died. */
  3580. smartlist_t *retry_nodes;
  3581. if (!have_completed_a_circuit())
  3582. return;
  3583. exclude_nodes = smartlist_new();
  3584. retry_nodes = smartlist_new();
  3585. now = time(NULL);
  3586. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
  3587. int r;
  3588. /* Number of intro points we want to open and add to the intro nodes
  3589. * list of the service. */
  3590. unsigned int n_intro_points_to_open;
  3591. /* Have an unsigned len so we can use it to compare values else gcc is
  3592. * not happy with unmatching signed comparaison. */
  3593. unsigned int intro_nodes_len;
  3594. /* Different service are allowed to have the same introduction point as
  3595. * long as they are on different circuit thus why we clear this list. */
  3596. smartlist_clear(exclude_nodes);
  3597. smartlist_clear(retry_nodes);
  3598. /* This retry period is important here so we don't stress circuit
  3599. * creation. */
  3600. if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
  3601. /* One period has elapsed; we can try building circuits again. */
  3602. service->intro_period_started = now;
  3603. service->n_intro_circuits_launched = 0;
  3604. } else if (service->n_intro_circuits_launched >=
  3605. MAX_INTRO_CIRCS_PER_PERIOD) {
  3606. /* We have failed too many times in this period; wait for the next
  3607. * one before we try again. */
  3608. continue;
  3609. }
  3610. /* Cleanup the invalid intro points and save the node objects, if apply,
  3611. * in the exclude_nodes and retry_nodes list. */
  3612. remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
  3613. /* Let's try to rebuild circuit on the nodes we want to retry on. */
  3614. SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
  3615. r = rend_service_launch_establish_intro(service, intro);
  3616. if (r < 0) {
  3617. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  3618. safe_str_client(extend_info_describe(intro->extend_info)),
  3619. safe_str_client(service->service_id));
  3620. /* Unable to launch a circuit to that intro point, remove it from
  3621. * the valid list so we can create a new one. */
  3622. smartlist_remove(service->intro_nodes, intro);
  3623. rend_intro_point_free(intro);
  3624. continue;
  3625. }
  3626. intro->circuit_retries++;
  3627. } SMARTLIST_FOREACH_END(intro);
  3628. /* Avoid mismatched signed comparaison below. */
  3629. intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
  3630. /* Quiescent state, no node expiring and we have more or the amount of
  3631. * wanted node for this service. Proceed to the next service. Could be
  3632. * more because we launch two preemptive circuits if our intro nodes
  3633. * list is empty. */
  3634. if (smartlist_len(service->expiring_nodes) == 0 &&
  3635. intro_nodes_len >= service->n_intro_points_wanted) {
  3636. continue;
  3637. }
  3638. /* Number of intro points we want to open which is the wanted amount
  3639. * minus the current amount of valid nodes. */
  3640. n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
  3641. if (intro_nodes_len == 0) {
  3642. /* We want to end up with n_intro_points_wanted intro points, but if
  3643. * we have no intro points at all (chances are they all cycled or we
  3644. * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
  3645. * and use the first n_intro_points_wanted that complete. See proposal
  3646. * #155, section 4 for the rationale of this which is purely for
  3647. * performance.
  3648. *
  3649. * The ones after the first n_intro_points_to_open will be converted
  3650. * to 'general' internal circuits in rend_service_intro_has_opened(),
  3651. * and then we'll drop them from the list of intro points. */
  3652. n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
  3653. }
  3654. for (i = 0; i < (int) n_intro_points_to_open; i++) {
  3655. const node_t *node;
  3656. rend_intro_point_t *intro;
  3657. router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
  3658. if (get_options()->AllowInvalid_ & ALLOW_INVALID_INTRODUCTION)
  3659. flags |= CRN_ALLOW_INVALID;
  3660. router_crn_flags_t direct_flags = flags;
  3661. direct_flags |= CRN_PREF_ADDR;
  3662. direct_flags |= CRN_DIRECT_CONN;
  3663. node = router_choose_random_node(exclude_nodes,
  3664. options->ExcludeNodes,
  3665. allow_direct ? direct_flags : flags);
  3666. /* If we are in single onion mode, retry node selection for a 3-hop
  3667. * path */
  3668. if (allow_direct && !node) {
  3669. log_info(LD_REND,
  3670. "Unable to find an intro point that we can connect to "
  3671. "directly for %s, falling back to a 3-hop path.",
  3672. safe_str_client(service->service_id));
  3673. node = router_choose_random_node(exclude_nodes,
  3674. options->ExcludeNodes, flags);
  3675. }
  3676. if (!node) {
  3677. log_warn(LD_REND,
  3678. "We only have %d introduction points established for %s; "
  3679. "wanted %u.",
  3680. smartlist_len(service->intro_nodes),
  3681. safe_str_client(service->service_id),
  3682. n_intro_points_to_open);
  3683. break;
  3684. }
  3685. /* Add the choosen node to the exclusion list in order to avoid picking
  3686. * it again in the next iteration. */
  3687. smartlist_add(exclude_nodes, (void*)node);
  3688. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3689. /* extend_info is for clients, so we want the multi-hop primary ORPort,
  3690. * even if we are a single onion service and intend to connect to it
  3691. * directly ourselves. */
  3692. intro->extend_info = extend_info_from_node(node, 0);
  3693. intro->intro_key = crypto_pk_new();
  3694. const int fail = crypto_pk_generate_key(intro->intro_key);
  3695. tor_assert(!fail);
  3696. intro->time_published = -1;
  3697. intro->time_to_expire = -1;
  3698. intro->max_introductions =
  3699. crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  3700. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
  3701. smartlist_add(service->intro_nodes, intro);
  3702. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  3703. safe_str_client(node_describe(node)),
  3704. safe_str_client(service->service_id));
  3705. /* Establish new introduction circuit to our chosen intro point. */
  3706. r = rend_service_launch_establish_intro(service, intro);
  3707. if (r < 0) {
  3708. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  3709. safe_str_client(extend_info_describe(intro->extend_info)),
  3710. safe_str_client(service->service_id));
  3711. /* This funcion will be called again by the main loop so this intro
  3712. * point without a intro circuit will be retried on or removed after
  3713. * a maximum number of attempts. */
  3714. }
  3715. }
  3716. } SMARTLIST_FOREACH_END(service);
  3717. smartlist_free(exclude_nodes);
  3718. smartlist_free(retry_nodes);
  3719. }
  3720. #define MIN_REND_INITIAL_POST_DELAY (30)
  3721. #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
  3722. /** Regenerate and upload rendezvous service descriptors for all
  3723. * services, if necessary. If the descriptor has been dirty enough
  3724. * for long enough, definitely upload; else only upload when the
  3725. * periodic timeout has expired.
  3726. *
  3727. * For the first upload, pick a random time between now and two periods
  3728. * from now, and pick it independently for each service.
  3729. */
  3730. void
  3731. rend_consider_services_upload(time_t now)
  3732. {
  3733. int i;
  3734. rend_service_t *service;
  3735. const or_options_t *options = get_options();
  3736. int rendpostperiod = options->RendPostPeriod;
  3737. int rendinitialpostdelay = (options->TestingTorNetwork ?
  3738. MIN_REND_INITIAL_POST_DELAY_TESTING :
  3739. MIN_REND_INITIAL_POST_DELAY);
  3740. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3741. service = smartlist_get(rend_service_list, i);
  3742. if (!service->next_upload_time) { /* never been uploaded yet */
  3743. /* The fixed lower bound of rendinitialpostdelay seconds ensures that
  3744. * the descriptor is stable before being published. See comment below. */
  3745. service->next_upload_time =
  3746. now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
  3747. /* Single Onion Services prioritise availability over hiding their
  3748. * startup time, as their IP address is publicly discoverable anyway.
  3749. */
  3750. if (rend_service_reveal_startup_time(options)) {
  3751. service->next_upload_time = now + rendinitialpostdelay;
  3752. }
  3753. }
  3754. /* Does every introduction points have been established? */
  3755. unsigned int intro_points_ready =
  3756. count_established_intro_points(service) >=
  3757. service->n_intro_points_wanted;
  3758. if (intro_points_ready &&
  3759. (service->next_upload_time < now ||
  3760. (service->desc_is_dirty &&
  3761. service->desc_is_dirty < now-rendinitialpostdelay))) {
  3762. /* if it's time, or if the directory servers have a wrong service
  3763. * descriptor and ours has been stable for rendinitialpostdelay seconds,
  3764. * upload a new one of each format. */
  3765. rend_service_update_descriptor(service);
  3766. upload_service_descriptor(service);
  3767. }
  3768. }
  3769. }
  3770. /** True if the list of available router descriptors might have changed so
  3771. * that we should have a look whether we can republish previously failed
  3772. * rendezvous service descriptors. */
  3773. static int consider_republishing_rend_descriptors = 1;
  3774. /** Called when our internal view of the directory has changed, so that we
  3775. * might have router descriptors of hidden service directories available that
  3776. * we did not have before. */
  3777. void
  3778. rend_hsdir_routers_changed(void)
  3779. {
  3780. consider_republishing_rend_descriptors = 1;
  3781. }
  3782. /** Consider republication of v2 rendezvous service descriptors that failed
  3783. * previously, but without regenerating descriptor contents.
  3784. */
  3785. void
  3786. rend_consider_descriptor_republication(void)
  3787. {
  3788. int i;
  3789. rend_service_t *service;
  3790. if (!consider_republishing_rend_descriptors)
  3791. return;
  3792. consider_republishing_rend_descriptors = 0;
  3793. if (!get_options()->PublishHidServDescriptors)
  3794. return;
  3795. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3796. service = smartlist_get(rend_service_list, i);
  3797. if (service->desc && !service->desc->all_uploads_performed) {
  3798. /* If we failed in uploading a descriptor last time, try again *without*
  3799. * updating the descriptor's contents. */
  3800. upload_service_descriptor(service);
  3801. }
  3802. }
  3803. }
  3804. /** Log the status of introduction points for all rendezvous services
  3805. * at log severity <b>severity</b>.
  3806. */
  3807. void
  3808. rend_service_dump_stats(int severity)
  3809. {
  3810. int i,j;
  3811. rend_service_t *service;
  3812. rend_intro_point_t *intro;
  3813. const char *safe_name;
  3814. origin_circuit_t *circ;
  3815. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3816. service = smartlist_get(rend_service_list, i);
  3817. tor_log(severity, LD_GENERAL, "Service configured in %s:",
  3818. rend_service_escaped_dir(service));
  3819. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  3820. intro = smartlist_get(service->intro_nodes, j);
  3821. safe_name = safe_str_client(intro->extend_info->nickname);
  3822. circ = find_intro_circuit(intro, service->pk_digest);
  3823. if (!circ) {
  3824. tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  3825. j, safe_name);
  3826. continue;
  3827. }
  3828. tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  3829. j, safe_name, circuit_state_to_string(circ->base_.state));
  3830. }
  3831. }
  3832. }
  3833. #ifdef HAVE_SYS_UN_H
  3834. /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
  3835. * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
  3836. * else return -ENOSYS if AF_UNIX is not supported (see function in the
  3837. * #else statement below). */
  3838. static int
  3839. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  3840. {
  3841. tor_assert(ports);
  3842. tor_assert(p);
  3843. tor_assert(p->is_unix_addr);
  3844. smartlist_add(ports, p);
  3845. return 0;
  3846. }
  3847. /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
  3848. * on success else return -ENOSYS if AF_UNIX is not supported (see function
  3849. * in the #else statement below). */
  3850. static int
  3851. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  3852. {
  3853. tor_assert(conn);
  3854. tor_assert(p);
  3855. tor_assert(p->is_unix_addr);
  3856. conn->base_.socket_family = AF_UNIX;
  3857. tor_addr_make_unspec(&conn->base_.addr);
  3858. conn->base_.port = 1;
  3859. conn->base_.address = tor_strdup(p->unix_addr);
  3860. return 0;
  3861. }
  3862. #else /* defined(HAVE_SYS_UN_H) */
  3863. static int
  3864. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  3865. {
  3866. (void) conn;
  3867. (void) p;
  3868. return -ENOSYS;
  3869. }
  3870. static int
  3871. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  3872. {
  3873. (void) ports;
  3874. (void) p;
  3875. return -ENOSYS;
  3876. }
  3877. #endif /* HAVE_SYS_UN_H */
  3878. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  3879. * 'circ', and look up the port and address based on conn-\>port.
  3880. * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
  3881. * for which the circuit should be closed, -1 on other failure,
  3882. * or 0 for success.
  3883. */
  3884. int
  3885. rend_service_set_connection_addr_port(edge_connection_t *conn,
  3886. origin_circuit_t *circ)
  3887. {
  3888. rend_service_t *service;
  3889. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3890. smartlist_t *matching_ports;
  3891. rend_service_port_config_t *chosen_port;
  3892. unsigned int warn_once = 0;
  3893. const char *rend_pk_digest;
  3894. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3895. tor_assert(circ->rend_data);
  3896. log_debug(LD_REND,"beginning to hunt for addr/port");
  3897. /* XXX: This is version 2 specific (only one supported). */
  3898. rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
  3899. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  3900. rend_pk_digest, REND_SERVICE_ID_LEN);
  3901. service = rend_service_get_by_pk_digest(rend_pk_digest);
  3902. if (!service) {
  3903. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  3904. "rendezvous circuit %u; closing.",
  3905. serviceid, (unsigned)circ->base_.n_circ_id);
  3906. return -2;
  3907. }
  3908. if (service->max_streams_per_circuit > 0) {
  3909. /* Enforce the streams-per-circuit limit, and refuse to provide a
  3910. * mapping if this circuit will exceed the limit. */
  3911. #define MAX_STREAM_WARN_INTERVAL 600
  3912. static struct ratelim_t stream_ratelim =
  3913. RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
  3914. if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
  3915. log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
  3916. "Maximum streams per circuit limit reached on rendezvous "
  3917. "circuit %u; %s. Circuit has %d out of %d streams.",
  3918. (unsigned)circ->base_.n_circ_id,
  3919. service->max_streams_close_circuit ?
  3920. "closing circuit" :
  3921. "ignoring open stream request",
  3922. circ->rend_data->nr_streams,
  3923. service->max_streams_per_circuit);
  3924. return service->max_streams_close_circuit ? -2 : -1;
  3925. }
  3926. }
  3927. matching_ports = smartlist_new();
  3928. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  3929. {
  3930. if (conn->base_.port != p->virtual_port) {
  3931. continue;
  3932. }
  3933. if (!(p->is_unix_addr)) {
  3934. smartlist_add(matching_ports, p);
  3935. } else {
  3936. if (add_unix_port(matching_ports, p)) {
  3937. if (!warn_once) {
  3938. /* Unix port not supported so warn only once. */
  3939. log_warn(LD_REND,
  3940. "Saw AF_UNIX virtual port mapping for port %d on service "
  3941. "%s, which is unsupported on this platform. Ignoring it.",
  3942. conn->base_.port, serviceid);
  3943. }
  3944. warn_once++;
  3945. }
  3946. }
  3947. });
  3948. chosen_port = smartlist_choose(matching_ports);
  3949. smartlist_free(matching_ports);
  3950. if (chosen_port) {
  3951. if (!(chosen_port->is_unix_addr)) {
  3952. /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
  3953. tor_addr_copy(&conn->base_.addr, &chosen_port->real_addr);
  3954. conn->base_.port = chosen_port->real_port;
  3955. } else {
  3956. if (set_unix_port(conn, chosen_port)) {
  3957. /* Simply impossible to end up here else we were able to add a Unix
  3958. * port without AF_UNIX support... ? */
  3959. tor_assert(0);
  3960. }
  3961. }
  3962. return 0;
  3963. }
  3964. log_info(LD_REND,
  3965. "No virtual port mapping exists for port %d on service %s",
  3966. conn->base_.port, serviceid);
  3967. if (service->allow_unknown_ports)
  3968. return -1;
  3969. else
  3970. return -2;
  3971. }
  3972. /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
  3973. */
  3974. static int
  3975. rend_service_non_anonymous_mode_consistent(const or_options_t *options)
  3976. {
  3977. /* !! is used to make these options boolean */
  3978. return (!! options->HiddenServiceSingleHopMode ==
  3979. !! options->HiddenServiceNonAnonymousMode);
  3980. }
  3981. /* Do the options allow onion services to make direct (non-anonymous)
  3982. * connections to introduction or rendezvous points?
  3983. * Must only be called after options_validate_single_onion() has successfully
  3984. * checked onion service option consistency.
  3985. * Returns true if tor is in HiddenServiceSingleHopMode. */
  3986. int
  3987. rend_service_allow_non_anonymous_connection(const or_options_t *options)
  3988. {
  3989. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  3990. return options->HiddenServiceSingleHopMode ? 1 : 0;
  3991. }
  3992. /* Do the options allow us to reveal the exact startup time of the onion
  3993. * service?
  3994. * Single Onion Services prioritise availability over hiding their
  3995. * startup time, as their IP address is publicly discoverable anyway.
  3996. * Must only be called after options_validate_single_onion() has successfully
  3997. * checked onion service option consistency.
  3998. * Returns true if tor is in non-anonymous hidden service mode. */
  3999. int
  4000. rend_service_reveal_startup_time(const or_options_t *options)
  4001. {
  4002. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  4003. return rend_service_non_anonymous_mode_enabled(options);
  4004. }
  4005. /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
  4006. * config option?
  4007. * Must only be called after options_validate_single_onion() has successfully
  4008. * checked onion service option consistency.
  4009. */
  4010. int
  4011. rend_service_non_anonymous_mode_enabled(const or_options_t *options)
  4012. {
  4013. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  4014. return options->HiddenServiceNonAnonymousMode ? 1 : 0;
  4015. }