rendservice.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char rendservice_c_id[] =
  5. "$Id$";
  6. /**
  7. * \file rendservice.c
  8. * \brief The hidden-service side of rendezvous functionality.
  9. **/
  10. #include "or.h"
  11. static origin_circuit_t *find_intro_circuit(routerinfo_t *router,
  12. const char *pk_digest);
  13. /** Represents the mapping from a virtual port of a rendezvous service to
  14. * a real port on some IP.
  15. */
  16. typedef struct rend_service_port_config_t {
  17. uint16_t virtual_port;
  18. uint16_t real_port;
  19. uint32_t real_addr;
  20. } rend_service_port_config_t;
  21. /** Try to maintain this many intro points per service if possible. */
  22. #define NUM_INTRO_POINTS 3
  23. /** If we can't build our intro circuits, don't retry for this long. */
  24. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  25. /** Don't try to build more than this many circuits before giving up
  26. * for a while.*/
  27. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  28. /** How many times will a hidden service operator attempt to connect to
  29. * a requested rendezvous point before giving up? */
  30. #define MAX_REND_FAILURES 30
  31. /** How many seconds should we spend trying to connect to a requested
  32. * rendezvous point before giving up? */
  33. #define MAX_REND_TIMEOUT 30
  34. /** Represents a single hidden service running at this OP. */
  35. typedef struct rend_service_t {
  36. /** Fields specified in config file */
  37. char *directory; /**< where in the filesystem it stores it */
  38. smartlist_t *ports; /**< List of rend_service_port_config_t */
  39. char *intro_prefer_nodes; /**< comma-separated list of nicknames */
  40. char *intro_exclude_nodes; /**< comma-separated list of nicknames */
  41. /* Other fields */
  42. crypto_pk_env_t *private_key;
  43. char service_id[REND_SERVICE_ID_LEN+1];
  44. char pk_digest[DIGEST_LEN];
  45. smartlist_t *intro_nodes; /**< list of hexdigests for intro points we have,
  46. * or are trying to establish. */
  47. strmap_t *intro_keys; /**< map from intro node hexdigest to key; only
  48. * used for versioned hidden service descriptors. */
  49. time_t intro_period_started;
  50. int n_intro_circuits_launched; /**< count of intro circuits we have
  51. * established in this period. */
  52. /* DOCDOC undocumented versions */
  53. rend_service_descriptor_t *desc;
  54. time_t desc_is_dirty;
  55. time_t next_upload_time;
  56. /* XXXX020 A service never actually has both descriptor versions; perhaps
  57. * this should be an int rather than in intmax. */
  58. /* A service can never publish v0 and v2 descriptors, but maybe it can
  59. * publish v2 and v3 descriptors in the future. As with origin_circuit_t:
  60. * Would it be clearer to switch to a single version number for now and
  61. * switch back to a bitmap, when the above becomes true? -KL */
  62. /* Yes. s/when/if/. "YAGNI" -NM. */
  63. int descriptor_versions; /**< bitmask of rendezvous descriptor versions
  64. * that will be published. "0" means "default." */
  65. } rend_service_t;
  66. /** A list of rend_service_t's for services run on this OP.
  67. */
  68. static smartlist_t *rend_service_list = NULL;
  69. /** Return the number of rendezvous services we have configured. */
  70. int
  71. num_rend_services(void)
  72. {
  73. if (!rend_service_list)
  74. return 0;
  75. return smartlist_len(rend_service_list);
  76. }
  77. /** Helper: Release the storage held by the intro key in <b>_ent</b>.
  78. */
  79. static void
  80. intro_key_free(void *_ent)
  81. {
  82. crypto_pk_env_t *ent = _ent;
  83. crypto_free_pk_env(ent);
  84. }
  85. /** Release the storage held by <b>service</b>.
  86. */
  87. static void
  88. rend_service_free(rend_service_t *service)
  89. {
  90. if (!service) return;
  91. tor_free(service->directory);
  92. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  93. smartlist_free(service->ports);
  94. if (service->private_key)
  95. crypto_free_pk_env(service->private_key);
  96. if (service->intro_keys)
  97. strmap_free(service->intro_keys, intro_key_free);
  98. tor_free(service->intro_prefer_nodes);
  99. tor_free(service->intro_exclude_nodes);
  100. SMARTLIST_FOREACH(service->intro_nodes, void*, p, tor_free(p));
  101. smartlist_free(service->intro_nodes);
  102. if (service->desc)
  103. rend_service_descriptor_free(service->desc);
  104. tor_free(service);
  105. }
  106. /** Release all the storage held in rend_service_list.
  107. */
  108. void
  109. rend_service_free_all(void)
  110. {
  111. if (!rend_service_list) {
  112. return;
  113. }
  114. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  115. rend_service_free(ptr));
  116. smartlist_free(rend_service_list);
  117. rend_service_list = NULL;
  118. }
  119. /** Validate <b>service</b> and add it to rend_service_list if possible.
  120. */
  121. static void
  122. add_service(rend_service_t *service)
  123. {
  124. int i;
  125. rend_service_port_config_t *p;
  126. struct in_addr addr;
  127. if (!service->intro_prefer_nodes)
  128. service->intro_prefer_nodes = tor_strdup("");
  129. if (!service->intro_exclude_nodes)
  130. service->intro_exclude_nodes = tor_strdup("");
  131. if (service->descriptor_versions == 0)
  132. service->descriptor_versions = 1 + (1<<2); /**< Default is v0 and v2 in
  133. * parallel. */
  134. service->intro_keys = strmap_new();
  135. /* If the service is configured to publish unversioned (v0) and versioned
  136. * descriptors (v2 or higher), split it up into two separate services. */
  137. if (service->descriptor_versions > 1 && service->descriptor_versions & 1) {
  138. rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
  139. v0_service->directory = tor_strdup(service->directory);
  140. v0_service->ports = smartlist_create();
  141. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
  142. rend_service_port_config_t *copy =
  143. tor_malloc_zero(sizeof(rend_service_port_config_t));
  144. memcpy(copy, p, sizeof(rend_service_port_config_t));
  145. smartlist_add(v0_service->ports, copy);
  146. });
  147. v0_service->intro_nodes = smartlist_create();
  148. v0_service->intro_prefer_nodes = tor_strdup(service->intro_prefer_nodes);
  149. v0_service->intro_exclude_nodes = tor_strdup(service->intro_exclude_nodes);
  150. v0_service->intro_period_started = service->intro_period_started;
  151. v0_service->descriptor_versions = 1; /* Unversioned descriptor. */
  152. add_service(v0_service);
  153. service->descriptor_versions -= 1; /* Versioned descriptor. */
  154. }
  155. if (!smartlist_len(service->ports)) {
  156. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  157. rend_service_free(service);
  158. } else {
  159. smartlist_set_capacity(service->ports, -1);
  160. smartlist_add(rend_service_list, service);
  161. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  162. service->directory);
  163. for (i = 0; i < smartlist_len(service->ports); ++i) {
  164. char addrbuf[INET_NTOA_BUF_LEN];
  165. p = smartlist_get(service->ports, i);
  166. addr.s_addr = htonl(p->real_addr);
  167. tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
  168. log_debug(LD_REND,"Service maps port %d to %s:%d",
  169. p->virtual_port, addrbuf, p->real_port);
  170. }
  171. }
  172. }
  173. /** Parses a real-port to virtual-port mapping and returns a new
  174. * rend_service_port_config_t.
  175. *
  176. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  177. *
  178. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  179. */
  180. static rend_service_port_config_t *
  181. parse_port_config(const char *string)
  182. {
  183. smartlist_t *sl;
  184. int virtport;
  185. int realport;
  186. uint16_t p;
  187. uint32_t addr;
  188. const char *addrport;
  189. rend_service_port_config_t *result = NULL;
  190. sl = smartlist_create();
  191. smartlist_split_string(sl, string, " ",
  192. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  193. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  194. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  195. goto err;
  196. }
  197. virtport = atoi(smartlist_get(sl,0));
  198. if (virtport < 1 || virtport > 65535) {
  199. log_warn(LD_CONFIG, "Missing or invalid port in hidden service port "
  200. "configuration.");
  201. goto err;
  202. }
  203. if (smartlist_len(sl) == 1) {
  204. /* No addr:port part; use default. */
  205. realport = virtport;
  206. addr = 0x7F000001u; /* 127.0.0.1 */
  207. } else {
  208. addrport = smartlist_get(sl,1);
  209. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  210. if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
  211. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  212. "configuration.");
  213. goto err;
  214. }
  215. realport = p?p:virtport;
  216. } else {
  217. /* No addr:port, no addr -- must be port. */
  218. realport = atoi(addrport);
  219. if (realport < 1 || realport > 65535)
  220. goto err;
  221. addr = 0x7F000001u; /* Default to 127.0.0.1 */
  222. }
  223. }
  224. result = tor_malloc(sizeof(rend_service_port_config_t));
  225. result->virtual_port = virtport;
  226. result->real_port = realport;
  227. result->real_addr = addr;
  228. err:
  229. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  230. smartlist_free(sl);
  231. return result;
  232. }
  233. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  234. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  235. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  236. * normal, but don't actually change the configured services.)
  237. */
  238. int
  239. rend_config_services(or_options_t *options, int validate_only)
  240. {
  241. config_line_t *line;
  242. rend_service_t *service = NULL;
  243. rend_service_port_config_t *portcfg;
  244. if (!validate_only) {
  245. rend_service_free_all();
  246. rend_service_list = smartlist_create();
  247. }
  248. for (line = options->RendConfigLines; line; line = line->next) {
  249. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  250. if (service) {
  251. if (validate_only)
  252. rend_service_free(service);
  253. else
  254. add_service(service);
  255. }
  256. service = tor_malloc_zero(sizeof(rend_service_t));
  257. service->directory = tor_strdup(line->value);
  258. service->ports = smartlist_create();
  259. service->intro_nodes = smartlist_create();
  260. service->intro_period_started = time(NULL);
  261. service->descriptor_versions = 0;
  262. continue;
  263. }
  264. if (!service) {
  265. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  266. line->key);
  267. rend_service_free(service);
  268. return -1;
  269. }
  270. if (!strcasecmp(line->key, "HiddenServicePort")) {
  271. portcfg = parse_port_config(line->value);
  272. if (!portcfg) {
  273. rend_service_free(service);
  274. return -1;
  275. }
  276. smartlist_add(service->ports, portcfg);
  277. } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
  278. if (service->intro_prefer_nodes) {
  279. log_warn(LD_CONFIG,
  280. "Got multiple HiddenServiceNodes lines for a single "
  281. "service.");
  282. return -1;
  283. }
  284. service->intro_prefer_nodes = tor_strdup(line->value);
  285. } else if (!strcasecmp(line->key, "HiddenServiceExcludeNodes")) {
  286. if (service->intro_exclude_nodes) {
  287. log_warn(LD_CONFIG,
  288. "Got multiple HiddenServiceExcludedNodes lines for "
  289. "a single service.");
  290. return -1;
  291. }
  292. service->intro_exclude_nodes = tor_strdup(line->value);
  293. } else {
  294. smartlist_t *versions;
  295. char *version_str;
  296. int i, version;
  297. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  298. versions = smartlist_create();
  299. smartlist_split_string(versions, line->value, ",",
  300. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  301. for (i = 0; i < smartlist_len(versions); i++) {
  302. version_str = smartlist_get(versions, i);
  303. if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
  304. log_warn(LD_CONFIG,
  305. "HiddenServiceVersion can only be 0 and/or 2.");
  306. return -1;
  307. }
  308. version = atoi(version_str);
  309. service->descriptor_versions |= 1 << version;
  310. }
  311. }
  312. }
  313. if (service) {
  314. if (validate_only)
  315. rend_service_free(service);
  316. else
  317. add_service(service);
  318. }
  319. return 0;
  320. }
  321. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  322. * the other fields in service.
  323. */
  324. static void
  325. rend_service_update_descriptor(rend_service_t *service)
  326. {
  327. rend_service_descriptor_t *d;
  328. origin_circuit_t *circ;
  329. int i,n;
  330. routerinfo_t *router;
  331. if (service->desc) {
  332. rend_service_descriptor_free(service->desc);
  333. service->desc = NULL;
  334. }
  335. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  336. d->pk = crypto_pk_dup_key(service->private_key);
  337. d->timestamp = time(NULL);
  338. d->version = 1; /*< XXXX020 this value is ignored by the
  339. * encode functions; do we need to set it at all? */
  340. n = smartlist_len(service->intro_nodes);
  341. d->n_intro_points = 0;
  342. d->intro_points = tor_malloc_zero(sizeof(char*)*n);
  343. d->intro_point_extend_info = tor_malloc_zero(sizeof(extend_info_t*)*n);
  344. /* We support intro protocol 2 and protocol 0. */
  345. d->protocols = (1<<2) | (1<<0);
  346. if (service->intro_keys) {
  347. /* We need to copy keys so that they're not deleted when we free the
  348. * descriptor. */
  349. strmap_iter_t *iter;
  350. d->intro_keys = strmap_new();
  351. for (iter = strmap_iter_init(service->intro_keys); !strmap_iter_done(iter);
  352. iter = strmap_iter_next(service->intro_keys, iter)) {
  353. const char *key;
  354. void *val;
  355. crypto_pk_env_t *k;
  356. strmap_iter_get(iter, &key, &val);
  357. k = val;
  358. strmap_set(d->intro_keys, key, crypto_pk_dup_key(k));
  359. }
  360. }
  361. for (i=0; i < n; ++i) {
  362. const char *name = smartlist_get(service->intro_nodes, i);
  363. router = router_get_by_nickname(name, 1);
  364. if (!router) {
  365. log_info(LD_REND,"Router '%s' not found for intro point %d. Skipping.",
  366. safe_str(name), i);
  367. continue;
  368. }
  369. circ = find_intro_circuit(router, service->pk_digest);
  370. if (circ && circ->_base.purpose == CIRCUIT_PURPOSE_S_INTRO) {
  371. /* We have an entirely established intro circuit. */
  372. d->intro_points[d->n_intro_points] = tor_strdup(name);
  373. d->intro_point_extend_info[d->n_intro_points] =
  374. extend_info_from_router(router);
  375. d->n_intro_points++;
  376. }
  377. }
  378. }
  379. /** Load and/or generate private keys for all hidden services. Return 0 on
  380. * success, -1 on failure.
  381. */
  382. int
  383. rend_service_load_keys(void)
  384. {
  385. int i;
  386. rend_service_t *s;
  387. char fname[512];
  388. char buf[128];
  389. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  390. s = smartlist_get(rend_service_list,i);
  391. if (s->private_key)
  392. continue;
  393. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  394. s->directory);
  395. /* Check/create directory */
  396. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  397. return -1;
  398. /* Load key */
  399. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  400. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  401. >= sizeof(fname)) {
  402. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  403. s->directory);
  404. return -1;
  405. }
  406. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  407. if (!s->private_key)
  408. return -1;
  409. /* Create service file */
  410. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  411. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  412. return -1;
  413. }
  414. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  415. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  416. return -1;
  417. }
  418. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  419. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  420. >= sizeof(fname)) {
  421. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  422. " \"%s\".", s->directory);
  423. return -1;
  424. }
  425. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  426. if (write_str_to_file(fname,buf,0)<0)
  427. return -1;
  428. }
  429. return 0;
  430. }
  431. /** Return the service whose public key has a digest of <b>digest</b> and
  432. * which publishes exactly the descriptor of the given <b>versions</b>
  433. * bitmask. Return NULL if no such service exists.
  434. */
  435. static rend_service_t *
  436. rend_service_get_by_pk_digest_and_version(const char* digest,
  437. uint8_t versions)
  438. {
  439. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  440. if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
  441. s->descriptor_versions == versions) return s);
  442. return NULL;
  443. }
  444. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  445. * to have good uptime. Else return 0.
  446. */
  447. static int
  448. rend_service_requires_uptime(rend_service_t *service)
  449. {
  450. int i;
  451. rend_service_port_config_t *p;
  452. for (i=0; i < smartlist_len(service->ports); ++i) {
  453. p = smartlist_get(service->ports, i);
  454. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  455. p->virtual_port))
  456. return 1;
  457. }
  458. return 0;
  459. }
  460. /******
  461. * Handle cells
  462. ******/
  463. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  464. * rendezvous point.
  465. */
  466. int
  467. rend_service_introduce(origin_circuit_t *circuit, const char *request,
  468. size_t request_len)
  469. {
  470. char *ptr, *r_cookie;
  471. extend_info_t *extend_info = NULL;
  472. char buf[RELAY_PAYLOAD_SIZE];
  473. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  474. rend_service_t *service;
  475. int r, i;
  476. size_t len, keylen;
  477. crypto_dh_env_t *dh = NULL;
  478. origin_circuit_t *launched = NULL;
  479. crypt_path_t *cpath = NULL;
  480. char serviceid[REND_SERVICE_ID_LEN+1];
  481. char hexcookie[9];
  482. int circ_needs_uptime;
  483. int reason = END_CIRC_REASON_TORPROTOCOL;
  484. crypto_pk_env_t *intro_key;
  485. char intro_key_digest[DIGEST_LEN];
  486. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  487. circuit->rend_pk_digest,10);
  488. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  489. escaped(serviceid), circuit->_base.n_circ_id);
  490. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  491. log_warn(LD_PROTOCOL,
  492. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  493. circuit->_base.n_circ_id);
  494. return -1;
  495. }
  496. /* min key length plus digest length plus nickname length */
  497. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  498. DH_KEY_LEN+42) {
  499. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  500. circuit->_base.n_circ_id);
  501. return -1;
  502. }
  503. /* look up service depending on circuit. */
  504. service = rend_service_get_by_pk_digest_and_version(
  505. circuit->rend_pk_digest, circuit->rend_desc_version);
  506. if (!service) {
  507. log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
  508. escaped(serviceid));
  509. return -1;
  510. }
  511. /* if descriptor is versioned, use intro key instead of service key. */
  512. if (circuit->rend_desc_version & 1) {
  513. intro_key = service->private_key;
  514. } else {
  515. intro_key = circuit->intro_key;
  516. }
  517. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  518. crypto_pk_get_digest(intro_key, intro_key_digest);
  519. if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
  520. base32_encode(serviceid, REND_SERVICE_ID_LEN+1, request, 10);
  521. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  522. escaped(serviceid));
  523. return -1;
  524. }
  525. keylen = crypto_pk_keysize(intro_key);
  526. if (request_len < keylen+DIGEST_LEN) {
  527. log_warn(LD_PROTOCOL,
  528. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  529. return -1;
  530. }
  531. /* Next N bytes is encrypted with service key */
  532. note_crypto_pk_op(REND_SERVER);
  533. r = crypto_pk_private_hybrid_decrypt(
  534. intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
  535. PK_PKCS1_OAEP_PADDING,1);
  536. if (r<0) {
  537. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  538. return -1;
  539. }
  540. len = r;
  541. if (*buf == 2) {
  542. /* Version 2 INTRODUCE2 cell. */
  543. int klen;
  544. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  545. extend_info->addr = ntohl(get_uint32(buf+1));
  546. extend_info->port = ntohs(get_uint16(buf+5));
  547. memcpy(extend_info->identity_digest, buf+7, DIGEST_LEN);
  548. extend_info->nickname[0] = '$';
  549. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  550. extend_info->identity_digest, DIGEST_LEN);
  551. klen = ntohs(get_uint16(buf+7+DIGEST_LEN));
  552. if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
  553. log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
  554. (int)len);
  555. reason = END_CIRC_REASON_TORPROTOCOL;
  556. goto err;
  557. }
  558. extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
  559. if (!extend_info->onion_key) {
  560. log_warn(LD_PROTOCOL,
  561. "Error decoding onion key in version 2 INTRODUCE2 cell.");
  562. reason = END_CIRC_REASON_TORPROTOCOL;
  563. goto err;
  564. }
  565. ptr = buf+7+DIGEST_LEN+2+klen;
  566. len -= 7+DIGEST_LEN+2+klen;
  567. } else {
  568. char *rp_nickname;
  569. size_t nickname_field_len;
  570. routerinfo_t *router;
  571. int version;
  572. if (*buf == 1) {
  573. rp_nickname = buf+1;
  574. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  575. version = 1;
  576. } else {
  577. nickname_field_len = MAX_NICKNAME_LEN+1;
  578. rp_nickname = buf;
  579. version = 0;
  580. }
  581. ptr=memchr(rp_nickname,0,nickname_field_len);
  582. if (!ptr || ptr == rp_nickname) {
  583. log_warn(LD_PROTOCOL,
  584. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  585. return -1;
  586. }
  587. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  588. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  589. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  590. return -1;
  591. }
  592. /* Okay, now we know that a nickname is at the start of the buffer. */
  593. ptr = rp_nickname+nickname_field_len;
  594. len -= nickname_field_len;
  595. len -= rp_nickname - buf; /* also remove header space used by version, if
  596. * any */
  597. router = router_get_by_nickname(rp_nickname, 0);
  598. if (!router) {
  599. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  600. escaped_safe_str(rp_nickname));
  601. /* XXXX Add a no-such-router reason? */
  602. reason = END_CIRC_REASON_TORPROTOCOL;
  603. goto err;
  604. }
  605. extend_info = extend_info_from_router(router);
  606. }
  607. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  608. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  609. reason = END_CIRC_REASON_TORPROTOCOL;
  610. return -1;
  611. }
  612. r_cookie = ptr;
  613. base16_encode(hexcookie,9,r_cookie,4);
  614. /* Try DH handshake... */
  615. dh = crypto_dh_new();
  616. if (!dh || crypto_dh_generate_public(dh)<0) {
  617. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  618. "or generate public key.");
  619. reason = END_CIRC_REASON_INTERNAL;
  620. goto err;
  621. }
  622. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  623. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  624. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  625. reason = END_CIRC_REASON_INTERNAL;
  626. goto err;
  627. }
  628. circ_needs_uptime = rend_service_requires_uptime(service);
  629. /* help predict this next time */
  630. rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
  631. /* Launch a circuit to alice's chosen rendezvous point.
  632. */
  633. for (i=0;i<MAX_REND_FAILURES;i++) {
  634. launched = circuit_launch_by_extend_info(
  635. CIRCUIT_PURPOSE_S_CONNECT_REND, 0, extend_info,
  636. circ_needs_uptime, 1, 1);
  637. if (launched)
  638. break;
  639. }
  640. if (!launched) { /* give up */
  641. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  642. "point %s for service %s.",
  643. escaped_safe_str(extend_info->nickname), serviceid);
  644. reason = END_CIRC_REASON_CONNECTFAILED;
  645. goto err;
  646. }
  647. log_info(LD_REND,
  648. "Accepted intro; launching circuit to %s "
  649. "(cookie %s) for service %s.",
  650. escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
  651. tor_assert(launched->build_state);
  652. /* Fill in the circuit's state. */
  653. memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
  654. DIGEST_LEN);
  655. memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
  656. strlcpy(launched->rend_query, service->service_id,
  657. sizeof(launched->rend_query));
  658. launched->rend_desc_version = service->descriptor_versions;
  659. launched->build_state->pending_final_cpath = cpath =
  660. tor_malloc_zero(sizeof(crypt_path_t));
  661. cpath->magic = CRYPT_PATH_MAGIC;
  662. launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
  663. cpath->dh_handshake_state = dh;
  664. dh = NULL;
  665. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  666. goto err;
  667. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  668. if (extend_info) extend_info_free(extend_info);
  669. return 0;
  670. err:
  671. if (dh) crypto_dh_free(dh);
  672. if (launched)
  673. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  674. if (extend_info) extend_info_free(extend_info);
  675. return -1;
  676. }
  677. /** Called when we fail building a rendezvous circuit at some point other
  678. * than the last hop: launches a new circuit to the same rendezvous point.
  679. */
  680. void
  681. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  682. {
  683. origin_circuit_t *newcirc;
  684. cpath_build_state_t *newstate, *oldstate;
  685. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  686. if (!oldcirc->build_state ||
  687. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  688. oldcirc->build_state->expiry_time < time(NULL)) {
  689. log_info(LD_REND,
  690. "Attempt to build circuit to %s for rendezvous has failed "
  691. "too many times or expired; giving up.",
  692. oldcirc->build_state ?
  693. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  694. return;
  695. }
  696. oldstate = oldcirc->build_state;
  697. tor_assert(oldstate);
  698. if (oldstate->pending_final_cpath == NULL) {
  699. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  700. "Initiator will retry.");
  701. return;
  702. }
  703. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  704. oldstate->chosen_exit->nickname);
  705. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, 0,
  706. oldstate->chosen_exit, 0, 1, 1);
  707. if (!newcirc) {
  708. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  709. oldstate->chosen_exit->nickname);
  710. return;
  711. }
  712. newstate = newcirc->build_state;
  713. tor_assert(newstate);
  714. newstate->failure_count = oldstate->failure_count+1;
  715. newstate->expiry_time = oldstate->expiry_time;
  716. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  717. oldstate->pending_final_cpath = NULL;
  718. memcpy(newcirc->rend_query, oldcirc->rend_query, REND_SERVICE_ID_LEN+1);
  719. memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
  720. DIGEST_LEN);
  721. memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
  722. REND_COOKIE_LEN);
  723. newcirc->rend_desc_version = oldcirc->rend_desc_version;
  724. }
  725. /** Launch a circuit to serve as an introduction point for the service
  726. * <b>service</b> at the introduction point <b>nickname</b>
  727. */
  728. static int
  729. rend_service_launch_establish_intro(rend_service_t *service,
  730. const char *nickname)
  731. {
  732. origin_circuit_t *launched;
  733. log_info(LD_REND,
  734. "Launching circuit to introduction point %s for service %s",
  735. escaped_safe_str(nickname), service->service_id);
  736. rep_hist_note_used_internal(time(NULL), 1, 0);
  737. ++service->n_intro_circuits_launched;
  738. launched = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, 0,
  739. nickname, 1, 0, 1);
  740. if (!launched) {
  741. log_info(LD_REND,
  742. "Can't launch circuit to establish introduction at %s.",
  743. escaped_safe_str(nickname));
  744. return -1;
  745. }
  746. strlcpy(launched->rend_query, service->service_id,
  747. sizeof(launched->rend_query));
  748. memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  749. launched->rend_desc_version = service->descriptor_versions;
  750. if (!(service->descriptor_versions & 1)) {
  751. launched->intro_key = crypto_new_pk_env();
  752. tor_assert(!crypto_pk_generate_key(launched->intro_key));
  753. strmap_set(service->intro_keys, nickname,
  754. crypto_pk_dup_key(launched->intro_key));
  755. }
  756. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  757. rend_service_intro_has_opened(launched);
  758. return 0;
  759. }
  760. /** Called when we're done building a circuit to an introduction point:
  761. * sends a RELAY_ESTABLISH_INTRO cell.
  762. */
  763. void
  764. rend_service_intro_has_opened(origin_circuit_t *circuit)
  765. {
  766. rend_service_t *service;
  767. size_t len;
  768. int r;
  769. char buf[RELAY_PAYLOAD_SIZE];
  770. char auth[DIGEST_LEN + 9];
  771. char serviceid[REND_SERVICE_ID_LEN+1];
  772. int reason = END_CIRC_REASON_TORPROTOCOL;
  773. crypto_pk_env_t *intro_key;
  774. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  775. tor_assert(circuit->cpath);
  776. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  777. circuit->rend_pk_digest,10);
  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, "Unrecognized service ID %s on introduction circuit %d.",
  782. serviceid, circuit->_base.n_circ_id);
  783. reason = END_CIRC_REASON_NOSUCHSERVICE;
  784. goto err;
  785. }
  786. log_info(LD_REND,
  787. "Established circuit %d as introduction point for service %s",
  788. circuit->_base.n_circ_id, serviceid);
  789. /* If the introduction point will not be used in an unversioned
  790. * descriptor, use the intro key instead of the service key in
  791. * ESTABLISH_INTRO. */
  792. if (service->descriptor_versions & 1)
  793. intro_key = service->private_key;
  794. else
  795. intro_key = circuit->intro_key;
  796. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  797. len = crypto_pk_asn1_encode(intro_key, buf+2,
  798. RELAY_PAYLOAD_SIZE-2);
  799. set_uint16(buf, htons((uint16_t)len));
  800. len += 2;
  801. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  802. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  803. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  804. goto err;
  805. len += 20;
  806. note_crypto_pk_op(REND_SERVER);
  807. r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
  808. if (r<0) {
  809. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  810. reason = END_CIRC_REASON_INTERNAL;
  811. goto err;
  812. }
  813. len += r;
  814. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  815. RELAY_COMMAND_ESTABLISH_INTRO,
  816. buf, len, circuit->cpath->prev)<0) {
  817. log_info(LD_GENERAL,
  818. "Couldn't send introduction request for service %s on circuit %d",
  819. serviceid, circuit->_base.n_circ_id);
  820. reason = END_CIRC_REASON_INTERNAL;
  821. goto err;
  822. }
  823. return;
  824. err:
  825. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  826. }
  827. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  828. * live introduction point, and note that the service descriptor is
  829. * now out-of-date.*/
  830. int
  831. rend_service_intro_established(origin_circuit_t *circuit, const char *request,
  832. size_t request_len)
  833. {
  834. rend_service_t *service;
  835. char serviceid[REND_SERVICE_ID_LEN+1];
  836. (void) request;
  837. (void) request_len;
  838. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  839. log_warn(LD_PROTOCOL,
  840. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  841. goto err;
  842. }
  843. service = rend_service_get_by_pk_digest_and_version(
  844. circuit->rend_pk_digest, circuit->rend_desc_version);
  845. if (!service) {
  846. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  847. circuit->_base.n_circ_id);
  848. goto err;
  849. }
  850. service->desc_is_dirty = time(NULL);
  851. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  852. base32_encode(serviceid, REND_SERVICE_ID_LEN + 1,
  853. circuit->rend_pk_digest, 10);
  854. log_info(LD_REND,
  855. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  856. circuit->_base.n_circ_id, serviceid);
  857. return 0;
  858. err:
  859. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  860. return -1;
  861. }
  862. /** Called once a circuit to a rendezvous point is established: sends a
  863. * RELAY_COMMAND_RENDEZVOUS1 cell.
  864. */
  865. void
  866. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  867. {
  868. rend_service_t *service;
  869. char buf[RELAY_PAYLOAD_SIZE];
  870. crypt_path_t *hop;
  871. char serviceid[REND_SERVICE_ID_LEN+1];
  872. char hexcookie[9];
  873. int reason;
  874. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  875. tor_assert(circuit->cpath);
  876. tor_assert(circuit->build_state);
  877. hop = circuit->build_state->pending_final_cpath;
  878. tor_assert(hop);
  879. base16_encode(hexcookie,9,circuit->rend_cookie,4);
  880. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  881. circuit->rend_pk_digest,10);
  882. log_info(LD_REND,
  883. "Done building circuit %d to rendezvous with "
  884. "cookie %s for service %s",
  885. circuit->_base.n_circ_id, hexcookie, serviceid);
  886. service = rend_service_get_by_pk_digest_and_version(
  887. circuit->rend_pk_digest, circuit->rend_desc_version);
  888. if (!service) {
  889. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  890. "introduction circuit.");
  891. reason = END_CIRC_REASON_INTERNAL;
  892. goto err;
  893. }
  894. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  895. memcpy(buf, circuit->rend_cookie, REND_COOKIE_LEN);
  896. if (crypto_dh_get_public(hop->dh_handshake_state,
  897. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  898. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  899. reason = END_CIRC_REASON_INTERNAL;
  900. goto err;
  901. }
  902. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  903. DIGEST_LEN);
  904. /* Send the cell */
  905. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  906. RELAY_COMMAND_RENDEZVOUS1,
  907. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  908. circuit->cpath->prev)<0) {
  909. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  910. reason = END_CIRC_REASON_INTERNAL;
  911. goto err;
  912. }
  913. crypto_dh_free(hop->dh_handshake_state);
  914. hop->dh_handshake_state = NULL;
  915. /* Append the cpath entry. */
  916. hop->state = CPATH_STATE_OPEN;
  917. /* set the windows to default. these are the windows
  918. * that bob thinks alice has.
  919. */
  920. hop->package_window = CIRCWINDOW_START;
  921. hop->deliver_window = CIRCWINDOW_START;
  922. onion_append_to_cpath(&circuit->cpath, hop);
  923. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  924. /* Change the circuit purpose. */
  925. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  926. return;
  927. err:
  928. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  929. }
  930. /*
  931. * Manage introduction points
  932. */
  933. /** Return the (possibly non-open) introduction circuit ending at
  934. * <b>router</b> for the service whose public key is <b>pk_digest</b>. Return
  935. * NULL if no such service is found.
  936. */
  937. static origin_circuit_t *
  938. find_intro_circuit(routerinfo_t *router, const char *pk_digest)
  939. {
  940. origin_circuit_t *circ = NULL;
  941. tor_assert(router);
  942. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  943. CIRCUIT_PURPOSE_S_INTRO))) {
  944. if (!strcasecmp(circ->build_state->chosen_exit->nickname,
  945. router->nickname)) {
  946. return circ;
  947. }
  948. }
  949. circ = NULL;
  950. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  951. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  952. if (!strcasecmp(circ->build_state->chosen_exit->nickname,
  953. router->nickname)) {
  954. return circ;
  955. }
  956. }
  957. return NULL;
  958. }
  959. /** Encode and sign up-to-date v0 and/or v2 service descriptors for
  960. * <b>service</b>, and upload it/them to all the dirservers/to the
  961. * responsible hidden service directories.
  962. */
  963. static void
  964. upload_service_descriptor(rend_service_t *service)
  965. {
  966. time_t now = time(NULL);
  967. int rendpostperiod;
  968. char serviceid[REND_SERVICE_ID_LEN+1];
  969. int uploaded = 0;
  970. /* Update the descriptor. */
  971. rend_service_update_descriptor(service);
  972. rendpostperiod = get_options()->RendPostPeriod;
  973. /* Upload unversioned (v0) descriptor? */
  974. if (service->descriptor_versions & 1 &&
  975. get_options()->PublishHidServDescriptors) {
  976. char *desc;
  977. size_t desc_len;
  978. /* Encode the descriptor. */
  979. if (rend_encode_service_descriptor(service->desc,
  980. service->private_key,
  981. &desc, &desc_len)<0) {
  982. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  983. "not uploading.");
  984. return;
  985. }
  986. /* Post it to the dirservers */
  987. rend_get_service_id(service->desc->pk, serviceid);
  988. log_info(LD_REND, "Sending publish request for hidden service %s",
  989. serviceid);
  990. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
  991. ROUTER_PURPOSE_GENERAL,
  992. HIDSERV_AUTHORITY, desc, desc_len, 0);
  993. tor_free(desc);
  994. service->next_upload_time = now + rendpostperiod;
  995. uploaded = 1;
  996. }
  997. /* Upload v2 descriptor? */
  998. if (service->descriptor_versions & (1 << 2) &&
  999. get_options()->PublishHidServDescriptors) {
  1000. if (hid_serv_have_enough_directories()) {
  1001. int seconds_valid;
  1002. smartlist_t *desc_strs = smartlist_create();
  1003. smartlist_t *desc_ids = smartlist_create();
  1004. int i;
  1005. /* Encode the current descriptor. */
  1006. seconds_valid = rend_encode_v2_descriptors(desc_strs, desc_ids,
  1007. service->desc, now, NULL, 0);
  1008. if (seconds_valid < 0) {
  1009. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  1010. "not uploading.");
  1011. return;
  1012. }
  1013. /* Post the current descriptors to the hidden service directories. */
  1014. rend_get_service_id(service->desc->pk, serviceid);
  1015. log_info(LD_REND, "Sending publish request for hidden service %s",
  1016. serviceid);
  1017. directory_post_to_hs_dir(desc_ids, desc_strs, serviceid, seconds_valid);
  1018. /* Free memory for descriptors. */
  1019. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  1020. tor_free(smartlist_get(desc_strs, i));
  1021. tor_free(smartlist_get(desc_ids, i));
  1022. }
  1023. smartlist_clear(desc_strs);
  1024. smartlist_clear(desc_ids);
  1025. /* Update next upload time. */
  1026. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1027. > rendpostperiod)
  1028. service->next_upload_time = now + rendpostperiod;
  1029. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1030. service->next_upload_time = now + seconds_valid + 1;
  1031. else
  1032. service->next_upload_time = now + seconds_valid -
  1033. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1034. /* Post also the next descriptors, if necessary. */
  1035. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1036. seconds_valid = rend_encode_v2_descriptors(desc_strs, desc_ids,
  1037. service->desc, now, NULL, 1);
  1038. if (seconds_valid < 0) {
  1039. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1040. "descriptor; not uploading.");
  1041. return;
  1042. }
  1043. directory_post_to_hs_dir(desc_ids, desc_strs, serviceid,
  1044. seconds_valid);
  1045. /* Free memory for descriptors. */
  1046. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  1047. tor_free(smartlist_get(desc_strs, i));
  1048. tor_free(smartlist_get(desc_ids, i));
  1049. }
  1050. smartlist_free(desc_strs);
  1051. smartlist_free(desc_ids);
  1052. }
  1053. uploaded = 1;
  1054. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1055. }
  1056. }
  1057. /* If not uploaded, try again in one minute. */
  1058. if (!uploaded)
  1059. service->next_upload_time = now + 60;
  1060. /* Unmark dirty flag of this service. */
  1061. service->desc_is_dirty = 0;
  1062. }
  1063. /** For every service, check how many intro points it currently has, and:
  1064. * - Pick new intro points as necessary.
  1065. * - Launch circuits to any new intro points.
  1066. */
  1067. void
  1068. rend_services_introduce(void)
  1069. {
  1070. int i,j,r;
  1071. routerinfo_t *router;
  1072. rend_service_t *service;
  1073. char *intro;
  1074. int changed, prev_intro_nodes;
  1075. smartlist_t *intro_routers, *exclude_routers;
  1076. time_t now;
  1077. intro_routers = smartlist_create();
  1078. exclude_routers = smartlist_create();
  1079. now = time(NULL);
  1080. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1081. smartlist_clear(intro_routers);
  1082. service = smartlist_get(rend_service_list, i);
  1083. tor_assert(service);
  1084. changed = 0;
  1085. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1086. /* One period has elapsed; we can try building circuits again. */
  1087. service->intro_period_started = now;
  1088. service->n_intro_circuits_launched = 0;
  1089. } else if (service->n_intro_circuits_launched >=
  1090. MAX_INTRO_CIRCS_PER_PERIOD) {
  1091. /* We have failed too many times in this period; wait for the next
  1092. * one before we try again. */
  1093. continue;
  1094. }
  1095. /* Find out which introduction points we have in progress for this
  1096. service. */
  1097. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1098. intro = smartlist_get(service->intro_nodes, j);
  1099. router = router_get_by_nickname(intro, 0);
  1100. if (!router || !find_intro_circuit(router,service->pk_digest)) {
  1101. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1102. intro, service->service_id);
  1103. tor_free(intro);
  1104. /* XXXXX020 we could also remove the intro key here. */
  1105. smartlist_del(service->intro_nodes,j--);
  1106. changed = 1;
  1107. service->desc_is_dirty = now;
  1108. }
  1109. smartlist_add(intro_routers, router);
  1110. }
  1111. /* We have enough intro points, and the intro points we thought we had were
  1112. * all connected.
  1113. */
  1114. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1115. /* We have all our intro points! Start a fresh period and reset the
  1116. * circuit count. */
  1117. service->intro_period_started = now;
  1118. service->n_intro_circuits_launched = 0;
  1119. continue;
  1120. }
  1121. /* Remember how many introduction circuits we started with. */
  1122. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1123. smartlist_add_all(exclude_routers, intro_routers);
  1124. /* The directory is now here. Pick three ORs as intro points. */
  1125. for (j=prev_intro_nodes; j < NUM_INTRO_POINTS; ++j) {
  1126. char *hex_digest;
  1127. router = router_choose_random_node(service->intro_prefer_nodes,
  1128. service->intro_exclude_nodes, exclude_routers, 1, 0, 0,
  1129. get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION,
  1130. 0, 0);
  1131. if (!router) {
  1132. log_warn(LD_REND,
  1133. "Could only establish %d introduction points for %s.",
  1134. smartlist_len(service->intro_nodes), service->service_id);
  1135. break;
  1136. }
  1137. changed = 1;
  1138. hex_digest = tor_malloc_zero(HEX_DIGEST_LEN+2);
  1139. hex_digest[0] = '$';
  1140. base16_encode(hex_digest+1, HEX_DIGEST_LEN+1,
  1141. router->cache_info.identity_digest,
  1142. DIGEST_LEN);
  1143. smartlist_add(intro_routers, router);
  1144. smartlist_add(exclude_routers, router);
  1145. smartlist_add(service->intro_nodes, hex_digest);
  1146. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1147. router->nickname, service->service_id);
  1148. }
  1149. /* Reset exclude_routers, for the next time around the loop. */
  1150. smartlist_clear(exclude_routers);
  1151. /* If there's no need to launch new circuits, stop here. */
  1152. if (!changed)
  1153. continue;
  1154. /* Establish new introduction points. */
  1155. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1156. intro = smartlist_get(service->intro_nodes, j);
  1157. r = rend_service_launch_establish_intro(service, intro);
  1158. if (r<0) {
  1159. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1160. intro, service->service_id);
  1161. }
  1162. }
  1163. }
  1164. smartlist_free(intro_routers);
  1165. smartlist_free(exclude_routers);
  1166. }
  1167. /** Regenerate and upload rendezvous service descriptors for all
  1168. * services, if necessary. If the descriptor has been dirty enough
  1169. * for long enough, definitely upload; else only upload when the
  1170. * periodic timeout has expired.
  1171. *
  1172. * For the first upload, pick a random time between now and two periods
  1173. * from now, and pick it independently for each service.
  1174. */
  1175. void
  1176. rend_consider_services_upload(time_t now)
  1177. {
  1178. int i;
  1179. rend_service_t *service;
  1180. int rendpostperiod = get_options()->RendPostPeriod;
  1181. if (!get_options()->PublishHidServDescriptors)
  1182. return;
  1183. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1184. service = smartlist_get(rend_service_list, i);
  1185. if (!service->next_upload_time) { /* never been uploaded yet */
  1186. service->next_upload_time =
  1187. now + crypto_rand_int(2*rendpostperiod);
  1188. }
  1189. if (service->next_upload_time < now ||
  1190. (service->desc_is_dirty &&
  1191. service->desc_is_dirty < now-30)) {
  1192. /* if it's time, or if the directory servers have a wrong service
  1193. * descriptor and ours has been stable for 30 seconds, upload a
  1194. * new one of each format. */
  1195. upload_service_descriptor(service);
  1196. }
  1197. }
  1198. }
  1199. /** Log the status of introduction points for all rendezvous services
  1200. * at log severity <b>severity</b>.
  1201. */
  1202. void
  1203. rend_service_dump_stats(int severity)
  1204. {
  1205. int i,j;
  1206. routerinfo_t *router;
  1207. rend_service_t *service;
  1208. const char *nickname, *safe_name;
  1209. char nn_buf[MAX_VERBOSE_NICKNAME_LEN];
  1210. origin_circuit_t *circ;
  1211. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1212. service = smartlist_get(rend_service_list, i);
  1213. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1214. service->directory);
  1215. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1216. nickname = smartlist_get(service->intro_nodes, j);
  1217. router = router_get_by_nickname(nickname,1);
  1218. if (router) {
  1219. router_get_verbose_nickname(nn_buf, router);
  1220. nickname = nn_buf;
  1221. }
  1222. safe_name = safe_str(nickname);
  1223. if (!router) {
  1224. log(severity, LD_GENERAL,
  1225. " Intro point %d at %s: unrecognized router", j, safe_name);
  1226. continue;
  1227. }
  1228. circ = find_intro_circuit(router, service->pk_digest);
  1229. if (!circ) {
  1230. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1231. j, safe_name);
  1232. continue;
  1233. }
  1234. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1235. j, safe_name, circuit_state_to_string(circ->_base.state));
  1236. }
  1237. }
  1238. }
  1239. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1240. * 'circ', and look up the port and address based on conn-\>port.
  1241. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1242. * or 0 for success.
  1243. */
  1244. int
  1245. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1246. origin_circuit_t *circ)
  1247. {
  1248. rend_service_t *service;
  1249. char serviceid[REND_SERVICE_ID_LEN+1];
  1250. smartlist_t *matching_ports;
  1251. rend_service_port_config_t *chosen_port;
  1252. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1253. log_debug(LD_REND,"beginning to hunt for addr/port");
  1254. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  1255. circ->rend_pk_digest,10);
  1256. service = rend_service_get_by_pk_digest_and_version(circ->rend_pk_digest,
  1257. circ->rend_desc_version);
  1258. if (!service) {
  1259. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1260. "rendezvous circuit %d; closing.",
  1261. serviceid, circ->_base.n_circ_id);
  1262. return -1;
  1263. }
  1264. matching_ports = smartlist_create();
  1265. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1266. {
  1267. if (conn->_base.port == p->virtual_port) {
  1268. smartlist_add(matching_ports, p);
  1269. }
  1270. });
  1271. chosen_port = smartlist_choose(matching_ports);
  1272. smartlist_free(matching_ports);
  1273. if (chosen_port) {
  1274. conn->_base.addr = chosen_port->real_addr;
  1275. conn->_base.port = chosen_port->real_port;
  1276. return 0;
  1277. }
  1278. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1279. conn->_base.port,serviceid);
  1280. return -1;
  1281. }