rendservice.c 133 KB

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