rendservice.c 36 KB

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