rendservice.c 35 KB

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