rendservice.c 47 KB

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