rendservice.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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. smartlist_t *hs_dirs = hid_serv_create_routing_table();
  1001. if (hid_serv_have_enough_directories(hs_dirs)) {
  1002. int seconds_valid;
  1003. smartlist_t *desc_strs = smartlist_create();
  1004. smartlist_t *desc_ids = smartlist_create();
  1005. int i;
  1006. /* Encode the current descriptor. */
  1007. seconds_valid = rend_encode_v2_descriptors(desc_strs, desc_ids,
  1008. service->desc, now, NULL, 0);
  1009. if (seconds_valid < 0) {
  1010. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  1011. "not uploading.");
  1012. smartlist_free(hs_dirs);
  1013. return;
  1014. }
  1015. /* Post the current descriptors to the hidden service directories. */
  1016. rend_get_service_id(service->desc->pk, serviceid);
  1017. log_info(LD_REND, "Sending publish request for hidden service %s",
  1018. serviceid);
  1019. directory_post_to_hs_dir(desc_ids, desc_strs, serviceid, seconds_valid,
  1020. hs_dirs);
  1021. /* Free memory for descriptors. */
  1022. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  1023. tor_free(smartlist_get(desc_strs, i));
  1024. tor_free(smartlist_get(desc_ids, i));
  1025. }
  1026. smartlist_clear(desc_strs);
  1027. smartlist_clear(desc_ids);
  1028. /* Update next upload time. */
  1029. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1030. > rendpostperiod)
  1031. service->next_upload_time = now + rendpostperiod;
  1032. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1033. service->next_upload_time = now + seconds_valid + 1;
  1034. else
  1035. service->next_upload_time = now + seconds_valid -
  1036. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1037. /* Post also the next descriptors, if necessary. */
  1038. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1039. seconds_valid = rend_encode_v2_descriptors(desc_strs, desc_ids,
  1040. service->desc, now, NULL, 1);
  1041. if (seconds_valid < 0) {
  1042. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1043. "descriptor; not uploading.");
  1044. smartlist_free(hs_dirs);
  1045. return;
  1046. }
  1047. directory_post_to_hs_dir(desc_ids, desc_strs, serviceid,
  1048. seconds_valid, hs_dirs);
  1049. /* Free memory for descriptors. */
  1050. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  1051. tor_free(smartlist_get(desc_strs, i));
  1052. tor_free(smartlist_get(desc_ids, i));
  1053. }
  1054. smartlist_free(desc_strs);
  1055. smartlist_free(desc_ids);
  1056. }
  1057. smartlist_free(hs_dirs);
  1058. uploaded = 1;
  1059. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1060. }
  1061. }
  1062. /* If not uploaded, try again in one minute. */
  1063. if (!uploaded)
  1064. service->next_upload_time = now + 60;
  1065. /* Unmark dirty flag of this service. */
  1066. service->desc_is_dirty = 0;
  1067. }
  1068. /** For every service, check how many intro points it currently has, and:
  1069. * - Pick new intro points as necessary.
  1070. * - Launch circuits to any new intro points.
  1071. */
  1072. void
  1073. rend_services_introduce(void)
  1074. {
  1075. int i,j,r;
  1076. routerinfo_t *router;
  1077. rend_service_t *service;
  1078. char *intro;
  1079. int changed, prev_intro_nodes;
  1080. smartlist_t *intro_routers, *exclude_routers;
  1081. time_t now;
  1082. intro_routers = smartlist_create();
  1083. exclude_routers = smartlist_create();
  1084. now = time(NULL);
  1085. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1086. smartlist_clear(intro_routers);
  1087. service = smartlist_get(rend_service_list, i);
  1088. tor_assert(service);
  1089. changed = 0;
  1090. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1091. /* One period has elapsed; we can try building circuits again. */
  1092. service->intro_period_started = now;
  1093. service->n_intro_circuits_launched = 0;
  1094. } else if (service->n_intro_circuits_launched >=
  1095. MAX_INTRO_CIRCS_PER_PERIOD) {
  1096. /* We have failed too many times in this period; wait for the next
  1097. * one before we try again. */
  1098. continue;
  1099. }
  1100. /* Find out which introduction points we have in progress for this
  1101. service. */
  1102. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1103. intro = smartlist_get(service->intro_nodes, j);
  1104. router = router_get_by_nickname(intro, 0);
  1105. if (!router || !find_intro_circuit(router,service->pk_digest)) {
  1106. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1107. intro, service->service_id);
  1108. tor_free(intro);
  1109. /* XXXXX020 we could also remove the intro key here. */
  1110. smartlist_del(service->intro_nodes,j--);
  1111. changed = 1;
  1112. service->desc_is_dirty = now;
  1113. }
  1114. smartlist_add(intro_routers, router);
  1115. }
  1116. /* We have enough intro points, and the intro points we thought we had were
  1117. * all connected.
  1118. */
  1119. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1120. /* We have all our intro points! Start a fresh period and reset the
  1121. * circuit count. */
  1122. service->intro_period_started = now;
  1123. service->n_intro_circuits_launched = 0;
  1124. continue;
  1125. }
  1126. /* Remember how many introduction circuits we started with. */
  1127. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1128. smartlist_add_all(exclude_routers, intro_routers);
  1129. /* The directory is now here. Pick three ORs as intro points. */
  1130. for (j=prev_intro_nodes; j < NUM_INTRO_POINTS; ++j) {
  1131. char *hex_digest;
  1132. router = router_choose_random_node(service->intro_prefer_nodes,
  1133. service->intro_exclude_nodes, exclude_routers, 1, 0, 0,
  1134. get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION,
  1135. 0, 0);
  1136. if (!router) {
  1137. log_warn(LD_REND,
  1138. "Could only establish %d introduction points for %s.",
  1139. smartlist_len(service->intro_nodes), service->service_id);
  1140. break;
  1141. }
  1142. changed = 1;
  1143. hex_digest = tor_malloc_zero(HEX_DIGEST_LEN+2);
  1144. hex_digest[0] = '$';
  1145. base16_encode(hex_digest+1, HEX_DIGEST_LEN+1,
  1146. router->cache_info.identity_digest,
  1147. DIGEST_LEN);
  1148. smartlist_add(intro_routers, router);
  1149. smartlist_add(exclude_routers, router);
  1150. smartlist_add(service->intro_nodes, hex_digest);
  1151. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1152. router->nickname, service->service_id);
  1153. }
  1154. /* Reset exclude_routers, for the next time around the loop. */
  1155. smartlist_clear(exclude_routers);
  1156. /* If there's no need to launch new circuits, stop here. */
  1157. if (!changed)
  1158. continue;
  1159. /* Establish new introduction points. */
  1160. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1161. intro = smartlist_get(service->intro_nodes, j);
  1162. r = rend_service_launch_establish_intro(service, intro);
  1163. if (r<0) {
  1164. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1165. intro, service->service_id);
  1166. }
  1167. }
  1168. }
  1169. smartlist_free(intro_routers);
  1170. smartlist_free(exclude_routers);
  1171. }
  1172. /** Regenerate and upload rendezvous service descriptors for all
  1173. * services, if necessary. If the descriptor has been dirty enough
  1174. * for long enough, definitely upload; else only upload when the
  1175. * periodic timeout has expired.
  1176. *
  1177. * For the first upload, pick a random time between now and two periods
  1178. * from now, and pick it independently for each service.
  1179. */
  1180. void
  1181. rend_consider_services_upload(time_t now)
  1182. {
  1183. int i;
  1184. rend_service_t *service;
  1185. int rendpostperiod = get_options()->RendPostPeriod;
  1186. if (!get_options()->PublishHidServDescriptors)
  1187. return;
  1188. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1189. service = smartlist_get(rend_service_list, i);
  1190. if (!service->next_upload_time) { /* never been uploaded yet */
  1191. service->next_upload_time =
  1192. now + crypto_rand_int(2*rendpostperiod);
  1193. }
  1194. if (service->next_upload_time < now ||
  1195. (service->desc_is_dirty &&
  1196. service->desc_is_dirty < now-30)) {
  1197. /* if it's time, or if the directory servers have a wrong service
  1198. * descriptor and ours has been stable for 30 seconds, upload a
  1199. * new one of each format. */
  1200. upload_service_descriptor(service);
  1201. }
  1202. }
  1203. }
  1204. /** Log the status of introduction points for all rendezvous services
  1205. * at log severity <b>severity</b>.
  1206. */
  1207. void
  1208. rend_service_dump_stats(int severity)
  1209. {
  1210. int i,j;
  1211. routerinfo_t *router;
  1212. rend_service_t *service;
  1213. const char *nickname, *safe_name;
  1214. char nn_buf[MAX_VERBOSE_NICKNAME_LEN];
  1215. origin_circuit_t *circ;
  1216. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1217. service = smartlist_get(rend_service_list, i);
  1218. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1219. service->directory);
  1220. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1221. nickname = smartlist_get(service->intro_nodes, j);
  1222. router = router_get_by_nickname(nickname,1);
  1223. if (router) {
  1224. router_get_verbose_nickname(nn_buf, router);
  1225. nickname = nn_buf;
  1226. }
  1227. safe_name = safe_str(nickname);
  1228. if (!router) {
  1229. log(severity, LD_GENERAL,
  1230. " Intro point %d at %s: unrecognized router", j, safe_name);
  1231. continue;
  1232. }
  1233. circ = find_intro_circuit(router, service->pk_digest);
  1234. if (!circ) {
  1235. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1236. j, safe_name);
  1237. continue;
  1238. }
  1239. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1240. j, safe_name, circuit_state_to_string(circ->_base.state));
  1241. }
  1242. }
  1243. }
  1244. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1245. * 'circ', and look up the port and address based on conn-\>port.
  1246. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1247. * or 0 for success.
  1248. */
  1249. int
  1250. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1251. origin_circuit_t *circ)
  1252. {
  1253. rend_service_t *service;
  1254. char serviceid[REND_SERVICE_ID_LEN+1];
  1255. smartlist_t *matching_ports;
  1256. rend_service_port_config_t *chosen_port;
  1257. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1258. log_debug(LD_REND,"beginning to hunt for addr/port");
  1259. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  1260. circ->rend_pk_digest,10);
  1261. service = rend_service_get_by_pk_digest_and_version(circ->rend_pk_digest,
  1262. circ->rend_desc_version);
  1263. if (!service) {
  1264. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1265. "rendezvous circuit %d; closing.",
  1266. serviceid, circ->_base.n_circ_id);
  1267. return -1;
  1268. }
  1269. matching_ports = smartlist_create();
  1270. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1271. {
  1272. if (conn->_base.port == p->virtual_port) {
  1273. smartlist_add(matching_ports, p);
  1274. }
  1275. });
  1276. chosen_port = smartlist_choose(matching_ports);
  1277. smartlist_free(matching_ports);
  1278. if (chosen_port) {
  1279. conn->_base.addr = chosen_port->real_addr;
  1280. conn->_base.port = chosen_port->real_port;
  1281. return 0;
  1282. }
  1283. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1284. conn->_base.port,serviceid);
  1285. return -1;
  1286. }