rendservice.c 145 KB

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