rendservice.c 117 KB

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