rendservice.c 155 KB

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