rendservice.c 36 KB

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