rendservice.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /* Copyright 2004 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char rendservice_c_id[] = "$Id$";
  5. /**
  6. * \file rendservice.c
  7. * \brief The hidden-service side of rendezvous functionality.
  8. **/
  9. #include "or.h"
  10. static circuit_t *find_intro_circuit(routerinfo_t *router, const char *pk_digest);
  11. /** Represents the mapping from a virtual port of a rendezvous service to
  12. * a real port on some IP.
  13. */
  14. typedef struct rend_service_port_config_t {
  15. uint16_t virtual_port;
  16. uint16_t real_port;
  17. uint32_t real_address;
  18. } rend_service_port_config_t;
  19. /** Try to maintain this many intro points per service if possible. */
  20. #define NUM_INTRO_POINTS 3
  21. /** If we can't build our intro circuits, don't retry for this long. */
  22. #define INTRO_CIRC_RETRY_PERIOD 60*5
  23. /** Don't try to build more than this many circuits before giving up
  24. * for a while.*/
  25. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  26. /** How many times will a hidden service operator attempt to connect to
  27. * a requested rendezvous point before giving up? */
  28. #define MAX_REND_FAILURES 3
  29. /** Represents a single hidden service running at this OP. */
  30. typedef struct rend_service_t {
  31. /** Fields specified in config file */
  32. char *directory; /**< where in the filesystem it stores it */
  33. smartlist_t *ports; /**< List of rend_service_port_config_t */
  34. char *intro_prefer_nodes; /**< comma-separated list of nicknames */
  35. char *intro_exclude_nodes; /**< comma-separated list of nicknames */
  36. /* Other fields */
  37. crypto_pk_env_t *private_key;
  38. char service_id[REND_SERVICE_ID_LEN+1];
  39. char pk_digest[DIGEST_LEN];
  40. smartlist_t *intro_nodes; /**< list of hexdigests for intro points we have,
  41. * or are trying to establish. */
  42. time_t intro_period_started;
  43. int n_intro_circuits_launched; /**< count of intro circuits we have
  44. * established in this period. */
  45. rend_service_descriptor_t *desc;
  46. time_t desc_is_dirty;
  47. time_t next_upload_time;
  48. } rend_service_t;
  49. /** A list of rend_service_t's for services run on this OP.
  50. */
  51. static smartlist_t *rend_service_list = NULL;
  52. /** Release the storage held by <b>service</b>.
  53. */
  54. static void rend_service_free(rend_service_t *service)
  55. {
  56. if (!service) return;
  57. tor_free(service->directory);
  58. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  59. smartlist_free(service->ports);
  60. if (service->private_key)
  61. crypto_free_pk_env(service->private_key);
  62. tor_free(service->intro_prefer_nodes);
  63. tor_free(service->intro_exclude_nodes);
  64. SMARTLIST_FOREACH(service->intro_nodes, void*, p, tor_free(p));
  65. smartlist_free(service->intro_nodes);
  66. if (service->desc)
  67. rend_service_descriptor_free(service->desc);
  68. tor_free(service);
  69. }
  70. /** Release all the storage held in rend_service_list, and allocate a new,
  71. * empty rend_service_list.
  72. */
  73. void rend_service_free_all(void)
  74. {
  75. if (!rend_service_list) {
  76. rend_service_list = smartlist_create();
  77. return;
  78. }
  79. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  80. rend_service_free(ptr));
  81. smartlist_free(rend_service_list);
  82. rend_service_list = NULL;
  83. }
  84. /** Validate <b>service</b> and add it to rend_service_list if possible.
  85. */
  86. static void add_service(rend_service_t *service)
  87. {
  88. int i;
  89. rend_service_port_config_t *p;
  90. struct in_addr addr;
  91. if (!service->intro_prefer_nodes)
  92. service->intro_prefer_nodes = tor_strdup("");
  93. if (!service->intro_exclude_nodes)
  94. service->intro_exclude_nodes = tor_strdup("");
  95. if (!smartlist_len(service->ports)) {
  96. log_fn(LOG_WARN, "Hidden service with no ports configured; ignoring.");
  97. rend_service_free(service);
  98. } else {
  99. smartlist_set_capacity(service->ports, -1);
  100. smartlist_add(rend_service_list, service);
  101. log_fn(LOG_DEBUG,"Configuring service with directory %s",service->directory);
  102. for (i = 0; i < smartlist_len(service->ports); ++i) {
  103. char addrbuf[INET_NTOA_BUF_LEN];
  104. p = smartlist_get(service->ports, i);
  105. addr.s_addr = htonl(p->real_address);
  106. tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
  107. log_fn(LOG_DEBUG,"Service maps port %d to %s:%d",
  108. p->virtual_port, addrbuf, p->real_port);
  109. }
  110. }
  111. }
  112. /** Parses a real-port to virtual-port mapping and returns a new
  113. * rend_service_port_config_t.
  114. *
  115. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  116. *
  117. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  118. */
  119. static rend_service_port_config_t *parse_port_config(const char *string)
  120. {
  121. int virtport;
  122. int realport;
  123. uint16_t p;
  124. uint32_t addr;
  125. char *endptr;
  126. rend_service_port_config_t *result;
  127. virtport = (int) strtol(string, &endptr, 10);
  128. if (endptr == string) {
  129. log_fn(LOG_WARN, "Missing port in hidden service port configuration");
  130. return NULL;
  131. }
  132. if (virtport < 1 || virtport > 65535) {
  133. log_fn(LOG_WARN, "Port out of range in hidden service port configuration");
  134. return NULL;
  135. }
  136. string = endptr + strspn(endptr, " \t");
  137. if (!*string) {
  138. /* No addr:port part; use default. */
  139. realport = virtport;
  140. addr = 0x7F000001u; /* 127.0.0.1 */
  141. } else if (strchr(string, ':') || strchr(string, '.')) {
  142. if (parse_addr_port(string, NULL, &addr, &p)<0) {
  143. log_fn(LOG_WARN,"Unparseable address in hidden service port configuration");
  144. return NULL;
  145. }
  146. realport = p?p:virtport;
  147. } else {
  148. /* No addr:port, no addr -- must be port. */
  149. realport = strtol(string, &endptr, 10);
  150. if (*endptr) {
  151. log_fn(LOG_WARN, "Unparseable or missing port in hidden service port configuration.");
  152. return NULL;
  153. }
  154. if (realport < 1 || realport > 65535) {
  155. log_fn(LOG_WARN, "Port out of range");
  156. return NULL;
  157. }
  158. addr = 0x7F000001u; /* Default to 127.0.0.1 */
  159. }
  160. result = tor_malloc(sizeof(rend_service_port_config_t));
  161. result->virtual_port = virtport;
  162. result->real_port = realport;
  163. result->real_address = addr;
  164. return result;
  165. }
  166. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  167. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  168. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  169. * normal, but don't actually change the configured services.)
  170. */
  171. int rend_config_services(or_options_t *options, int validate_only)
  172. {
  173. struct config_line_t *line;
  174. rend_service_t *service = NULL;
  175. rend_service_port_config_t *portcfg;
  176. if (!validate_only) {
  177. rend_service_free_all();
  178. rend_service_list = smartlist_create();
  179. }
  180. for (line = options->RendConfigLines; line; line = line->next) {
  181. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  182. if (service) {
  183. if (validate_only)
  184. rend_service_free(service);
  185. else
  186. add_service(service);
  187. }
  188. service = tor_malloc_zero(sizeof(rend_service_t));
  189. service->directory = tor_strdup(line->value);
  190. service->ports = smartlist_create();
  191. service->intro_nodes = smartlist_create();
  192. service->intro_period_started = time(NULL);
  193. continue;
  194. }
  195. if (!service) {
  196. log_fn(LOG_WARN, "HiddenServicePort with no preceding HiddenServiceDir directive");
  197. rend_service_free(service);
  198. return -1;
  199. }
  200. if (!strcasecmp(line->key, "HiddenServicePort")) {
  201. portcfg = parse_port_config(line->value);
  202. if (!portcfg) {
  203. rend_service_free(service);
  204. return -1;
  205. }
  206. smartlist_add(service->ports, portcfg);
  207. } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
  208. if (service->intro_prefer_nodes) {
  209. log_fn(LOG_WARN, "Got multiple HiddenServiceNodes lines for a single service");
  210. return -1;
  211. }
  212. service->intro_prefer_nodes = tor_strdup(line->value);
  213. } else {
  214. tor_assert(!strcasecmp(line->key, "HiddenServiceExcludeNodes"));
  215. if (service->intro_exclude_nodes) {
  216. log_fn(LOG_WARN, "Got multiple HiddenServiceExcludedNodes lines for a single service");
  217. return -1;
  218. }
  219. service->intro_exclude_nodes = tor_strdup(line->value);
  220. }
  221. }
  222. if (service) {
  223. if (validate_only)
  224. rend_service_free(service);
  225. else
  226. add_service(service);
  227. }
  228. return 0;
  229. }
  230. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  231. * the other fields in service.
  232. */
  233. static void rend_service_update_descriptor(rend_service_t *service)
  234. {
  235. rend_service_descriptor_t *d;
  236. circuit_t *circ;
  237. int i,n;
  238. routerinfo_t *router;
  239. if (service->desc) {
  240. rend_service_descriptor_free(service->desc);
  241. service->desc = NULL;
  242. }
  243. d = service->desc = tor_malloc(sizeof(rend_service_descriptor_t));
  244. d->pk = crypto_pk_dup_key(service->private_key);
  245. d->timestamp = time(NULL);
  246. n = smartlist_len(service->intro_nodes);
  247. d->n_intro_points = 0;
  248. d->intro_points = tor_malloc(sizeof(char*)*n);
  249. for (i=0; i < n; ++i) {
  250. router = router_get_by_nickname(smartlist_get(service->intro_nodes, i));
  251. if (!router) {
  252. log_fn(LOG_WARN,"Router '%s' not found. Skipping.",
  253. (char*)smartlist_get(service->intro_nodes, i));
  254. continue;
  255. }
  256. circ = find_intro_circuit(router, service->pk_digest);
  257. if (circ && circ->purpose == CIRCUIT_PURPOSE_S_INTRO) {
  258. /* We have an entirely established intro circuit. */
  259. d->intro_points[d->n_intro_points++] = tor_strdup(router->nickname);
  260. }
  261. }
  262. }
  263. /** Load and/or generate private keys for all hidden services. Return 0 on
  264. * success, -1 on failure.
  265. */
  266. int rend_service_load_keys(void)
  267. {
  268. int i;
  269. rend_service_t *s;
  270. char fname[512];
  271. char buf[128];
  272. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  273. s = smartlist_get(rend_service_list,i);
  274. if (s->private_key)
  275. continue;
  276. log_fn(LOG_INFO, "Loading hidden-service keys from '%s'", s->directory);
  277. /* Check/create directory */
  278. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  279. return -1;
  280. /* Load key */
  281. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  282. strlcat(fname,"/private_key",sizeof(fname)) >= sizeof(fname)) {
  283. log_fn(LOG_WARN, "Directory name too long: '%s'", s->directory);
  284. return -1;
  285. }
  286. s->private_key = init_key_from_file(fname);
  287. if (!s->private_key)
  288. return -1;
  289. /* Create service file */
  290. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  291. log_fn(LOG_WARN, "Couldn't encode service ID");
  292. return -1;
  293. }
  294. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  295. log_fn(LOG_WARN, "Couldn't compute hash of public key");
  296. return -1;
  297. }
  298. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  299. strlcat(fname,"/hostname",sizeof(fname)) >= sizeof(fname)) {
  300. log_fn(LOG_WARN, "Directory name too long: '%s'", s->directory);
  301. return -1;
  302. }
  303. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  304. if (write_str_to_file(fname,buf,0)<0)
  305. return -1;
  306. }
  307. return 0;
  308. }
  309. /** Return the service whose public key has a digest of <b>digest</b>. Return
  310. * NULL if no such service exists.
  311. */
  312. static rend_service_t *
  313. rend_service_get_by_pk_digest(const char* digest)
  314. {
  315. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  316. if (!memcmp(s->pk_digest,digest,DIGEST_LEN)) return s);
  317. return NULL;
  318. }
  319. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  320. * to have good uptime. Else return 0.
  321. */
  322. static int
  323. rend_service_requires_uptime(rend_service_t *service) {
  324. int i;
  325. rend_service_port_config_t *p;
  326. for (i=0; i < smartlist_len(service->ports); ++i) {
  327. p = smartlist_get(service->ports, i);
  328. if (smartlist_string_num_isin(get_options()->LongLivedPorts, p->virtual_port))
  329. return 1;
  330. }
  331. return 0;
  332. }
  333. /******
  334. * Handle cells
  335. ******/
  336. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  337. * rendezvous point.
  338. */
  339. int
  340. rend_service_introduce(circuit_t *circuit, const char *request, size_t request_len)
  341. {
  342. char *ptr, *rp_nickname, *r_cookie;
  343. char buf[RELAY_PAYLOAD_SIZE];
  344. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  345. rend_service_t *service;
  346. int r, i;
  347. size_t len, keylen;
  348. crypto_dh_env_t *dh = NULL;
  349. circuit_t *launched = NULL;
  350. crypt_path_t *cpath = NULL;
  351. char serviceid[REND_SERVICE_ID_LEN+1];
  352. char hexcookie[9];
  353. int version;
  354. size_t nickname_field_len;
  355. int circ_needs_uptime;
  356. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  357. circuit->rend_pk_digest,10);
  358. log_fn(LOG_INFO, "Received INTRODUCE2 cell for service %s on circ %d",
  359. serviceid, circuit->n_circ_id);
  360. if (circuit->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  361. log_fn(LOG_WARN, "Got an INTRODUCE2 over a non-introduction circuit %d",
  362. circuit->n_circ_id);
  363. return -1;
  364. }
  365. /* min key length plus digest length plus nickname length */
  366. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  367. DH_KEY_LEN+42) {
  368. log_fn(LOG_WARN, "Got a truncated INTRODUCE2 cell on circ %d",
  369. circuit->n_circ_id);
  370. return -1;
  371. }
  372. /* first DIGEST_LEN bytes of request is service pk digest */
  373. service = rend_service_get_by_pk_digest(request);
  374. if (!service) {
  375. log_fn(LOG_WARN, "Got an INTRODUCE2 cell for an unrecognized service %s",
  376. serviceid);
  377. return -1;
  378. }
  379. if (memcmp(circuit->rend_pk_digest, request, DIGEST_LEN)) {
  380. base32_encode(serviceid, REND_SERVICE_ID_LEN+1, request, 10);
  381. log_fn(LOG_WARN, "Got an INTRODUCE2 cell for the wrong service (%s)",
  382. serviceid);
  383. return -1;
  384. }
  385. keylen = crypto_pk_keysize(service->private_key);
  386. if (request_len < keylen+DIGEST_LEN) {
  387. log_fn(LOG_WARN, "PK-encrypted portion of INTRODUCE2 cell was truncated");
  388. return -1;
  389. }
  390. /* Next N bytes is encrypted with service key */
  391. r = crypto_pk_private_hybrid_decrypt(
  392. service->private_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
  393. PK_PKCS1_OAEP_PADDING,1);
  394. if (r<0) {
  395. log_fn(LOG_WARN, "Couldn't decrypt INTRODUCE2 cell");
  396. return -1;
  397. }
  398. len = r;
  399. if (*buf == 1) {
  400. rp_nickname = buf+1;
  401. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  402. version = 1;
  403. } else {
  404. nickname_field_len = MAX_NICKNAME_LEN+1;
  405. rp_nickname = buf;
  406. version = 0;
  407. }
  408. /* XXX when 0.0.9.x is obsolete, change this to reject version != 1. */
  409. ptr=memchr(rp_nickname,0,nickname_field_len);
  410. if (!ptr || ptr == rp_nickname) {
  411. log_fn(LOG_WARN, "Couldn't find a null-padded nickname in INTRODUCE2 cell");
  412. return -1;
  413. }
  414. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  415. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  416. log_fn(LOG_WARN, "Bad nickname in INTRODUCE2 cell.");
  417. return -1;
  418. }
  419. /* Okay, now we know that a nickname is at the start of the buffer. */
  420. ptr = rp_nickname+nickname_field_len;
  421. len -= nickname_field_len;
  422. len -= rp_nickname - buf; /* also remove header space used by version, if any */
  423. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  424. log_fn(LOG_WARN, "Bad length %u for INTRODUCE2 cell.", (int)len);
  425. return -1;
  426. }
  427. r_cookie = ptr;
  428. base16_encode(hexcookie,9,r_cookie,4);
  429. /* Try DH handshake... */
  430. dh = crypto_dh_new();
  431. if (!dh || crypto_dh_generate_public(dh)<0) {
  432. log_fn(LOG_WARN, "Couldn't build DH state or generate public key");
  433. goto err;
  434. }
  435. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  436. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  437. log_fn(LOG_WARN, "Couldn't complete DH handshake");
  438. goto err;
  439. }
  440. circ_needs_uptime = rend_service_requires_uptime(service);
  441. /* help predict this next time */
  442. rep_hist_note_used_hidserv(time(NULL), circ_needs_uptime, 1);
  443. /* Launch a circuit to alice's chosen rendezvous point.
  444. */
  445. for (i=0;i<MAX_REND_FAILURES;i++) {
  446. launched = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_CONNECT_REND, rp_nickname,
  447. circ_needs_uptime, 1, 1);
  448. if (launched)
  449. break;
  450. }
  451. if (!launched) { /* give up */
  452. log_fn(LOG_WARN,"Giving up launching first hop of circuit to rendezvous point '%s' for service %s",
  453. rp_nickname, serviceid);
  454. goto err;
  455. }
  456. log_fn(LOG_INFO,
  457. "Accepted intro; launching circuit to '%s' (cookie %s) for service %s",
  458. rp_nickname, hexcookie, serviceid);
  459. tor_assert(launched->build_state);
  460. /* Fill in the circuit's state. */
  461. memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
  462. DIGEST_LEN);
  463. memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
  464. strlcpy(launched->rend_query, service->service_id,
  465. sizeof(launched->rend_query));
  466. launched->build_state->pending_final_cpath = cpath =
  467. tor_malloc_zero(sizeof(crypt_path_t));
  468. cpath->handshake_state = dh;
  469. dh = NULL;
  470. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  471. goto err;
  472. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  473. return 0;
  474. err:
  475. if (dh) crypto_dh_free(dh);
  476. if (launched) circuit_mark_for_close(launched);
  477. return -1;
  478. }
  479. /** Called when we fail building a rendezvous circuit at some point other
  480. * than the last hop: launches a new circuit to the same rendezvous point.
  481. */
  482. void
  483. rend_service_relaunch_rendezvous(circuit_t *oldcirc)
  484. {
  485. circuit_t *newcirc;
  486. cpath_build_state_t *newstate, *oldstate;
  487. tor_assert(oldcirc->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  488. if (!oldcirc->build_state ||
  489. oldcirc->build_state->failure_count > MAX_REND_FAILURES) {
  490. log_fn(LOG_INFO,"Attempt to build circuit to %s for rendezvous has failed too many times; giving up.",
  491. oldcirc->build_state->chosen_exit_name);
  492. return;
  493. }
  494. oldstate = oldcirc->build_state;
  495. tor_assert(oldstate);
  496. if (oldstate->pending_final_cpath == NULL) {
  497. log_fn(LOG_INFO,"Skipping relaunch of circ that failed on its first hop. Initiator will retry.");
  498. return;
  499. }
  500. log_fn(LOG_INFO,"Reattempting rendezvous circuit to %s",
  501. oldstate->chosen_exit_name);
  502. newcirc = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_CONNECT_REND,
  503. oldstate->chosen_exit_name, 0, 1, 1);
  504. if (!newcirc) {
  505. log_fn(LOG_WARN,"Couldn't relaunch rendezvous circuit to %s",
  506. oldstate->chosen_exit_name);
  507. return;
  508. }
  509. newstate = newcirc->build_state;
  510. tor_assert(newstate);
  511. newstate->failure_count = oldstate->failure_count+1;
  512. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  513. oldstate->pending_final_cpath = NULL;
  514. memcpy(newcirc->rend_query, oldcirc->rend_query, REND_SERVICE_ID_LEN+1);
  515. memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest, DIGEST_LEN);
  516. memcpy(newcirc->rend_cookie, oldcirc->rend_cookie, REND_COOKIE_LEN);
  517. }
  518. /** Launch a circuit to serve as an introduction point for the service
  519. * <b>service</b> at the introduction point <b>nickname</b>
  520. */
  521. static int
  522. rend_service_launch_establish_intro(rend_service_t *service, const char *nickname)
  523. {
  524. circuit_t *launched;
  525. log_fn(LOG_INFO, "Launching circuit to introduction point %s for service %s",
  526. nickname, service->service_id);
  527. rep_hist_note_used_hidserv(time(NULL), 1, 0);
  528. ++service->n_intro_circuits_launched;
  529. launched = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, nickname, 1, 0, 1);
  530. if (!launched) {
  531. log_fn(LOG_WARN, "Can't launch circuit to establish introduction at '%s'",
  532. nickname);
  533. return -1;
  534. }
  535. strlcpy(launched->rend_query, service->service_id,
  536. sizeof(launched->rend_query));
  537. memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  538. return 0;
  539. }
  540. /** Called when we're done building a circuit to an introduction point:
  541. * sends a RELAY_ESTABLISH_INTRO cell.
  542. */
  543. void
  544. rend_service_intro_has_opened(circuit_t *circuit)
  545. {
  546. rend_service_t *service;
  547. size_t len;
  548. int r;
  549. char buf[RELAY_PAYLOAD_SIZE];
  550. char auth[DIGEST_LEN + 9];
  551. char serviceid[REND_SERVICE_ID_LEN+1];
  552. tor_assert(circuit->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  553. tor_assert(CIRCUIT_IS_ORIGIN(circuit));
  554. tor_assert(circuit->cpath);
  555. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  556. circuit->rend_pk_digest,10);
  557. service = rend_service_get_by_pk_digest(circuit->rend_pk_digest);
  558. if (!service) {
  559. log_fn(LOG_WARN, "Unrecognized service ID %s on introduction circuit %d",
  560. serviceid, circuit->n_circ_id);
  561. goto err;
  562. }
  563. log_fn(LOG_INFO,
  564. "Established circuit %d as introduction point for service %s",
  565. circuit->n_circ_id, serviceid);
  566. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  567. len = crypto_pk_asn1_encode(service->private_key, buf+2,
  568. RELAY_PAYLOAD_SIZE-2);
  569. set_uint16(buf, htons((uint16_t)len));
  570. len += 2;
  571. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  572. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  573. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  574. goto err;
  575. len += 20;
  576. r = crypto_pk_private_sign_digest(service->private_key, buf+len, buf, len);
  577. if (r<0) {
  578. log_fn(LOG_WARN, "Couldn't sign introduction request");
  579. goto err;
  580. }
  581. len += r;
  582. if (connection_edge_send_command(NULL, circuit,RELAY_COMMAND_ESTABLISH_INTRO,
  583. buf, len, circuit->cpath->prev)<0) {
  584. log_fn(LOG_WARN,
  585. "Couldn't send introduction request for service %s on circuit %d",
  586. serviceid, circuit->n_circ_id);
  587. goto err;
  588. }
  589. return;
  590. err:
  591. circuit_mark_for_close(circuit);
  592. }
  593. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  594. * live introduction point, and note that the service descriptor is
  595. * now out-of-date.*/
  596. int
  597. rend_service_intro_established(circuit_t *circuit, const char *request, size_t request_len)
  598. {
  599. rend_service_t *service;
  600. if (circuit->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  601. log_fn(LOG_WARN, "received INTRO_ESTABLISHED cell on non-intro circuit");
  602. goto err;
  603. }
  604. service = rend_service_get_by_pk_digest(circuit->rend_pk_digest);
  605. if (!service) {
  606. log_fn(LOG_WARN, "Unknown service on introduction circuit %d",
  607. circuit->n_circ_id);
  608. goto err;
  609. }
  610. service->desc_is_dirty = time(NULL);
  611. circuit->purpose = CIRCUIT_PURPOSE_S_INTRO;
  612. return 0;
  613. err:
  614. circuit_mark_for_close(circuit);
  615. return -1;
  616. }
  617. /** Called once a circuit to a rendezvous point is established: sends a
  618. * RELAY_COMMAND_RENDEZVOUS1 cell.
  619. */
  620. void
  621. rend_service_rendezvous_has_opened(circuit_t *circuit)
  622. {
  623. rend_service_t *service;
  624. char buf[RELAY_PAYLOAD_SIZE];
  625. crypt_path_t *hop;
  626. char serviceid[REND_SERVICE_ID_LEN+1];
  627. char hexcookie[9];
  628. tor_assert(circuit->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  629. tor_assert(circuit->cpath);
  630. tor_assert(circuit->build_state);
  631. hop = circuit->build_state->pending_final_cpath;
  632. tor_assert(hop);
  633. base16_encode(hexcookie,9,circuit->rend_cookie,4);
  634. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  635. circuit->rend_pk_digest,10);
  636. log_fn(LOG_INFO,
  637. "Done building circuit %d to rendezvous with cookie %s for service %s",
  638. circuit->n_circ_id, hexcookie, serviceid);
  639. service = rend_service_get_by_pk_digest(circuit->rend_pk_digest);
  640. if (!service) {
  641. log_fn(LOG_WARN, "Internal error: unrecognized service ID on introduction circuit");
  642. goto err;
  643. }
  644. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  645. memcpy(buf, circuit->rend_cookie, REND_COOKIE_LEN);
  646. if (crypto_dh_get_public(hop->handshake_state,
  647. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  648. log_fn(LOG_WARN,"Couldn't get DH public key");
  649. goto err;
  650. }
  651. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  652. DIGEST_LEN);
  653. /* Send the cell */
  654. if (connection_edge_send_command(NULL, circuit, RELAY_COMMAND_RENDEZVOUS1,
  655. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  656. circuit->cpath->prev)<0) {
  657. log_fn(LOG_WARN, "Couldn't send RENDEZVOUS1 cell");
  658. goto err;
  659. }
  660. crypto_dh_free(hop->handshake_state);
  661. hop->handshake_state = NULL;
  662. /* Append the cpath entry. */
  663. hop->state = CPATH_STATE_OPEN;
  664. /* set the windows to default. these are the windows
  665. * that bob thinks alice has.
  666. */
  667. hop->package_window = CIRCWINDOW_START;
  668. hop->deliver_window = CIRCWINDOW_START;
  669. onion_append_to_cpath(&circuit->cpath, hop);
  670. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  671. /* Change the circuit purpose. */
  672. circuit->purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  673. return;
  674. err:
  675. circuit_mark_for_close(circuit);
  676. }
  677. /*
  678. * Manage introduction points
  679. */
  680. /** Return the (possibly non-open) introduction circuit ending at
  681. * <b>router</b> for the service whose public key is <b>pk_digest</b>. Return
  682. * NULL if no such service is found.
  683. */
  684. static circuit_t *
  685. find_intro_circuit(routerinfo_t *router, const char *pk_digest)
  686. {
  687. circuit_t *circ = NULL;
  688. tor_assert(router);
  689. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  690. CIRCUIT_PURPOSE_S_INTRO))) {
  691. tor_assert(circ->cpath);
  692. if (circ->build_state->chosen_exit_name &&
  693. !strcasecmp(circ->build_state->chosen_exit_name, router->nickname)) {
  694. return circ;
  695. }
  696. }
  697. circ = NULL;
  698. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  699. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  700. tor_assert(circ->cpath);
  701. if (circ->build_state->chosen_exit_name &&
  702. !strcasecmp(circ->build_state->chosen_exit_name, router->nickname)) {
  703. return circ;
  704. }
  705. }
  706. return NULL;
  707. }
  708. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  709. * and upload it to all the dirservers.
  710. */
  711. static void
  712. upload_service_descriptor(rend_service_t *service)
  713. {
  714. char *desc;
  715. size_t desc_len;
  716. /* Update the descriptor. */
  717. rend_service_update_descriptor(service);
  718. if (rend_encode_service_descriptor(service->desc,
  719. service->private_key,
  720. &desc, &desc_len)<0) {
  721. log_fn(LOG_WARN, "Couldn't encode service descriptor; not uploading");
  722. return;
  723. }
  724. /* Post it to the dirservers */
  725. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC, desc, desc_len);
  726. tor_free(desc);
  727. service->desc_is_dirty = 0;
  728. }
  729. /* XXXX Make this longer once directories remember service descriptors across
  730. * restarts.*/
  731. #define MAX_SERVICE_PUBLICATION_INTERVAL (15*60)
  732. /** For every service, check how many intro points it currently has, and:
  733. * - Pick new intro points as necessary.
  734. * - Launch circuits to any new intro points.
  735. */
  736. void rend_services_introduce(void) {
  737. int i,j,r;
  738. routerinfo_t *router;
  739. rend_service_t *service;
  740. char *intro;
  741. int changed, prev_intro_nodes;
  742. smartlist_t *intro_routers, *exclude_routers;
  743. time_t now;
  744. intro_routers = smartlist_create();
  745. exclude_routers = smartlist_create();
  746. now = time(NULL);
  747. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  748. smartlist_clear(intro_routers);
  749. service = smartlist_get(rend_service_list, i);
  750. tor_assert(service);
  751. changed = 0;
  752. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  753. /* One period has elapsed; we can try building circuits again. */
  754. service->intro_period_started = now;
  755. service->n_intro_circuits_launched = 0;
  756. } else if (service->n_intro_circuits_launched >=
  757. MAX_INTRO_CIRCS_PER_PERIOD) {
  758. /* We have failed too many times in this period; wait for the next
  759. * one before we try again. */
  760. continue;
  761. }
  762. /* Find out which introduction points we have in progress for this service. */
  763. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  764. intro = smartlist_get(service->intro_nodes, j);
  765. router = router_get_by_nickname(intro);
  766. if (!router || !find_intro_circuit(router,service->pk_digest)) {
  767. log_fn(LOG_INFO,"Giving up on %s as intro point for %s.",
  768. intro, service->service_id);
  769. tor_free(intro);
  770. smartlist_del(service->intro_nodes,j--);
  771. changed = 1;
  772. service->desc_is_dirty = now;
  773. }
  774. smartlist_add(intro_routers, router);
  775. }
  776. /* We have enough intro points, and the intro points we thought we had were
  777. * all connected.
  778. */
  779. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  780. /* We have all our intro points! Start a fresh period and reset the
  781. * circuit count. */
  782. service->intro_period_started = now;
  783. service->n_intro_circuits_launched = 0;
  784. continue;
  785. }
  786. /* Remember how many introduction circuits we started with. */
  787. prev_intro_nodes = smartlist_len(service->intro_nodes);
  788. smartlist_add_all(exclude_routers, intro_routers);
  789. /* The directory is now here. Pick three ORs as intro points. */
  790. for (j=prev_intro_nodes; j < NUM_INTRO_POINTS; ++j) {
  791. router = router_choose_random_node(service->intro_prefer_nodes,
  792. service->intro_exclude_nodes, exclude_routers, 1, 0,
  793. get_options()->_AllowUnverified & ALLOW_UNVERIFIED_INTRODUCTION, 0);
  794. if (!router) {
  795. log_fn(LOG_WARN, "Could only establish %d introduction points for %s",
  796. smartlist_len(service->intro_nodes), service->service_id);
  797. break;
  798. }
  799. changed = 1;
  800. smartlist_add(intro_routers, router);
  801. smartlist_add(exclude_routers, router);
  802. /*XXX009 should strdup the hexdigest, not nickname */
  803. smartlist_add(service->intro_nodes, tor_strdup(router->nickname));
  804. log_fn(LOG_INFO,"Picked router %s as an intro point for %s.", router->nickname,
  805. service->service_id);
  806. }
  807. /* Reset exclude_routers, for the next time around the loop. */
  808. smartlist_clear(exclude_routers);
  809. /* If there's no need to launch new circuits, stop here. */
  810. if (!changed)
  811. continue;
  812. /* Establish new introduction points. */
  813. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  814. intro = smartlist_get(service->intro_nodes, j);
  815. r = rend_service_launch_establish_intro(service, intro);
  816. if (r<0) {
  817. log_fn(LOG_WARN, "Error launching circuit to node %s for service %s",
  818. intro, service->service_id);
  819. }
  820. }
  821. }
  822. smartlist_free(intro_routers);
  823. smartlist_free(exclude_routers);
  824. }
  825. /** Regenerate and upload rendezvous service descriptors for all
  826. * services, if necessary. If the descriptor has been dirty enough
  827. * for long enough, definitely upload; else only upload when the
  828. * periodic timeout has expired.
  829. *
  830. * For the first upload, pick a random time between now and two periods
  831. * from now, and pick it independently for each service.
  832. */
  833. void
  834. rend_consider_services_upload(time_t now) {
  835. int i;
  836. rend_service_t *service;
  837. int rendpostperiod = get_options()->RendPostPeriod;
  838. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  839. service = smartlist_get(rend_service_list, i);
  840. if (!service->next_upload_time) { /* never been uploaded yet */
  841. service->next_upload_time =
  842. now + crypto_pseudo_rand_int(2*rendpostperiod);
  843. }
  844. if (service->next_upload_time < now ||
  845. (service->desc_is_dirty &&
  846. service->desc_is_dirty < now-5)) {
  847. /* if it's time, or if the directory servers have a wrong service
  848. * descriptor and ours has been stable for 5 seconds, upload a
  849. * new one. */
  850. upload_service_descriptor(service);
  851. service->next_upload_time = now + rendpostperiod;
  852. }
  853. }
  854. }
  855. /** Log the status of introduction points for all rendezvous services
  856. * at log severity <b>severity</b>.
  857. */
  858. void
  859. rend_service_dump_stats(int severity)
  860. {
  861. int i,j;
  862. routerinfo_t *router;
  863. rend_service_t *service;
  864. char *nickname;
  865. circuit_t *circ;
  866. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  867. service = smartlist_get(rend_service_list, i);
  868. log(severity, "Service configured in %s:", service->directory);
  869. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  870. nickname = smartlist_get(service->intro_nodes, j);
  871. router = router_get_by_nickname(smartlist_get(service->intro_nodes,j));
  872. if (!router) {
  873. log(severity, " Intro point at %s: unrecognized router",nickname);
  874. continue;
  875. }
  876. circ = find_intro_circuit(router, service->pk_digest);
  877. if (!circ) {
  878. log(severity, " Intro point at %s: no circuit",nickname);
  879. continue;
  880. }
  881. log(severity, " Intro point at %s: circuit is %s",nickname,
  882. circuit_state_to_string[circ->state]);
  883. }
  884. }
  885. }
  886. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  887. * 'circ', and look up the port and address based on conn-\>port.
  888. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  889. * or 0 for success.
  890. */
  891. int
  892. rend_service_set_connection_addr_port(connection_t *conn, circuit_t *circ)
  893. {
  894. rend_service_t *service;
  895. int i;
  896. rend_service_port_config_t *p;
  897. char serviceid[REND_SERVICE_ID_LEN+1];
  898. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  899. log_fn(LOG_DEBUG,"beginning to hunt for addr/port");
  900. base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
  901. circ->rend_pk_digest,10);
  902. service = rend_service_get_by_pk_digest(circ->rend_pk_digest);
  903. if (!service) {
  904. log_fn(LOG_WARN, "Couldn't find any service associated with pk %s on rendezvous circuit %d; closing",
  905. serviceid, circ->n_circ_id);
  906. return -1;
  907. }
  908. for (i = 0; i < smartlist_len(service->ports); ++i) {
  909. p = smartlist_get(service->ports, i);
  910. if (conn->port == p->virtual_port) {
  911. conn->addr = p->real_address;
  912. conn->port = p->real_port;
  913. return 0;
  914. }
  915. }
  916. log_fn(LOG_INFO, "No virtual port mapping exists for port %d on service %s",
  917. conn->port,serviceid);
  918. return -1;
  919. }