rendservice.c 156 KB

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