rendservice.c 64 KB

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