rendservice.c 152 KB

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