rendservice.c 73 KB

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