rendservice.c 159 KB

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