rendservice.c 155 KB

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