rendservice.c 37 KB

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