rendservice.c 155 KB

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