rendservice.c 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2009, 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. #include "or.h"
  9. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  10. const char *pk_digest,
  11. int desc_version);
  12. /** Represents the mapping from a virtual port of a rendezvous service to
  13. * a real port on some IP.
  14. */
  15. typedef struct rend_service_port_config_t {
  16. uint16_t virtual_port;
  17. uint16_t real_port;
  18. tor_addr_t real_addr;
  19. } rend_service_port_config_t;
  20. /** Try to maintain this many intro points per service if possible. */
  21. #define NUM_INTRO_POINTS 3
  22. /** If we can't build our intro circuits, don't retry for this long. */
  23. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  24. /** Don't try to build more than this many circuits before giving up
  25. * for a while.*/
  26. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  27. /** How many times will a hidden service operator attempt to connect to
  28. * a requested rendezvous point before giving up? */
  29. #define MAX_REND_FAILURES 30
  30. /** How many seconds should we spend trying to connect to a requested
  31. * rendezvous point before giving up? */
  32. #define MAX_REND_TIMEOUT 30
  33. /** Represents a single hidden service running at this OP. */
  34. typedef struct rend_service_t {
  35. /* Fields specified in config file */
  36. char *directory; /**< where in the filesystem it stores it */
  37. smartlist_t *ports; /**< List of rend_service_port_config_t */
  38. rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
  39. * authorization is performed. */
  40. smartlist_t *clients; /**< List of rend_authorized_client_t's of
  41. * clients that may access our service. Can be NULL
  42. * if no client authorization is peformed. */
  43. /* Other fields */
  44. crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
  45. char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
  46. * '.onion' */
  47. char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
  48. smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
  49. * or are trying to establish. */
  50. time_t intro_period_started; /**< Start of the current period to build
  51. * introduction points. */
  52. int n_intro_circuits_launched; /**< count of intro circuits we have
  53. * established in this period. */
  54. rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  55. time_t desc_is_dirty; /**< Time at which changes to the hidden service
  56. * descriptor content occurred, or 0 if it's
  57. * up-to-date. */
  58. time_t next_upload_time; /**< Scheduled next hidden service descriptor
  59. * upload time. */
  60. /** Map from digests of diffie-hellman values INTRODUCE2 to time_t of when
  61. * they were received; used to prevent replays. */
  62. digestmap_t *accepted_intros;
  63. /** Time at which we last removed expired values from accepted_intros. */
  64. time_t last_cleaned_accepted_intros;
  65. } rend_service_t;
  66. /** A list of rend_service_t's for services run on this OP.
  67. */
  68. static smartlist_t *rend_service_list = NULL;
  69. /** Return the number of rendezvous services we have configured. */
  70. int
  71. num_rend_services(void)
  72. {
  73. if (!rend_service_list)
  74. return 0;
  75. return smartlist_len(rend_service_list);
  76. }
  77. /** Helper: free storage held by a single service authorized client entry. */
  78. static void
  79. rend_authorized_client_free(rend_authorized_client_t *client)
  80. {
  81. if (!client) return;
  82. if (client->client_key)
  83. crypto_free_pk_env(client->client_key);
  84. tor_free(client->client_name);
  85. tor_free(client);
  86. }
  87. /** Helper for strmap_free. */
  88. static void
  89. rend_authorized_client_strmap_item_free(void *authorized_client)
  90. {
  91. rend_authorized_client_free(authorized_client);
  92. }
  93. /** Release the storage held by <b>service</b>.
  94. */
  95. static void
  96. rend_service_free(rend_service_t *service)
  97. {
  98. if (!service) return;
  99. tor_free(service->directory);
  100. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  101. smartlist_free(service->ports);
  102. if (service->private_key)
  103. crypto_free_pk_env(service->private_key);
  104. if (service->intro_nodes) {
  105. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  106. rend_intro_point_free(intro););
  107. smartlist_free(service->intro_nodes);
  108. }
  109. if (service->desc)
  110. rend_service_descriptor_free(service->desc);
  111. if (service->clients) {
  112. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  113. rend_authorized_client_free(c););
  114. smartlist_free(service->clients);
  115. }
  116. if (service->accepted_intros)
  117. digestmap_free(service->accepted_intros, _tor_free);
  118. tor_free(service);
  119. }
  120. /** Release all the storage held in rend_service_list.
  121. */
  122. void
  123. rend_service_free_all(void)
  124. {
  125. if (!rend_service_list) {
  126. return;
  127. }
  128. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  129. rend_service_free(ptr));
  130. smartlist_free(rend_service_list);
  131. rend_service_list = NULL;
  132. }
  133. /** Validate <b>service</b> and add it to rend_service_list if possible.
  134. */
  135. static void
  136. rend_add_service(rend_service_t *service)
  137. {
  138. int i;
  139. rend_service_port_config_t *p;
  140. service->intro_nodes = smartlist_create();
  141. if (service->auth_type != REND_NO_AUTH &&
  142. smartlist_len(service->clients) == 0) {
  143. log_warn(LD_CONFIG, "Hidden service with client authorization but no "
  144. "clients; ignoring.");
  145. rend_service_free(service);
  146. return;
  147. }
  148. if (!smartlist_len(service->ports)) {
  149. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  150. rend_service_free(service);
  151. } else {
  152. smartlist_add(rend_service_list, service);
  153. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  154. service->directory);
  155. for (i = 0; i < smartlist_len(service->ports); ++i) {
  156. p = smartlist_get(service->ports, i);
  157. log_debug(LD_REND,"Service maps port %d to %s:%d",
  158. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  159. }
  160. }
  161. }
  162. /** Parses a real-port to virtual-port mapping and returns a new
  163. * rend_service_port_config_t.
  164. *
  165. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  166. *
  167. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  168. */
  169. static rend_service_port_config_t *
  170. parse_port_config(const char *string)
  171. {
  172. smartlist_t *sl;
  173. int virtport;
  174. int realport;
  175. uint16_t p;
  176. tor_addr_t addr;
  177. const char *addrport;
  178. rend_service_port_config_t *result = NULL;
  179. sl = smartlist_create();
  180. smartlist_split_string(sl, string, " ",
  181. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  182. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  183. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  184. goto err;
  185. }
  186. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  187. if (!virtport) {
  188. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  189. "configuration", escaped(smartlist_get(sl,0)));
  190. goto err;
  191. }
  192. if (smartlist_len(sl) == 1) {
  193. /* No addr:port part; use default. */
  194. realport = virtport;
  195. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  196. } else {
  197. addrport = smartlist_get(sl,1);
  198. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  199. if (tor_addr_port_parse(addrport, &addr, &p)<0) {
  200. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  201. "configuration.");
  202. goto err;
  203. }
  204. realport = p?p:virtport;
  205. } else {
  206. /* No addr:port, no addr -- must be port. */
  207. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  208. if (!realport) {
  209. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  210. "service port configuration.", escaped(addrport));
  211. goto err;
  212. }
  213. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  214. }
  215. }
  216. result = tor_malloc(sizeof(rend_service_port_config_t));
  217. result->virtual_port = virtport;
  218. result->real_port = realport;
  219. tor_addr_copy(&result->real_addr, &addr);
  220. err:
  221. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  222. smartlist_free(sl);
  223. return result;
  224. }
  225. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  226. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  227. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  228. * normal, but don't actually change the configured services.)
  229. */
  230. int
  231. rend_config_services(or_options_t *options, int validate_only)
  232. {
  233. config_line_t *line;
  234. rend_service_t *service = NULL;
  235. rend_service_port_config_t *portcfg;
  236. smartlist_t *old_service_list = NULL;
  237. if (!validate_only) {
  238. old_service_list = rend_service_list;
  239. rend_service_list = smartlist_create();
  240. }
  241. for (line = options->RendConfigLines; line; line = line->next) {
  242. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  243. if (service) {
  244. if (validate_only)
  245. rend_service_free(service);
  246. else
  247. rend_add_service(service);
  248. }
  249. service = tor_malloc_zero(sizeof(rend_service_t));
  250. service->directory = tor_strdup(line->value);
  251. service->ports = smartlist_create();
  252. service->intro_period_started = time(NULL);
  253. continue;
  254. }
  255. if (!service) {
  256. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  257. line->key);
  258. rend_service_free(service);
  259. return -1;
  260. }
  261. if (!strcasecmp(line->key, "HiddenServicePort")) {
  262. portcfg = parse_port_config(line->value);
  263. if (!portcfg) {
  264. rend_service_free(service);
  265. return -1;
  266. }
  267. smartlist_add(service->ports, portcfg);
  268. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  269. /* Parse auth type and comma-separated list of client names and add a
  270. * rend_authorized_client_t for each client to the service's list
  271. * of authorized clients. */
  272. smartlist_t *type_names_split, *clients;
  273. const char *authname;
  274. int num_clients;
  275. if (service->auth_type != REND_NO_AUTH) {
  276. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  277. "lines for a single service.");
  278. rend_service_free(service);
  279. return -1;
  280. }
  281. type_names_split = smartlist_create();
  282. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  283. if (smartlist_len(type_names_split) < 1) {
  284. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  285. "should have been prevented when parsing the "
  286. "configuration.");
  287. smartlist_free(type_names_split);
  288. rend_service_free(service);
  289. return -1;
  290. }
  291. authname = smartlist_get(type_names_split, 0);
  292. if (!strcasecmp(authname, "basic")) {
  293. service->auth_type = REND_BASIC_AUTH;
  294. } else if (!strcasecmp(authname, "stealth")) {
  295. service->auth_type = REND_STEALTH_AUTH;
  296. } else {
  297. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  298. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  299. "are recognized.",
  300. (char *) smartlist_get(type_names_split, 0));
  301. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  302. smartlist_free(type_names_split);
  303. rend_service_free(service);
  304. return -1;
  305. }
  306. service->clients = smartlist_create();
  307. if (smartlist_len(type_names_split) < 2) {
  308. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  309. "auth-type '%s', but no client names.",
  310. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  311. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  312. smartlist_free(type_names_split);
  313. continue;
  314. }
  315. clients = smartlist_create();
  316. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  317. ",", SPLIT_SKIP_SPACE, 0);
  318. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  319. smartlist_free(type_names_split);
  320. /* Remove duplicate client names. */
  321. num_clients = smartlist_len(clients);
  322. smartlist_sort_strings(clients);
  323. smartlist_uniq_strings(clients);
  324. if (smartlist_len(clients) < num_clients) {
  325. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  326. "duplicate client name(s); removing.",
  327. num_clients - smartlist_len(clients));
  328. num_clients = smartlist_len(clients);
  329. }
  330. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  331. {
  332. rend_authorized_client_t *client;
  333. size_t len = strlen(client_name);
  334. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  335. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  336. "illegal client name: '%s'. Length must be "
  337. "between 1 and %d characters.",
  338. client_name, REND_CLIENTNAME_MAX_LEN);
  339. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  340. smartlist_free(clients);
  341. rend_service_free(service);
  342. return -1;
  343. }
  344. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  345. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  346. "illegal client name: '%s'. Valid "
  347. "characters are [A-Za-z0-9+-_].",
  348. client_name);
  349. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  350. smartlist_free(clients);
  351. rend_service_free(service);
  352. return -1;
  353. }
  354. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  355. client->client_name = tor_strdup(client_name);
  356. smartlist_add(service->clients, client);
  357. log_debug(LD_REND, "Adding client name '%s'", client_name);
  358. }
  359. SMARTLIST_FOREACH_END(client_name);
  360. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  361. smartlist_free(clients);
  362. /* Ensure maximum number of clients. */
  363. if ((service->auth_type == REND_BASIC_AUTH &&
  364. smartlist_len(service->clients) > 512) ||
  365. (service->auth_type == REND_STEALTH_AUTH &&
  366. smartlist_len(service->clients) > 16)) {
  367. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  368. "client authorization entries, but only a "
  369. "maximum of %d entries is allowed for "
  370. "authorization type '%s'.",
  371. smartlist_len(service->clients),
  372. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  373. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  374. rend_service_free(service);
  375. return -1;
  376. }
  377. } else {
  378. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  379. if (strcmp(line->value, "2")) {
  380. log_warn(LD_CONFIG,
  381. "The only supported HiddenServiceVersion is 2.");
  382. rend_service_free(service);
  383. return -1;
  384. }
  385. }
  386. }
  387. if (service) {
  388. if (validate_only)
  389. rend_service_free(service);
  390. else
  391. rend_add_service(service);
  392. }
  393. /* If this is a reload and there were hidden services configured before,
  394. * keep the introduction points that are still needed and close the
  395. * other ones. */
  396. if (old_service_list && !validate_only) {
  397. smartlist_t *surviving_services = smartlist_create();
  398. circuit_t *circ;
  399. /* Copy introduction points to new services. */
  400. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  401. * probably ok? */
  402. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
  403. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  404. if (!strcmp(old->directory, new->directory)) {
  405. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  406. smartlist_clear(old->intro_nodes);
  407. smartlist_add(surviving_services, old);
  408. break;
  409. }
  410. });
  411. });
  412. /* Close introduction circuits of services we don't serve anymore. */
  413. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  414. * so we could just iterate over the list of services to close, but
  415. * once again, this isn't critical-path code. */
  416. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  417. if (!circ->marked_for_close &&
  418. circ->state == CIRCUIT_STATE_OPEN &&
  419. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  420. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  421. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  422. int keep_it = 0;
  423. tor_assert(oc->rend_data);
  424. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  425. if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  426. DIGEST_LEN)) {
  427. keep_it = 1;
  428. break;
  429. }
  430. });
  431. if (keep_it)
  432. continue;
  433. log_info(LD_REND, "Closing intro point %s for service %s version %d.",
  434. safe_str(oc->build_state->chosen_exit->nickname),
  435. oc->rend_data->onion_address,
  436. oc->rend_data->rend_desc_version);
  437. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  438. /* XXXX Is there another reason we should use here? */
  439. }
  440. }
  441. smartlist_free(surviving_services);
  442. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  443. rend_service_free(ptr));
  444. smartlist_free(old_service_list);
  445. }
  446. return 0;
  447. }
  448. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  449. * the other fields in service.
  450. */
  451. static void
  452. rend_service_update_descriptor(rend_service_t *service)
  453. {
  454. rend_service_descriptor_t *d;
  455. origin_circuit_t *circ;
  456. int i;
  457. if (service->desc) {
  458. rend_service_descriptor_free(service->desc);
  459. service->desc = NULL;
  460. }
  461. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  462. d->pk = crypto_pk_dup_key(service->private_key);
  463. d->timestamp = time(NULL);
  464. d->intro_nodes = smartlist_create();
  465. /* Support intro protocols 2 and 3. */
  466. d->protocols = (1 << 2) + (1 << 3);
  467. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  468. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  469. rend_intro_point_t *intro_desc;
  470. circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
  471. if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
  472. continue;
  473. /* We have an entirely established intro circuit. */
  474. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  475. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  476. if (intro_svc->intro_key)
  477. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  478. smartlist_add(d->intro_nodes, intro_desc);
  479. }
  480. }
  481. /** Load and/or generate private keys for all hidden services, possibly
  482. * including keys for client authorization. Return 0 on success, -1 on
  483. * failure.
  484. */
  485. int
  486. rend_service_load_keys(void)
  487. {
  488. int r = 0;
  489. char fname[512];
  490. char buf[1500];
  491. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  492. if (s->private_key)
  493. continue;
  494. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  495. s->directory);
  496. /* Check/create directory */
  497. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  498. return -1;
  499. /* Load key */
  500. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  501. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  502. >= sizeof(fname)) {
  503. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  504. s->directory);
  505. return -1;
  506. }
  507. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  508. if (!s->private_key)
  509. return -1;
  510. /* Create service file */
  511. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  512. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  513. return -1;
  514. }
  515. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  516. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  517. return -1;
  518. }
  519. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  520. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  521. >= sizeof(fname)) {
  522. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  523. " \"%s\".", s->directory);
  524. return -1;
  525. }
  526. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  527. if (write_str_to_file(fname,buf,0)<0) {
  528. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  529. return -1;
  530. }
  531. /* If client authorization is configured, load or generate keys. */
  532. if (s->auth_type != REND_NO_AUTH) {
  533. char *client_keys_str = NULL;
  534. strmap_t *parsed_clients = strmap_new();
  535. char cfname[512];
  536. FILE *cfile, *hfile;
  537. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  538. /* Load client keys and descriptor cookies, if available. */
  539. if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
  540. s->directory)<0) {
  541. log_warn(LD_CONFIG, "Directory name too long to store client keys "
  542. "file: \"%s\".", s->directory);
  543. goto err;
  544. }
  545. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  546. if (client_keys_str) {
  547. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  548. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  549. "be parsed.");
  550. goto err;
  551. } else {
  552. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  553. strmap_size(parsed_clients));
  554. tor_free(client_keys_str);
  555. }
  556. }
  557. /* Prepare client_keys and hostname files. */
  558. if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
  559. 0600, &open_cfile))) {
  560. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  561. escaped(cfname));
  562. goto err;
  563. }
  564. if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
  565. 0600, &open_hfile))) {
  566. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
  567. goto err;
  568. }
  569. /* Either use loaded keys for configured clients or generate new
  570. * ones if a client is new. */
  571. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
  572. {
  573. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  574. char service_id[16+1];
  575. rend_authorized_client_t *parsed =
  576. strmap_get(parsed_clients, client->client_name);
  577. int written;
  578. size_t len;
  579. /* Copy descriptor cookie from parsed entry or create new one. */
  580. if (parsed) {
  581. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  582. REND_DESC_COOKIE_LEN);
  583. } else {
  584. crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  585. }
  586. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  587. client->descriptor_cookie,
  588. REND_DESC_COOKIE_LEN) < 0) {
  589. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  590. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  591. return -1;
  592. }
  593. /* Copy client key from parsed entry or create new one if required. */
  594. if (parsed && parsed->client_key) {
  595. client->client_key = crypto_pk_dup_key(parsed->client_key);
  596. } else if (s->auth_type == REND_STEALTH_AUTH) {
  597. /* Create private key for client. */
  598. crypto_pk_env_t *prkey = NULL;
  599. if (!(prkey = crypto_new_pk_env())) {
  600. log_warn(LD_BUG,"Error constructing client key");
  601. goto err;
  602. }
  603. if (crypto_pk_generate_key(prkey)) {
  604. log_warn(LD_BUG,"Error generating client key");
  605. crypto_free_pk_env(prkey);
  606. goto err;
  607. }
  608. if (crypto_pk_check_key(prkey) <= 0) {
  609. log_warn(LD_BUG,"Generated client key seems invalid");
  610. crypto_free_pk_env(prkey);
  611. goto err;
  612. }
  613. client->client_key = prkey;
  614. }
  615. /* Add entry to client_keys file. */
  616. desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
  617. written = tor_snprintf(buf, sizeof(buf),
  618. "client-name %s\ndescriptor-cookie %s\n",
  619. client->client_name, desc_cook_out);
  620. if (written < 0) {
  621. log_warn(LD_BUG, "Could not write client entry.");
  622. goto err;
  623. }
  624. if (client->client_key) {
  625. char *client_key_out = NULL;
  626. crypto_pk_write_private_key_to_string(client->client_key,
  627. &client_key_out, &len);
  628. if (rend_get_service_id(client->client_key, service_id)<0) {
  629. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  630. tor_free(client_key_out);
  631. goto err;
  632. }
  633. written = tor_snprintf(buf + written, sizeof(buf) - written,
  634. "client-key\n%s", client_key_out);
  635. tor_free(client_key_out);
  636. if (written < 0) {
  637. log_warn(LD_BUG, "Could not write client entry.");
  638. goto err;
  639. }
  640. }
  641. if (fputs(buf, cfile) < 0) {
  642. log_warn(LD_FS, "Could not append client entry to file: %s",
  643. strerror(errno));
  644. goto err;
  645. }
  646. /* Add line to hostname file. */
  647. if (s->auth_type == REND_BASIC_AUTH) {
  648. /* Remove == signs (newline has been removed above). */
  649. desc_cook_out[strlen(desc_cook_out)-2] = '\0';
  650. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  651. s->service_id, desc_cook_out, client->client_name);
  652. } else {
  653. char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
  654. memcpy(extended_desc_cookie, client->descriptor_cookie,
  655. REND_DESC_COOKIE_LEN);
  656. extended_desc_cookie[REND_DESC_COOKIE_LEN] =
  657. ((int)s->auth_type - 1) << 4;
  658. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  659. extended_desc_cookie,
  660. REND_DESC_COOKIE_LEN+1) < 0) {
  661. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  662. goto err;
  663. }
  664. desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
  665. newline. */
  666. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  667. service_id, desc_cook_out, client->client_name);
  668. }
  669. if (fputs(buf, hfile)<0) {
  670. log_warn(LD_FS, "Could not append host entry to file: %s",
  671. strerror(errno));
  672. goto err;
  673. }
  674. }
  675. SMARTLIST_FOREACH_END(client);
  676. goto done;
  677. err:
  678. r = -1;
  679. done:
  680. tor_free(client_keys_str);
  681. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  682. if (r<0) {
  683. if (open_cfile)
  684. abort_writing_to_file(open_cfile);
  685. if (open_hfile)
  686. abort_writing_to_file(open_hfile);
  687. return r;
  688. } else {
  689. finish_writing_to_file(open_cfile);
  690. finish_writing_to_file(open_hfile);
  691. }
  692. }
  693. } SMARTLIST_FOREACH_END(s);
  694. return r;
  695. }
  696. /** Return the service whose public key has a digest of <b>digest</b> and
  697. * which publishes the given descriptor <b>version</b>. (There is no other
  698. * version than 2, so version is ignored.) Return NULL if no such service
  699. * exists.
  700. */
  701. static rend_service_t *
  702. rend_service_get_by_pk_digest_and_version(const char* digest,
  703. uint8_t version)
  704. {
  705. (void) version;
  706. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  707. if (!memcmp(s->pk_digest,digest,DIGEST_LEN))
  708. return s);
  709. return NULL;
  710. }
  711. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  712. * to have good uptime. Else return 0.
  713. */
  714. static int
  715. rend_service_requires_uptime(rend_service_t *service)
  716. {
  717. int i;
  718. rend_service_port_config_t *p;
  719. for (i=0; i < smartlist_len(service->ports); ++i) {
  720. p = smartlist_get(service->ports, i);
  721. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  722. p->virtual_port))
  723. return 1;
  724. }
  725. return 0;
  726. }
  727. /** Check client authorization of a given <b>descriptor_cookie</b> for
  728. * <b>service</b>. Return 1 for success and 0 for failure. */
  729. static int
  730. rend_check_authorization(rend_service_t *service,
  731. const char *descriptor_cookie)
  732. {
  733. rend_authorized_client_t *auth_client = NULL;
  734. tor_assert(service);
  735. tor_assert(descriptor_cookie);
  736. if (!service->clients) {
  737. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  738. "authorized clients configured.");
  739. return 0;
  740. }
  741. /* Look up client authorization by descriptor cookie. */
  742. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  743. if (!memcmp(client->descriptor_cookie, descriptor_cookie,
  744. REND_DESC_COOKIE_LEN)) {
  745. auth_client = client;
  746. break;
  747. }
  748. });
  749. if (!auth_client) {
  750. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  751. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  752. descriptor_cookie, REND_DESC_COOKIE_LEN);
  753. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  754. "Dropping cell!",
  755. descriptor_cookie_base64);
  756. return 0;
  757. }
  758. /* Allow the request. */
  759. log_debug(LD_REND, "Client %s authorized for service %s.",
  760. auth_client->client_name, service->service_id);
  761. return 1;
  762. }
  763. /** Remove elements from <b>service</b>'s replay cache that are old enough to
  764. * be noticed by timestamp checking. */
  765. static void
  766. clean_accepted_intros(rend_service_t *service, time_t now)
  767. {
  768. const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
  769. service->last_cleaned_accepted_intros = now;
  770. if (!service->accepted_intros)
  771. return;
  772. DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
  773. if (*t < cutoff) {
  774. tor_free(t);
  775. MAP_DEL_CURRENT(digest);
  776. }
  777. } DIGESTMAP_FOREACH_END;
  778. }
  779. /******
  780. * Handle cells
  781. ******/
  782. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  783. * rendezvous point.
  784. */
  785. int
  786. rend_service_introduce(origin_circuit_t *circuit, const char *request,
  787. size_t request_len)
  788. {
  789. char *ptr, *r_cookie;
  790. extend_info_t *extend_info = NULL;
  791. char buf[RELAY_PAYLOAD_SIZE];
  792. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  793. rend_service_t *service;
  794. int r, i, v3_shift = 0;
  795. size_t len, keylen;
  796. crypto_dh_env_t *dh = NULL;
  797. origin_circuit_t *launched = NULL;
  798. crypt_path_t *cpath = NULL;
  799. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  800. char hexcookie[9];
  801. int circ_needs_uptime;
  802. int reason = END_CIRC_REASON_TORPROTOCOL;
  803. crypto_pk_env_t *intro_key;
  804. char intro_key_digest[DIGEST_LEN];
  805. int auth_type;
  806. size_t auth_len = 0;
  807. char auth_data[REND_DESC_COOKIE_LEN];
  808. crypto_digest_env_t *digest = NULL;
  809. time_t now = time(NULL);
  810. char diffie_hellman_hash[DIGEST_LEN];
  811. time_t *access_time;
  812. tor_assert(circuit->rend_data);
  813. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  814. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  815. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  816. escaped(serviceid), circuit->_base.n_circ_id);
  817. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  818. log_warn(LD_PROTOCOL,
  819. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  820. circuit->_base.n_circ_id);
  821. return -1;
  822. }
  823. /* min key length plus digest length plus nickname length */
  824. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  825. DH_KEY_LEN+42) {
  826. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  827. circuit->_base.n_circ_id);
  828. return -1;
  829. }
  830. /* look up service depending on circuit. */
  831. service = rend_service_get_by_pk_digest_and_version(
  832. circuit->rend_data->rend_pk_digest,
  833. circuit->rend_data->rend_desc_version);
  834. if (!service) {
  835. log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
  836. escaped(serviceid));
  837. return -1;
  838. }
  839. /* use intro key instead of service key. */
  840. intro_key = circuit->intro_key;
  841. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  842. crypto_pk_get_digest(intro_key, intro_key_digest);
  843. if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
  844. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  845. request, REND_SERVICE_ID_LEN);
  846. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  847. escaped(serviceid));
  848. return -1;
  849. }
  850. keylen = crypto_pk_keysize(intro_key);
  851. if (request_len < keylen+DIGEST_LEN) {
  852. log_warn(LD_PROTOCOL,
  853. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  854. return -1;
  855. }
  856. /* Next N bytes is encrypted with service key */
  857. note_crypto_pk_op(REND_SERVER);
  858. r = crypto_pk_private_hybrid_decrypt(
  859. intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
  860. PK_PKCS1_OAEP_PADDING,1);
  861. if (r<0) {
  862. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  863. return -1;
  864. }
  865. len = r;
  866. if (*buf == 3) {
  867. /* Version 3 INTRODUCE2 cell. */
  868. time_t ts = 0, now = time(NULL);
  869. v3_shift = 1;
  870. auth_type = buf[1];
  871. switch (auth_type) {
  872. case REND_BASIC_AUTH:
  873. /* fall through */
  874. case REND_STEALTH_AUTH:
  875. auth_len = ntohs(get_uint16(buf+2));
  876. if (auth_len != REND_DESC_COOKIE_LEN) {
  877. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  878. (int)auth_len, REND_DESC_COOKIE_LEN);
  879. return -1;
  880. }
  881. memcpy(auth_data, buf+4, sizeof(auth_data));
  882. v3_shift += 2+REND_DESC_COOKIE_LEN;
  883. break;
  884. case REND_NO_AUTH:
  885. break;
  886. default:
  887. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  888. }
  889. /* Check timestamp. */
  890. memcpy((char*)&ts, buf+1+v3_shift, sizeof(uint32_t));
  891. v3_shift += 4;
  892. ts = ntohl(ts);
  893. if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
  894. (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
  895. log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
  896. (now - ts) < 0 ? "old" : "new");
  897. return -1;
  898. }
  899. }
  900. if (*buf == 2 || *buf == 3) {
  901. /* Version 2 INTRODUCE2 cell. */
  902. int klen;
  903. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  904. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  905. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  906. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  907. DIGEST_LEN);
  908. extend_info->nickname[0] = '$';
  909. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  910. extend_info->identity_digest, DIGEST_LEN);
  911. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  912. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  913. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  914. (int)len, *buf);
  915. reason = END_CIRC_REASON_TORPROTOCOL;
  916. goto err;
  917. }
  918. extend_info->onion_key =
  919. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  920. if (!extend_info->onion_key) {
  921. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  922. "INTRODUCE2 cell.", *buf);
  923. reason = END_CIRC_REASON_TORPROTOCOL;
  924. goto err;
  925. }
  926. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  927. len -= v3_shift+7+DIGEST_LEN+2+klen;
  928. } else {
  929. char *rp_nickname;
  930. size_t nickname_field_len;
  931. routerinfo_t *router;
  932. int version;
  933. if (*buf == 1) {
  934. rp_nickname = buf+1;
  935. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  936. version = 1;
  937. } else {
  938. nickname_field_len = MAX_NICKNAME_LEN+1;
  939. rp_nickname = buf;
  940. version = 0;
  941. }
  942. ptr=memchr(rp_nickname,0,nickname_field_len);
  943. if (!ptr || ptr == rp_nickname) {
  944. log_warn(LD_PROTOCOL,
  945. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  946. return -1;
  947. }
  948. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  949. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  950. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  951. return -1;
  952. }
  953. /* Okay, now we know that a nickname is at the start of the buffer. */
  954. ptr = rp_nickname+nickname_field_len;
  955. len -= nickname_field_len;
  956. len -= rp_nickname - buf; /* also remove header space used by version, if
  957. * any */
  958. router = router_get_by_nickname(rp_nickname, 0);
  959. if (!router) {
  960. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  961. escaped_safe_str(rp_nickname));
  962. /* XXXX Add a no-such-router reason? */
  963. reason = END_CIRC_REASON_TORPROTOCOL;
  964. goto err;
  965. }
  966. extend_info = extend_info_from_router(router);
  967. }
  968. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  969. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  970. reason = END_CIRC_REASON_TORPROTOCOL;
  971. goto err;
  972. }
  973. r_cookie = ptr;
  974. base16_encode(hexcookie,9,r_cookie,4);
  975. /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
  976. digest = crypto_new_digest_env();
  977. crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
  978. crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
  979. crypto_free_digest_env(digest);
  980. /* Check whether there is a past request with the same Diffie-Hellman,
  981. * part 1. */
  982. if (!service->accepted_intros)
  983. service->accepted_intros = digestmap_new();
  984. access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
  985. if (access_time != NULL) {
  986. log_warn(LD_REND, "Possible replay detected! We received an "
  987. "INTRODUCE2 cell with same first part of "
  988. "Diffie-Hellman handshake %d seconds ago. Dropping "
  989. "cell.",
  990. (int) (now - *access_time));
  991. goto err;
  992. }
  993. /* Add request to access history, including time and hash of Diffie-Hellman,
  994. * part 1, and possibly remove requests from the history that are older than
  995. * one hour. */
  996. access_time = tor_malloc(sizeof(time_t));
  997. *access_time = now;
  998. digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
  999. if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
  1000. clean_accepted_intros(service, now);
  1001. /* If the service performs client authorization, check included auth data. */
  1002. if (service->clients) {
  1003. if (auth_len > 0) {
  1004. if (rend_check_authorization(service, auth_data)) {
  1005. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1006. } else {
  1007. log_info(LD_REND, "The authorization data that are contained in "
  1008. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1009. reason = END_CIRC_REASON_CONNECTFAILED;
  1010. goto err;
  1011. }
  1012. } else {
  1013. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1014. "data, but we require client authorization. Dropping cell.");
  1015. reason = END_CIRC_REASON_CONNECTFAILED;
  1016. goto err;
  1017. }
  1018. }
  1019. /* Try DH handshake... */
  1020. dh = crypto_dh_new();
  1021. if (!dh || crypto_dh_generate_public(dh)<0) {
  1022. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1023. "or generate public key.");
  1024. reason = END_CIRC_REASON_INTERNAL;
  1025. goto err;
  1026. }
  1027. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  1028. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1029. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1030. reason = END_CIRC_REASON_INTERNAL;
  1031. goto err;
  1032. }
  1033. circ_needs_uptime = rend_service_requires_uptime(service);
  1034. /* help predict this next time */
  1035. rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
  1036. /* Launch a circuit to alice's chosen rendezvous point.
  1037. */
  1038. for (i=0;i<MAX_REND_FAILURES;i++) {
  1039. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1040. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1041. launched = circuit_launch_by_extend_info(
  1042. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1043. if (launched)
  1044. break;
  1045. }
  1046. if (!launched) { /* give up */
  1047. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1048. "point %s for service %s.",
  1049. escaped_safe_str(extend_info->nickname), serviceid);
  1050. reason = END_CIRC_REASON_CONNECTFAILED;
  1051. goto err;
  1052. }
  1053. log_info(LD_REND,
  1054. "Accepted intro; launching circuit to %s "
  1055. "(cookie %s) for service %s.",
  1056. escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
  1057. tor_assert(launched->build_state);
  1058. /* Fill in the circuit's state. */
  1059. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1060. memcpy(launched->rend_data->rend_pk_digest,
  1061. circuit->rend_data->rend_pk_digest,
  1062. DIGEST_LEN);
  1063. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1064. strlcpy(launched->rend_data->onion_address, service->service_id,
  1065. sizeof(launched->rend_data->onion_address));
  1066. launched->build_state->pending_final_cpath = cpath =
  1067. tor_malloc_zero(sizeof(crypt_path_t));
  1068. cpath->magic = CRYPT_PATH_MAGIC;
  1069. launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
  1070. cpath->dh_handshake_state = dh;
  1071. dh = NULL;
  1072. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1073. goto err;
  1074. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1075. if (extend_info) extend_info_free(extend_info);
  1076. return 0;
  1077. err:
  1078. if (dh) crypto_dh_free(dh);
  1079. if (launched)
  1080. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1081. if (extend_info) extend_info_free(extend_info);
  1082. return -1;
  1083. }
  1084. /** Called when we fail building a rendezvous circuit at some point other
  1085. * than the last hop: launches a new circuit to the same rendezvous point.
  1086. */
  1087. void
  1088. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1089. {
  1090. origin_circuit_t *newcirc;
  1091. cpath_build_state_t *newstate, *oldstate;
  1092. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1093. if (!oldcirc->build_state ||
  1094. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1095. oldcirc->build_state->expiry_time < time(NULL)) {
  1096. log_info(LD_REND,
  1097. "Attempt to build circuit to %s for rendezvous has failed "
  1098. "too many times or expired; giving up.",
  1099. oldcirc->build_state ?
  1100. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  1101. return;
  1102. }
  1103. oldstate = oldcirc->build_state;
  1104. tor_assert(oldstate);
  1105. if (oldstate->pending_final_cpath == NULL) {
  1106. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1107. "Initiator will retry.");
  1108. return;
  1109. }
  1110. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1111. oldstate->chosen_exit->nickname);
  1112. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1113. oldstate->chosen_exit,
  1114. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1115. if (!newcirc) {
  1116. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1117. oldstate->chosen_exit->nickname);
  1118. return;
  1119. }
  1120. newstate = newcirc->build_state;
  1121. tor_assert(newstate);
  1122. newstate->failure_count = oldstate->failure_count+1;
  1123. newstate->expiry_time = oldstate->expiry_time;
  1124. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  1125. oldstate->pending_final_cpath = NULL;
  1126. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1127. }
  1128. /** Launch a circuit to serve as an introduction point for the service
  1129. * <b>service</b> at the introduction point <b>nickname</b>
  1130. */
  1131. static int
  1132. rend_service_launch_establish_intro(rend_service_t *service,
  1133. rend_intro_point_t *intro)
  1134. {
  1135. origin_circuit_t *launched;
  1136. log_info(LD_REND,
  1137. "Launching circuit to introduction point %s for service %s",
  1138. escaped_safe_str(intro->extend_info->nickname),
  1139. service->service_id);
  1140. rep_hist_note_used_internal(time(NULL), 1, 0);
  1141. ++service->n_intro_circuits_launched;
  1142. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1143. intro->extend_info,
  1144. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1145. if (!launched) {
  1146. log_info(LD_REND,
  1147. "Can't launch circuit to establish introduction at %s.",
  1148. escaped_safe_str(intro->extend_info->nickname));
  1149. return -1;
  1150. }
  1151. if (memcmp(intro->extend_info->identity_digest,
  1152. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1153. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1154. base16_encode(cann, sizeof(cann),
  1155. launched->build_state->chosen_exit->identity_digest,
  1156. DIGEST_LEN);
  1157. base16_encode(orig, sizeof(orig),
  1158. intro->extend_info->identity_digest, DIGEST_LEN);
  1159. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1160. "but we requested an intro circuit to $%s. Updating "
  1161. "our service.", cann, orig);
  1162. extend_info_free(intro->extend_info);
  1163. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1164. }
  1165. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1166. strlcpy(launched->rend_data->onion_address, service->service_id,
  1167. sizeof(launched->rend_data->onion_address));
  1168. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1169. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1170. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1171. rend_service_intro_has_opened(launched);
  1172. return 0;
  1173. }
  1174. /** Return the number of introduction points that are or have been
  1175. * established for the given service address and rendezvous version. */
  1176. static int
  1177. count_established_intro_points(const char *query, int rend_version)
  1178. {
  1179. int num_ipos = 0;
  1180. circuit_t *circ;
  1181. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1182. if (!circ->marked_for_close &&
  1183. circ->state == CIRCUIT_STATE_OPEN &&
  1184. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1185. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1186. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1187. if (oc->rend_data &&
  1188. oc->rend_data->rend_desc_version == rend_version &&
  1189. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1190. num_ipos++;
  1191. }
  1192. }
  1193. return num_ipos;
  1194. }
  1195. /** Called when we're done building a circuit to an introduction point:
  1196. * sends a RELAY_ESTABLISH_INTRO cell.
  1197. */
  1198. void
  1199. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1200. {
  1201. rend_service_t *service;
  1202. size_t len;
  1203. int r;
  1204. char buf[RELAY_PAYLOAD_SIZE];
  1205. char auth[DIGEST_LEN + 9];
  1206. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1207. int reason = END_CIRC_REASON_TORPROTOCOL;
  1208. crypto_pk_env_t *intro_key;
  1209. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1210. tor_assert(circuit->cpath);
  1211. tor_assert(circuit->rend_data);
  1212. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1213. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1214. service = rend_service_get_by_pk_digest_and_version(
  1215. circuit->rend_data->rend_pk_digest,
  1216. circuit->rend_data->rend_desc_version);
  1217. if (!service) {
  1218. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1219. serviceid, circuit->_base.n_circ_id);
  1220. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1221. goto err;
  1222. }
  1223. /* If we already have enough introduction circuits for this service,
  1224. * redefine this one as a general circuit. */
  1225. if (count_established_intro_points(serviceid,
  1226. circuit->rend_data->rend_desc_version) > NUM_INTRO_POINTS) {
  1227. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1228. "circuit, but we already have enough. Redefining purpose to "
  1229. "general.");
  1230. TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1231. circuit_has_opened(circuit);
  1232. return;
  1233. }
  1234. log_info(LD_REND,
  1235. "Established circuit %d as introduction point for service %s",
  1236. circuit->_base.n_circ_id, serviceid);
  1237. /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
  1238. intro_key = circuit->intro_key;
  1239. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1240. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1241. RELAY_PAYLOAD_SIZE-2);
  1242. if (r < 0) {
  1243. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1244. reason = END_CIRC_REASON_INTERNAL;
  1245. goto err;
  1246. }
  1247. len = r;
  1248. set_uint16(buf, htons((uint16_t)len));
  1249. len += 2;
  1250. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1251. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1252. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1253. goto err;
  1254. len += 20;
  1255. note_crypto_pk_op(REND_SERVER);
  1256. r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
  1257. if (r<0) {
  1258. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1259. reason = END_CIRC_REASON_INTERNAL;
  1260. goto err;
  1261. }
  1262. len += r;
  1263. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1264. RELAY_COMMAND_ESTABLISH_INTRO,
  1265. buf, len, circuit->cpath->prev)<0) {
  1266. log_info(LD_GENERAL,
  1267. "Couldn't send introduction request for service %s on circuit %d",
  1268. serviceid, circuit->_base.n_circ_id);
  1269. reason = END_CIRC_REASON_INTERNAL;
  1270. goto err;
  1271. }
  1272. return;
  1273. err:
  1274. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1275. }
  1276. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1277. * live introduction point, and note that the service descriptor is
  1278. * now out-of-date.*/
  1279. int
  1280. rend_service_intro_established(origin_circuit_t *circuit, const char *request,
  1281. size_t request_len)
  1282. {
  1283. rend_service_t *service;
  1284. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1285. (void) request;
  1286. (void) request_len;
  1287. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1288. log_warn(LD_PROTOCOL,
  1289. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1290. goto err;
  1291. }
  1292. tor_assert(circuit->rend_data);
  1293. service = rend_service_get_by_pk_digest_and_version(
  1294. circuit->rend_data->rend_pk_digest,
  1295. circuit->rend_data->rend_desc_version);
  1296. if (!service) {
  1297. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1298. circuit->_base.n_circ_id);
  1299. goto err;
  1300. }
  1301. service->desc_is_dirty = time(NULL);
  1302. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1303. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1304. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1305. log_info(LD_REND,
  1306. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1307. circuit->_base.n_circ_id, serviceid);
  1308. return 0;
  1309. err:
  1310. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1311. return -1;
  1312. }
  1313. /** Called once a circuit to a rendezvous point is established: sends a
  1314. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1315. */
  1316. void
  1317. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1318. {
  1319. rend_service_t *service;
  1320. char buf[RELAY_PAYLOAD_SIZE];
  1321. crypt_path_t *hop;
  1322. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1323. char hexcookie[9];
  1324. int reason;
  1325. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1326. tor_assert(circuit->cpath);
  1327. tor_assert(circuit->build_state);
  1328. tor_assert(circuit->rend_data);
  1329. hop = circuit->build_state->pending_final_cpath;
  1330. tor_assert(hop);
  1331. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1332. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1333. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1334. log_info(LD_REND,
  1335. "Done building circuit %d to rendezvous with "
  1336. "cookie %s for service %s",
  1337. circuit->_base.n_circ_id, hexcookie, serviceid);
  1338. service = rend_service_get_by_pk_digest_and_version(
  1339. circuit->rend_data->rend_pk_digest,
  1340. circuit->rend_data->rend_desc_version);
  1341. if (!service) {
  1342. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1343. "introduction circuit.");
  1344. reason = END_CIRC_REASON_INTERNAL;
  1345. goto err;
  1346. }
  1347. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1348. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1349. if (crypto_dh_get_public(hop->dh_handshake_state,
  1350. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1351. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1352. reason = END_CIRC_REASON_INTERNAL;
  1353. goto err;
  1354. }
  1355. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1356. DIGEST_LEN);
  1357. /* Send the cell */
  1358. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1359. RELAY_COMMAND_RENDEZVOUS1,
  1360. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1361. circuit->cpath->prev)<0) {
  1362. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1363. reason = END_CIRC_REASON_INTERNAL;
  1364. goto err;
  1365. }
  1366. crypto_dh_free(hop->dh_handshake_state);
  1367. hop->dh_handshake_state = NULL;
  1368. /* Append the cpath entry. */
  1369. hop->state = CPATH_STATE_OPEN;
  1370. /* set the windows to default. these are the windows
  1371. * that bob thinks alice has.
  1372. */
  1373. hop->package_window = CIRCWINDOW_START;
  1374. hop->deliver_window = CIRCWINDOW_START;
  1375. onion_append_to_cpath(&circuit->cpath, hop);
  1376. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1377. /* Change the circuit purpose. */
  1378. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1379. return;
  1380. err:
  1381. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1382. }
  1383. /*
  1384. * Manage introduction points
  1385. */
  1386. /** Return the (possibly non-open) introduction circuit ending at
  1387. * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
  1388. * which publishes descriptor of version <b>desc_version</b>. Return
  1389. * NULL if no such service is found.
  1390. */
  1391. static origin_circuit_t *
  1392. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
  1393. int desc_version)
  1394. {
  1395. origin_circuit_t *circ = NULL;
  1396. tor_assert(intro);
  1397. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1398. CIRCUIT_PURPOSE_S_INTRO))) {
  1399. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1400. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1401. circ->rend_data &&
  1402. circ->rend_data->rend_desc_version == desc_version) {
  1403. return circ;
  1404. }
  1405. }
  1406. circ = NULL;
  1407. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1408. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1409. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1410. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1411. circ->rend_data &&
  1412. circ->rend_data->rend_desc_version == desc_version) {
  1413. return circ;
  1414. }
  1415. }
  1416. return NULL;
  1417. }
  1418. /** Determine the responsible hidden service directories for the
  1419. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1420. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1421. * purposes. */
  1422. static void
  1423. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1424. smartlist_t *descs, const char *service_id,
  1425. int seconds_valid)
  1426. {
  1427. int i, j, failed_upload = 0;
  1428. smartlist_t *responsible_dirs = smartlist_create();
  1429. smartlist_t *successful_uploads = smartlist_create();
  1430. routerstatus_t *hs_dir;
  1431. for (i = 0; i < smartlist_len(descs); i++) {
  1432. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1433. /* Determine responsible dirs. */
  1434. if (hid_serv_get_responsible_directories(responsible_dirs,
  1435. desc->desc_id) < 0) {
  1436. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1437. "directories to post descriptors to.");
  1438. smartlist_free(responsible_dirs);
  1439. smartlist_free(successful_uploads);
  1440. return;
  1441. }
  1442. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1443. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1444. hs_dir = smartlist_get(responsible_dirs, j);
  1445. if (smartlist_digest_isin(renddesc->successful_uploads,
  1446. hs_dir->identity_digest))
  1447. /* Don't upload descriptor if we succeeded in doing so last time. */
  1448. continue;
  1449. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1450. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1451. "hidden service directory '%s'; we don't have its "
  1452. "router descriptor. Queueing for later upload.",
  1453. hs_dir->nickname);
  1454. failed_upload = -1;
  1455. continue;
  1456. }
  1457. /* Send publish request. */
  1458. directory_initiate_command_routerstatus(hs_dir,
  1459. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1460. ROUTER_PURPOSE_GENERAL,
  1461. 1, NULL, desc->desc_str,
  1462. strlen(desc->desc_str), 0);
  1463. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1464. desc->desc_id, DIGEST_LEN);
  1465. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1466. "service '%s' with descriptor ID '%s' with validity "
  1467. "of %d seconds to hidden service directory '%s' on "
  1468. "port %d.",
  1469. safe_str(service_id),
  1470. safe_str(desc_id_base32),
  1471. seconds_valid,
  1472. hs_dir->nickname,
  1473. hs_dir->dir_port);
  1474. /* Remember successful upload to this router for next time. */
  1475. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1476. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1477. }
  1478. smartlist_clear(responsible_dirs);
  1479. }
  1480. if (!failed_upload) {
  1481. if (renddesc->successful_uploads) {
  1482. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1483. smartlist_free(renddesc->successful_uploads);
  1484. renddesc->successful_uploads = NULL;
  1485. }
  1486. renddesc->all_uploads_performed = 1;
  1487. } else {
  1488. /* Remember which routers worked this time, so that we don't upload the
  1489. * descriptor to them again. */
  1490. if (!renddesc->successful_uploads)
  1491. renddesc->successful_uploads = smartlist_create();
  1492. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1493. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1494. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1495. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1496. }
  1497. });
  1498. }
  1499. smartlist_free(responsible_dirs);
  1500. smartlist_free(successful_uploads);
  1501. }
  1502. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  1503. * and upload it/them to the responsible hidden service directories.
  1504. */
  1505. static void
  1506. upload_service_descriptor(rend_service_t *service)
  1507. {
  1508. time_t now = time(NULL);
  1509. int rendpostperiod;
  1510. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1511. int uploaded = 0;
  1512. rendpostperiod = get_options()->RendPostPeriod;
  1513. /* Upload descriptor? */
  1514. if (get_options()->PublishHidServDescriptors) {
  1515. networkstatus_t *c = networkstatus_get_latest_consensus();
  1516. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1517. int seconds_valid, i, j, num_descs;
  1518. smartlist_t *descs = smartlist_create();
  1519. smartlist_t *client_cookies = smartlist_create();
  1520. /* Either upload a single descriptor (including replicas) or one
  1521. * descriptor for each authorized client in case of authorization
  1522. * type 'stealth'. */
  1523. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1524. smartlist_len(service->clients) : 1;
  1525. for (j = 0; j < num_descs; j++) {
  1526. crypto_pk_env_t *client_key = NULL;
  1527. rend_authorized_client_t *client = NULL;
  1528. smartlist_clear(client_cookies);
  1529. switch (service->auth_type) {
  1530. case REND_NO_AUTH:
  1531. /* Do nothing here. */
  1532. break;
  1533. case REND_BASIC_AUTH:
  1534. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1535. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1536. break;
  1537. case REND_STEALTH_AUTH:
  1538. client = smartlist_get(service->clients, j);
  1539. client_key = client->client_key;
  1540. smartlist_add(client_cookies, client->descriptor_cookie);
  1541. break;
  1542. }
  1543. /* Encode the current descriptor. */
  1544. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1545. now, 0,
  1546. service->auth_type,
  1547. client_key,
  1548. client_cookies);
  1549. if (seconds_valid < 0) {
  1550. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1551. "descriptor; not uploading.");
  1552. smartlist_free(descs);
  1553. smartlist_free(client_cookies);
  1554. return;
  1555. }
  1556. /* Post the current descriptors to the hidden service directories. */
  1557. rend_get_service_id(service->desc->pk, serviceid);
  1558. log_info(LD_REND, "Sending publish request for hidden service %s",
  1559. serviceid);
  1560. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1561. seconds_valid);
  1562. /* Free memory for descriptors. */
  1563. for (i = 0; i < smartlist_len(descs); i++)
  1564. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1565. smartlist_clear(descs);
  1566. /* Update next upload time. */
  1567. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1568. > rendpostperiod)
  1569. service->next_upload_time = now + rendpostperiod;
  1570. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1571. service->next_upload_time = now + seconds_valid + 1;
  1572. else
  1573. service->next_upload_time = now + seconds_valid -
  1574. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1575. /* Post also the next descriptors, if necessary. */
  1576. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1577. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1578. now, 1,
  1579. service->auth_type,
  1580. client_key,
  1581. client_cookies);
  1582. if (seconds_valid < 0) {
  1583. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1584. "descriptor; not uploading.");
  1585. smartlist_free(descs);
  1586. smartlist_free(client_cookies);
  1587. return;
  1588. }
  1589. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1590. seconds_valid);
  1591. /* Free memory for descriptors. */
  1592. for (i = 0; i < smartlist_len(descs); i++)
  1593. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1594. smartlist_clear(descs);
  1595. }
  1596. }
  1597. smartlist_free(descs);
  1598. smartlist_free(client_cookies);
  1599. uploaded = 1;
  1600. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1601. }
  1602. }
  1603. /* If not uploaded, try again in one minute. */
  1604. if (!uploaded)
  1605. service->next_upload_time = now + 60;
  1606. /* Unmark dirty flag of this service. */
  1607. service->desc_is_dirty = 0;
  1608. }
  1609. /** For every service, check how many intro points it currently has, and:
  1610. * - Pick new intro points as necessary.
  1611. * - Launch circuits to any new intro points.
  1612. */
  1613. void
  1614. rend_services_introduce(void)
  1615. {
  1616. int i,j,r;
  1617. routerinfo_t *router;
  1618. rend_service_t *service;
  1619. rend_intro_point_t *intro;
  1620. int changed, prev_intro_nodes;
  1621. smartlist_t *intro_routers;
  1622. time_t now;
  1623. or_options_t *options = get_options();
  1624. intro_routers = smartlist_create();
  1625. now = time(NULL);
  1626. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1627. smartlist_clear(intro_routers);
  1628. service = smartlist_get(rend_service_list, i);
  1629. tor_assert(service);
  1630. changed = 0;
  1631. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1632. /* One period has elapsed; we can try building circuits again. */
  1633. service->intro_period_started = now;
  1634. service->n_intro_circuits_launched = 0;
  1635. } else if (service->n_intro_circuits_launched >=
  1636. MAX_INTRO_CIRCS_PER_PERIOD) {
  1637. /* We have failed too many times in this period; wait for the next
  1638. * one before we try again. */
  1639. continue;
  1640. }
  1641. /* Find out which introduction points we have in progress for this
  1642. service. */
  1643. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1644. intro = smartlist_get(service->intro_nodes, j);
  1645. router = router_get_by_digest(intro->extend_info->identity_digest);
  1646. if (!router || !find_intro_circuit(intro, service->pk_digest, -1)) {
  1647. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1648. intro->extend_info->nickname, service->service_id);
  1649. if (service->desc) {
  1650. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1651. dintro, {
  1652. if (!memcmp(dintro->extend_info->identity_digest,
  1653. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1654. log_info(LD_REND, "The intro point we are giving up on was "
  1655. "included in the last published descriptor. "
  1656. "Marking current descriptor as dirty.");
  1657. service->desc_is_dirty = now;
  1658. }
  1659. });
  1660. }
  1661. rend_intro_point_free(intro);
  1662. smartlist_del(service->intro_nodes,j--);
  1663. changed = 1;
  1664. }
  1665. if (router)
  1666. smartlist_add(intro_routers, router);
  1667. }
  1668. /* We have enough intro points, and the intro points we thought we had were
  1669. * all connected.
  1670. */
  1671. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1672. /* We have all our intro points! Start a fresh period and reset the
  1673. * circuit count. */
  1674. service->intro_period_started = now;
  1675. service->n_intro_circuits_launched = 0;
  1676. continue;
  1677. }
  1678. /* Remember how many introduction circuits we started with. */
  1679. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1680. /* We have enough directory information to start establishing our
  1681. * intro points. We want to end up with three intro points, but if
  1682. * we're just starting, we launch five and pick the first three that
  1683. * complete.
  1684. *
  1685. * The ones after the first three will be converted to 'general'
  1686. * internal circuits in rend_service_intro_has_opened(), and then
  1687. * we'll drop them from the list of intro points next time we
  1688. * go through the above "find out which introduction points we have
  1689. * in progress" loop. */
  1690. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1691. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1692. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1693. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1694. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1695. flags |= CRN_ALLOW_INVALID;
  1696. router = router_choose_random_node(NULL, intro_routers,
  1697. options->ExcludeNodes, flags);
  1698. if (!router) {
  1699. log_warn(LD_REND,
  1700. "Could only establish %d introduction points for %s.",
  1701. smartlist_len(service->intro_nodes), service->service_id);
  1702. break;
  1703. }
  1704. changed = 1;
  1705. smartlist_add(intro_routers, router);
  1706. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1707. intro->extend_info = extend_info_from_router(router);
  1708. intro->intro_key = crypto_new_pk_env();
  1709. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1710. smartlist_add(service->intro_nodes, intro);
  1711. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1712. router->nickname, service->service_id);
  1713. }
  1714. /* If there's no need to launch new circuits, stop here. */
  1715. if (!changed)
  1716. continue;
  1717. /* Establish new introduction points. */
  1718. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1719. intro = smartlist_get(service->intro_nodes, j);
  1720. r = rend_service_launch_establish_intro(service, intro);
  1721. if (r<0) {
  1722. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1723. intro->extend_info->nickname, service->service_id);
  1724. }
  1725. }
  1726. }
  1727. smartlist_free(intro_routers);
  1728. }
  1729. /** Regenerate and upload rendezvous service descriptors for all
  1730. * services, if necessary. If the descriptor has been dirty enough
  1731. * for long enough, definitely upload; else only upload when the
  1732. * periodic timeout has expired.
  1733. *
  1734. * For the first upload, pick a random time between now and two periods
  1735. * from now, and pick it independently for each service.
  1736. */
  1737. void
  1738. rend_consider_services_upload(time_t now)
  1739. {
  1740. int i;
  1741. rend_service_t *service;
  1742. int rendpostperiod = get_options()->RendPostPeriod;
  1743. if (!get_options()->PublishHidServDescriptors)
  1744. return;
  1745. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1746. service = smartlist_get(rend_service_list, i);
  1747. if (!service->next_upload_time) { /* never been uploaded yet */
  1748. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1749. * is stable before being published. See comment below. */
  1750. service->next_upload_time =
  1751. now + 30 + crypto_rand_int(2*rendpostperiod);
  1752. }
  1753. if (service->next_upload_time < now ||
  1754. (service->desc_is_dirty &&
  1755. service->desc_is_dirty < now-30)) {
  1756. /* if it's time, or if the directory servers have a wrong service
  1757. * descriptor and ours has been stable for 30 seconds, upload a
  1758. * new one of each format. */
  1759. rend_service_update_descriptor(service);
  1760. upload_service_descriptor(service);
  1761. }
  1762. }
  1763. }
  1764. /** True if the list of available router descriptors might have changed so
  1765. * that we should have a look whether we can republish previously failed
  1766. * rendezvous service descriptors. */
  1767. static int consider_republishing_rend_descriptors = 1;
  1768. /** Called when our internal view of the directory has changed, so that we
  1769. * might have router descriptors of hidden service directories available that
  1770. * we did not have before. */
  1771. void
  1772. rend_hsdir_routers_changed(void)
  1773. {
  1774. consider_republishing_rend_descriptors = 1;
  1775. }
  1776. /** Consider republication of v2 rendezvous service descriptors that failed
  1777. * previously, but without regenerating descriptor contents.
  1778. */
  1779. void
  1780. rend_consider_descriptor_republication(void)
  1781. {
  1782. int i;
  1783. rend_service_t *service;
  1784. if (!consider_republishing_rend_descriptors)
  1785. return;
  1786. consider_republishing_rend_descriptors = 0;
  1787. if (!get_options()->PublishHidServDescriptors)
  1788. return;
  1789. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1790. service = smartlist_get(rend_service_list, i);
  1791. if (service->desc && !service->desc->all_uploads_performed) {
  1792. /* If we failed in uploading a descriptor last time, try again *without*
  1793. * updating the descriptor's contents. */
  1794. upload_service_descriptor(service);
  1795. }
  1796. }
  1797. }
  1798. /** Log the status of introduction points for all rendezvous services
  1799. * at log severity <b>severity</b>.
  1800. */
  1801. void
  1802. rend_service_dump_stats(int severity)
  1803. {
  1804. int i,j;
  1805. rend_service_t *service;
  1806. rend_intro_point_t *intro;
  1807. const char *safe_name;
  1808. origin_circuit_t *circ;
  1809. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1810. service = smartlist_get(rend_service_list, i);
  1811. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1812. service->directory);
  1813. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1814. intro = smartlist_get(service->intro_nodes, j);
  1815. safe_name = safe_str(intro->extend_info->nickname);
  1816. circ = find_intro_circuit(intro, service->pk_digest, -1);
  1817. if (!circ) {
  1818. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1819. j, safe_name);
  1820. continue;
  1821. }
  1822. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1823. j, safe_name, circuit_state_to_string(circ->_base.state));
  1824. }
  1825. }
  1826. }
  1827. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1828. * 'circ', and look up the port and address based on conn-\>port.
  1829. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1830. * or 0 for success.
  1831. */
  1832. int
  1833. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1834. origin_circuit_t *circ)
  1835. {
  1836. rend_service_t *service;
  1837. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1838. smartlist_t *matching_ports;
  1839. rend_service_port_config_t *chosen_port;
  1840. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1841. tor_assert(circ->rend_data);
  1842. log_debug(LD_REND,"beginning to hunt for addr/port");
  1843. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1844. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1845. service = rend_service_get_by_pk_digest_and_version(
  1846. circ->rend_data->rend_pk_digest,
  1847. circ->rend_data->rend_desc_version);
  1848. if (!service) {
  1849. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1850. "rendezvous circuit %d; closing.",
  1851. serviceid, circ->_base.n_circ_id);
  1852. return -1;
  1853. }
  1854. matching_ports = smartlist_create();
  1855. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1856. {
  1857. if (conn->_base.port == p->virtual_port) {
  1858. smartlist_add(matching_ports, p);
  1859. }
  1860. });
  1861. chosen_port = smartlist_choose(matching_ports);
  1862. smartlist_free(matching_ports);
  1863. if (chosen_port) {
  1864. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1865. conn->_base.port = chosen_port->real_port;
  1866. return 0;
  1867. }
  1868. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1869. conn->_base.port,serviceid);
  1870. return -1;
  1871. }