rendservice.c 33 KB

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