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