rendservice.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2009, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendservice.c
  6. * \brief The hidden-service side of rendezvous functionality.
  7. **/
  8. #include "or.h"
  9. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  10. 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. tor_addr_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. rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
  38. * authorization is performed. */
  39. smartlist_t *clients; /**< List of rend_authorized_client_t's of
  40. * clients that may access our service. Can be NULL
  41. * if no client authorization is performed. */
  42. /* Other fields */
  43. crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
  44. char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
  45. * '.onion' */
  46. char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
  47. smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
  48. * or are trying to establish. */
  49. time_t intro_period_started; /**< Start of the current period to build
  50. * introduction points. */
  51. int n_intro_circuits_launched; /**< Count of intro circuits we have
  52. * established in this period. */
  53. rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  54. time_t desc_is_dirty; /**< Time at which changes to the hidden service
  55. * descriptor content occurred, or 0 if it's
  56. * up-to-date. */
  57. time_t next_upload_time; /**< Scheduled next hidden service descriptor
  58. * upload time. */
  59. /** Map from digests of Diffie-Hellman values INTRODUCE2 to time_t of when
  60. * they were received; used to prevent replays. */
  61. digestmap_t *accepted_intros;
  62. /** Time at which we last removed expired values from accepted_intros. */
  63. time_t last_cleaned_accepted_intros;
  64. } rend_service_t;
  65. /** A list of rend_service_t's for services run on this OP.
  66. */
  67. static smartlist_t *rend_service_list = NULL;
  68. /** Return the number of rendezvous services we have configured. */
  69. int
  70. num_rend_services(void)
  71. {
  72. if (!rend_service_list)
  73. return 0;
  74. return smartlist_len(rend_service_list);
  75. }
  76. /** Helper: free storage held by a single service authorized client entry. */
  77. static void
  78. rend_authorized_client_free(rend_authorized_client_t *client)
  79. {
  80. if (!client) return;
  81. if (client->client_key)
  82. crypto_free_pk_env(client->client_key);
  83. tor_free(client->client_name);
  84. tor_free(client);
  85. }
  86. /** Helper for strmap_free. */
  87. static void
  88. rend_authorized_client_strmap_item_free(void *authorized_client)
  89. {
  90. rend_authorized_client_free(authorized_client);
  91. }
  92. /** Release the storage held by <b>service</b>.
  93. */
  94. static void
  95. rend_service_free(rend_service_t *service)
  96. {
  97. if (!service) return;
  98. tor_free(service->directory);
  99. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  100. smartlist_free(service->ports);
  101. if (service->private_key)
  102. crypto_free_pk_env(service->private_key);
  103. if (service->intro_nodes) {
  104. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  105. rend_intro_point_free(intro););
  106. smartlist_free(service->intro_nodes);
  107. }
  108. if (service->desc)
  109. rend_service_descriptor_free(service->desc);
  110. if (service->clients) {
  111. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  112. rend_authorized_client_free(c););
  113. smartlist_free(service->clients);
  114. }
  115. if (service->accepted_intros)
  116. digestmap_free(service->accepted_intros, _tor_free);
  117. tor_free(service);
  118. }
  119. /** Release all the storage held in rend_service_list.
  120. */
  121. void
  122. rend_service_free_all(void)
  123. {
  124. if (!rend_service_list) {
  125. return;
  126. }
  127. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  128. rend_service_free(ptr));
  129. smartlist_free(rend_service_list);
  130. rend_service_list = NULL;
  131. }
  132. /** Validate <b>service</b> and add it to rend_service_list if possible.
  133. */
  134. static void
  135. rend_add_service(rend_service_t *service)
  136. {
  137. int i;
  138. rend_service_port_config_t *p;
  139. service->intro_nodes = smartlist_create();
  140. if (service->auth_type != REND_NO_AUTH &&
  141. smartlist_len(service->clients) == 0) {
  142. log_warn(LD_CONFIG, "Hidden service with client authorization but no "
  143. "clients; ignoring.");
  144. rend_service_free(service);
  145. return;
  146. }
  147. if (!smartlist_len(service->ports)) {
  148. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  149. rend_service_free(service);
  150. } else {
  151. smartlist_add(rend_service_list, service);
  152. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  153. service->directory);
  154. for (i = 0; i < smartlist_len(service->ports); ++i) {
  155. p = smartlist_get(service->ports, i);
  156. log_debug(LD_REND,"Service maps port %d to %s:%d",
  157. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  158. }
  159. }
  160. }
  161. /** Parses a real-port to virtual-port mapping and returns a new
  162. * rend_service_port_config_t.
  163. *
  164. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  165. *
  166. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  167. */
  168. static rend_service_port_config_t *
  169. parse_port_config(const char *string)
  170. {
  171. smartlist_t *sl;
  172. int virtport;
  173. int realport;
  174. uint16_t p;
  175. tor_addr_t addr;
  176. const char *addrport;
  177. rend_service_port_config_t *result = NULL;
  178. sl = smartlist_create();
  179. smartlist_split_string(sl, string, " ",
  180. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  181. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  182. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  183. goto err;
  184. }
  185. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  186. if (!virtport) {
  187. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  188. "configuration", escaped(smartlist_get(sl,0)));
  189. goto err;
  190. }
  191. if (smartlist_len(sl) == 1) {
  192. /* No addr:port part; use default. */
  193. realport = virtport;
  194. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  195. } else {
  196. addrport = smartlist_get(sl,1);
  197. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  198. if (tor_addr_port_parse(addrport, &addr, &p)<0) {
  199. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  200. "configuration.");
  201. goto err;
  202. }
  203. realport = p?p:virtport;
  204. } else {
  205. /* No addr:port, no addr -- must be port. */
  206. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  207. if (!realport) {
  208. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  209. "service port configuration.", escaped(addrport));
  210. goto err;
  211. }
  212. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  213. }
  214. }
  215. result = tor_malloc(sizeof(rend_service_port_config_t));
  216. result->virtual_port = virtport;
  217. result->real_port = realport;
  218. tor_addr_copy(&result->real_addr, &addr);
  219. err:
  220. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  221. smartlist_free(sl);
  222. return result;
  223. }
  224. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  225. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  226. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  227. * normal, but don't actually change the configured services.)
  228. */
  229. int
  230. rend_config_services(or_options_t *options, int validate_only)
  231. {
  232. config_line_t *line;
  233. rend_service_t *service = NULL;
  234. rend_service_port_config_t *portcfg;
  235. smartlist_t *old_service_list = NULL;
  236. if (!validate_only) {
  237. old_service_list = rend_service_list;
  238. rend_service_list = smartlist_create();
  239. }
  240. for (line = options->RendConfigLines; line; line = line->next) {
  241. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  242. if (service) { /* register the one we just finished parsing */
  243. if (validate_only)
  244. rend_service_free(service);
  245. else
  246. rend_add_service(service);
  247. }
  248. service = tor_malloc_zero(sizeof(rend_service_t));
  249. service->directory = tor_strdup(line->value);
  250. service->ports = smartlist_create();
  251. service->intro_period_started = time(NULL);
  252. continue;
  253. }
  254. if (!service) {
  255. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  256. line->key);
  257. rend_service_free(service);
  258. return -1;
  259. }
  260. if (!strcasecmp(line->key, "HiddenServicePort")) {
  261. portcfg = parse_port_config(line->value);
  262. if (!portcfg) {
  263. rend_service_free(service);
  264. return -1;
  265. }
  266. smartlist_add(service->ports, portcfg);
  267. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  268. /* Parse auth type and comma-separated list of client names and add a
  269. * rend_authorized_client_t for each client to the service's list
  270. * of authorized clients. */
  271. smartlist_t *type_names_split, *clients;
  272. const char *authname;
  273. int num_clients;
  274. if (service->auth_type != REND_NO_AUTH) {
  275. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  276. "lines for a single service.");
  277. rend_service_free(service);
  278. return -1;
  279. }
  280. type_names_split = smartlist_create();
  281. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  282. if (smartlist_len(type_names_split) < 1) {
  283. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  284. "should have been prevented when parsing the "
  285. "configuration.");
  286. smartlist_free(type_names_split);
  287. rend_service_free(service);
  288. return -1;
  289. }
  290. authname = smartlist_get(type_names_split, 0);
  291. if (!strcasecmp(authname, "basic")) {
  292. service->auth_type = REND_BASIC_AUTH;
  293. } else if (!strcasecmp(authname, "stealth")) {
  294. service->auth_type = REND_STEALTH_AUTH;
  295. } else {
  296. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  297. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  298. "are recognized.",
  299. (char *) smartlist_get(type_names_split, 0));
  300. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  301. smartlist_free(type_names_split);
  302. rend_service_free(service);
  303. return -1;
  304. }
  305. service->clients = smartlist_create();
  306. if (smartlist_len(type_names_split) < 2) {
  307. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  308. "auth-type '%s', but no client names.",
  309. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  310. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  311. smartlist_free(type_names_split);
  312. continue;
  313. }
  314. clients = smartlist_create();
  315. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  316. ",", SPLIT_SKIP_SPACE, 0);
  317. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  318. smartlist_free(type_names_split);
  319. /* Remove duplicate client names. */
  320. num_clients = smartlist_len(clients);
  321. smartlist_sort_strings(clients);
  322. smartlist_uniq_strings(clients);
  323. if (smartlist_len(clients) < num_clients) {
  324. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  325. "duplicate client name(s); removing.",
  326. num_clients - smartlist_len(clients));
  327. num_clients = smartlist_len(clients);
  328. }
  329. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  330. {
  331. rend_authorized_client_t *client;
  332. size_t len = strlen(client_name);
  333. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  334. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  335. "illegal client name: '%s'. Length must be "
  336. "between 1 and %d characters.",
  337. client_name, REND_CLIENTNAME_MAX_LEN);
  338. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  339. smartlist_free(clients);
  340. rend_service_free(service);
  341. return -1;
  342. }
  343. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  344. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  345. "illegal client name: '%s'. Valid "
  346. "characters are [A-Za-z0-9+-_].",
  347. client_name);
  348. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  349. smartlist_free(clients);
  350. rend_service_free(service);
  351. return -1;
  352. }
  353. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  354. client->client_name = tor_strdup(client_name);
  355. smartlist_add(service->clients, client);
  356. log_debug(LD_REND, "Adding client name '%s'", client_name);
  357. }
  358. SMARTLIST_FOREACH_END(client_name);
  359. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  360. smartlist_free(clients);
  361. /* Ensure maximum number of clients. */
  362. if ((service->auth_type == REND_BASIC_AUTH &&
  363. smartlist_len(service->clients) > 512) ||
  364. (service->auth_type == REND_STEALTH_AUTH &&
  365. smartlist_len(service->clients) > 16)) {
  366. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  367. "client authorization entries, but only a "
  368. "maximum of %d entries is allowed for "
  369. "authorization type '%s'.",
  370. smartlist_len(service->clients),
  371. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  372. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  373. rend_service_free(service);
  374. return -1;
  375. }
  376. } else {
  377. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  378. if (strcmp(line->value, "2")) {
  379. log_warn(LD_CONFIG,
  380. "The only supported HiddenServiceVersion is 2.");
  381. rend_service_free(service);
  382. return -1;
  383. }
  384. }
  385. }
  386. if (service) {
  387. if (validate_only)
  388. rend_service_free(service);
  389. else
  390. rend_add_service(service);
  391. }
  392. /* If this is a reload and there were hidden services configured before,
  393. * keep the introduction points that are still needed and close the
  394. * other ones. */
  395. if (old_service_list && !validate_only) {
  396. smartlist_t *surviving_services = smartlist_create();
  397. circuit_t *circ;
  398. /* Copy introduction points to new services. */
  399. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  400. * probably ok? */
  401. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
  402. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  403. if (!strcmp(old->directory, new->directory)) {
  404. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  405. smartlist_clear(old->intro_nodes);
  406. smartlist_add(surviving_services, old);
  407. break;
  408. }
  409. });
  410. });
  411. /* Close introduction circuits of services we don't serve anymore. */
  412. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  413. * so we could just iterate over the list of services to close, but
  414. * once again, this isn't critical-path code. */
  415. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  416. if (!circ->marked_for_close &&
  417. circ->state == CIRCUIT_STATE_OPEN &&
  418. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  419. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  420. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  421. int keep_it = 0;
  422. tor_assert(oc->rend_data);
  423. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  424. if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  425. DIGEST_LEN)) {
  426. keep_it = 1;
  427. break;
  428. }
  429. });
  430. if (keep_it)
  431. continue;
  432. log_info(LD_REND, "Closing intro point %s for service %s.",
  433. safe_str(oc->build_state->chosen_exit->nickname),
  434. oc->rend_data->onion_address);
  435. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  436. /* XXXX Is there another reason we should use here? */
  437. }
  438. }
  439. smartlist_free(surviving_services);
  440. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  441. rend_service_free(ptr));
  442. smartlist_free(old_service_list);
  443. }
  444. return 0;
  445. }
  446. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  447. * the other fields in service.
  448. */
  449. static void
  450. rend_service_update_descriptor(rend_service_t *service)
  451. {
  452. rend_service_descriptor_t *d;
  453. origin_circuit_t *circ;
  454. int i;
  455. if (service->desc) {
  456. rend_service_descriptor_free(service->desc);
  457. service->desc = NULL;
  458. }
  459. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  460. d->pk = crypto_pk_dup_key(service->private_key);
  461. d->timestamp = time(NULL);
  462. d->intro_nodes = smartlist_create();
  463. /* Support intro protocols 2 and 3. */
  464. d->protocols = (1 << 2) + (1 << 3);
  465. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  466. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  467. rend_intro_point_t *intro_desc;
  468. circ = find_intro_circuit(intro_svc, service->pk_digest);
  469. if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
  470. continue;
  471. /* We have an entirely established intro circuit. */
  472. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  473. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  474. if (intro_svc->intro_key)
  475. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  476. smartlist_add(d->intro_nodes, intro_desc);
  477. }
  478. }
  479. /** Load and/or generate private keys for all hidden services, possibly
  480. * including keys for client authorization. Return 0 on success, -1 on
  481. * failure.
  482. */
  483. int
  484. rend_service_load_keys(void)
  485. {
  486. int r = 0;
  487. char fname[512];
  488. char buf[1500];
  489. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  490. if (s->private_key)
  491. continue;
  492. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  493. s->directory);
  494. /* Check/create directory */
  495. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  496. return -1;
  497. /* Load key */
  498. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  499. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  500. >= sizeof(fname)) {
  501. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  502. s->directory);
  503. return -1;
  504. }
  505. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  506. if (!s->private_key)
  507. return -1;
  508. /* Create service file */
  509. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  510. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  511. return -1;
  512. }
  513. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  514. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  515. return -1;
  516. }
  517. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  518. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  519. >= sizeof(fname)) {
  520. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  521. " \"%s\".", s->directory);
  522. return -1;
  523. }
  524. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  525. if (write_str_to_file(fname,buf,0)<0) {
  526. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  527. return -1;
  528. }
  529. /* If client authorization is configured, load or generate keys. */
  530. if (s->auth_type != REND_NO_AUTH) {
  531. char *client_keys_str = NULL;
  532. strmap_t *parsed_clients = strmap_new();
  533. char cfname[512];
  534. FILE *cfile, *hfile;
  535. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  536. /* Load client keys and descriptor cookies, if available. */
  537. if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
  538. s->directory)<0) {
  539. log_warn(LD_CONFIG, "Directory name too long to store client keys "
  540. "file: \"%s\".", s->directory);
  541. goto err;
  542. }
  543. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  544. if (client_keys_str) {
  545. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  546. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  547. "be parsed.");
  548. goto err;
  549. } else {
  550. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  551. strmap_size(parsed_clients));
  552. tor_free(client_keys_str);
  553. }
  554. }
  555. /* Prepare client_keys and hostname files. */
  556. if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
  557. 0600, &open_cfile))) {
  558. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  559. escaped(cfname));
  560. goto err;
  561. }
  562. if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
  563. 0600, &open_hfile))) {
  564. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
  565. goto err;
  566. }
  567. /* Either use loaded keys for configured clients or generate new
  568. * ones if a client is new. */
  569. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
  570. {
  571. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  572. char service_id[16+1];
  573. rend_authorized_client_t *parsed =
  574. strmap_get(parsed_clients, client->client_name);
  575. int written;
  576. size_t len;
  577. /* Copy descriptor cookie from parsed entry or create new one. */
  578. if (parsed) {
  579. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  580. REND_DESC_COOKIE_LEN);
  581. } else {
  582. crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  583. }
  584. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  585. client->descriptor_cookie,
  586. REND_DESC_COOKIE_LEN) < 0) {
  587. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  588. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  589. return -1;
  590. }
  591. /* Copy client key from parsed entry or create new one if required. */
  592. if (parsed && parsed->client_key) {
  593. client->client_key = crypto_pk_dup_key(parsed->client_key);
  594. } else if (s->auth_type == REND_STEALTH_AUTH) {
  595. /* Create private key for client. */
  596. crypto_pk_env_t *prkey = NULL;
  597. if (!(prkey = crypto_new_pk_env())) {
  598. log_warn(LD_BUG,"Error constructing client key");
  599. goto err;
  600. }
  601. if (crypto_pk_generate_key(prkey)) {
  602. log_warn(LD_BUG,"Error generating client key");
  603. crypto_free_pk_env(prkey);
  604. goto err;
  605. }
  606. if (crypto_pk_check_key(prkey) <= 0) {
  607. log_warn(LD_BUG,"Generated client key seems invalid");
  608. crypto_free_pk_env(prkey);
  609. goto err;
  610. }
  611. client->client_key = prkey;
  612. }
  613. /* Add entry to client_keys file. */
  614. desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
  615. written = tor_snprintf(buf, sizeof(buf),
  616. "client-name %s\ndescriptor-cookie %s\n",
  617. client->client_name, desc_cook_out);
  618. if (written < 0) {
  619. log_warn(LD_BUG, "Could not write client entry.");
  620. goto err;
  621. }
  622. if (client->client_key) {
  623. char *client_key_out = NULL;
  624. crypto_pk_write_private_key_to_string(client->client_key,
  625. &client_key_out, &len);
  626. if (rend_get_service_id(client->client_key, service_id)<0) {
  627. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  628. tor_free(client_key_out);
  629. goto err;
  630. }
  631. written = tor_snprintf(buf + written, sizeof(buf) - written,
  632. "client-key\n%s", client_key_out);
  633. tor_free(client_key_out);
  634. if (written < 0) {
  635. log_warn(LD_BUG, "Could not write client entry.");
  636. goto err;
  637. }
  638. }
  639. if (fputs(buf, cfile) < 0) {
  640. log_warn(LD_FS, "Could not append client entry to file: %s",
  641. strerror(errno));
  642. goto err;
  643. }
  644. /* Add line to hostname file. */
  645. if (s->auth_type == REND_BASIC_AUTH) {
  646. /* Remove == signs (newline has been removed above). */
  647. desc_cook_out[strlen(desc_cook_out)-2] = '\0';
  648. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  649. s->service_id, desc_cook_out, client->client_name);
  650. } else {
  651. char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
  652. memcpy(extended_desc_cookie, client->descriptor_cookie,
  653. REND_DESC_COOKIE_LEN);
  654. extended_desc_cookie[REND_DESC_COOKIE_LEN] =
  655. ((int)s->auth_type - 1) << 4;
  656. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  657. extended_desc_cookie,
  658. REND_DESC_COOKIE_LEN+1) < 0) {
  659. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  660. goto err;
  661. }
  662. desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
  663. newline. */
  664. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  665. service_id, desc_cook_out, client->client_name);
  666. }
  667. if (fputs(buf, hfile)<0) {
  668. log_warn(LD_FS, "Could not append host entry to file: %s",
  669. strerror(errno));
  670. goto err;
  671. }
  672. }
  673. SMARTLIST_FOREACH_END(client);
  674. goto done;
  675. err:
  676. r = -1;
  677. done:
  678. tor_free(client_keys_str);
  679. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  680. if (r<0) {
  681. if (open_cfile)
  682. abort_writing_to_file(open_cfile);
  683. if (open_hfile)
  684. abort_writing_to_file(open_hfile);
  685. return r;
  686. } else {
  687. finish_writing_to_file(open_cfile);
  688. finish_writing_to_file(open_hfile);
  689. }
  690. }
  691. } SMARTLIST_FOREACH_END(s);
  692. return r;
  693. }
  694. /** Return the service whose public key has a digest of <b>digest</b>, or
  695. * NULL if no such service exists.
  696. */
  697. static rend_service_t *
  698. rend_service_get_by_pk_digest(const char* digest)
  699. {
  700. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  701. if (!memcmp(s->pk_digest,digest,DIGEST_LEN))
  702. return s);
  703. return NULL;
  704. }
  705. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  706. * to have good uptime. Else return 0.
  707. */
  708. static int
  709. rend_service_requires_uptime(rend_service_t *service)
  710. {
  711. int i;
  712. rend_service_port_config_t *p;
  713. for (i=0; i < smartlist_len(service->ports); ++i) {
  714. p = smartlist_get(service->ports, i);
  715. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  716. p->virtual_port))
  717. return 1;
  718. }
  719. return 0;
  720. }
  721. /** Check client authorization of a given <b>descriptor_cookie</b> for
  722. * <b>service</b>. Return 1 for success and 0 for failure. */
  723. static int
  724. rend_check_authorization(rend_service_t *service,
  725. const char *descriptor_cookie)
  726. {
  727. rend_authorized_client_t *auth_client = NULL;
  728. tor_assert(service);
  729. tor_assert(descriptor_cookie);
  730. if (!service->clients) {
  731. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  732. "authorized clients configured.");
  733. return 0;
  734. }
  735. /* Look up client authorization by descriptor cookie. */
  736. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  737. if (!memcmp(client->descriptor_cookie, descriptor_cookie,
  738. REND_DESC_COOKIE_LEN)) {
  739. auth_client = client;
  740. break;
  741. }
  742. });
  743. if (!auth_client) {
  744. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  745. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  746. descriptor_cookie, REND_DESC_COOKIE_LEN);
  747. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  748. "Dropping cell!",
  749. descriptor_cookie_base64);
  750. return 0;
  751. }
  752. /* Allow the request. */
  753. log_debug(LD_REND, "Client %s authorized for service %s.",
  754. auth_client->client_name, service->service_id);
  755. return 1;
  756. }
  757. /** Remove elements from <b>service</b>'s replay cache that are old enough to
  758. * be noticed by timestamp checking. */
  759. static void
  760. clean_accepted_intros(rend_service_t *service, time_t now)
  761. {
  762. const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
  763. service->last_cleaned_accepted_intros = now;
  764. if (!service->accepted_intros)
  765. return;
  766. DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
  767. if (*t < cutoff) {
  768. tor_free(t);
  769. MAP_DEL_CURRENT(digest);
  770. }
  771. } DIGESTMAP_FOREACH_END;
  772. }
  773. /******
  774. * Handle cells
  775. ******/
  776. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  777. * rendezvous point.
  778. */
  779. int
  780. rend_service_introduce(origin_circuit_t *circuit, const char *request,
  781. size_t request_len)
  782. {
  783. char *ptr, *r_cookie;
  784. extend_info_t *extend_info = NULL;
  785. char buf[RELAY_PAYLOAD_SIZE];
  786. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  787. rend_service_t *service;
  788. int r, i, v3_shift = 0;
  789. size_t len, keylen;
  790. crypto_dh_env_t *dh = NULL;
  791. origin_circuit_t *launched = NULL;
  792. crypt_path_t *cpath = NULL;
  793. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  794. char hexcookie[9];
  795. int circ_needs_uptime;
  796. int reason = END_CIRC_REASON_TORPROTOCOL;
  797. crypto_pk_env_t *intro_key;
  798. char intro_key_digest[DIGEST_LEN];
  799. int auth_type;
  800. size_t auth_len = 0;
  801. char auth_data[REND_DESC_COOKIE_LEN];
  802. crypto_digest_env_t *digest = NULL;
  803. time_t now = time(NULL);
  804. char diffie_hellman_hash[DIGEST_LEN];
  805. time_t *access_time;
  806. tor_assert(circuit->rend_data);
  807. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  808. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  809. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  810. escaped(serviceid), circuit->_base.n_circ_id);
  811. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  812. log_warn(LD_PROTOCOL,
  813. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  814. circuit->_base.n_circ_id);
  815. return -1;
  816. }
  817. /* min key length plus digest length plus nickname length */
  818. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  819. DH_KEY_LEN+42) {
  820. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  821. circuit->_base.n_circ_id);
  822. return -1;
  823. }
  824. /* look up service depending on circuit. */
  825. service = rend_service_get_by_pk_digest(
  826. circuit->rend_data->rend_pk_digest);
  827. if (!service) {
  828. log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
  829. escaped(serviceid));
  830. return -1;
  831. }
  832. /* use intro key instead of service key. */
  833. intro_key = circuit->intro_key;
  834. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  835. crypto_pk_get_digest(intro_key, intro_key_digest);
  836. if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
  837. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  838. request, REND_SERVICE_ID_LEN);
  839. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  840. escaped(serviceid));
  841. return -1;
  842. }
  843. keylen = crypto_pk_keysize(intro_key);
  844. if (request_len < keylen+DIGEST_LEN) {
  845. log_warn(LD_PROTOCOL,
  846. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  847. return -1;
  848. }
  849. /* Next N bytes is encrypted with service key */
  850. note_crypto_pk_op(REND_SERVER);
  851. r = crypto_pk_private_hybrid_decrypt(
  852. intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
  853. PK_PKCS1_OAEP_PADDING,1);
  854. if (r<0) {
  855. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  856. return -1;
  857. }
  858. len = r;
  859. if (*buf == 3) {
  860. /* Version 3 INTRODUCE2 cell. */
  861. time_t ts = 0;
  862. v3_shift = 1;
  863. auth_type = buf[1];
  864. switch (auth_type) {
  865. case REND_BASIC_AUTH:
  866. /* fall through */
  867. case REND_STEALTH_AUTH:
  868. auth_len = ntohs(get_uint16(buf+2));
  869. if (auth_len != REND_DESC_COOKIE_LEN) {
  870. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  871. (int)auth_len, REND_DESC_COOKIE_LEN);
  872. return -1;
  873. }
  874. memcpy(auth_data, buf+4, sizeof(auth_data));
  875. v3_shift += 2+REND_DESC_COOKIE_LEN;
  876. break;
  877. case REND_NO_AUTH:
  878. break;
  879. default:
  880. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  881. }
  882. /* Check timestamp. */
  883. ts = ntohl(get_uint32(buf+1+v3_shift));
  884. v3_shift += 4;
  885. if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
  886. (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
  887. log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
  888. (now - ts) < 0 ? "old" : "new");
  889. return -1;
  890. }
  891. }
  892. if (*buf == 2 || *buf == 3) {
  893. /* Version 2 INTRODUCE2 cell. */
  894. int klen;
  895. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  896. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  897. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  898. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  899. DIGEST_LEN);
  900. extend_info->nickname[0] = '$';
  901. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  902. extend_info->identity_digest, DIGEST_LEN);
  903. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  904. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  905. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  906. (int)len, *buf);
  907. reason = END_CIRC_REASON_TORPROTOCOL;
  908. goto err;
  909. }
  910. extend_info->onion_key =
  911. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  912. if (!extend_info->onion_key) {
  913. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  914. "INTRODUCE2 cell.", *buf);
  915. reason = END_CIRC_REASON_TORPROTOCOL;
  916. goto err;
  917. }
  918. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  919. len -= v3_shift+7+DIGEST_LEN+2+klen;
  920. } else {
  921. char *rp_nickname;
  922. size_t nickname_field_len;
  923. routerinfo_t *router;
  924. int version;
  925. if (*buf == 1) {
  926. rp_nickname = buf+1;
  927. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  928. version = 1;
  929. } else {
  930. nickname_field_len = MAX_NICKNAME_LEN+1;
  931. rp_nickname = buf;
  932. version = 0;
  933. }
  934. ptr=memchr(rp_nickname,0,nickname_field_len);
  935. if (!ptr || ptr == rp_nickname) {
  936. log_warn(LD_PROTOCOL,
  937. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  938. return -1;
  939. }
  940. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  941. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  942. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  943. return -1;
  944. }
  945. /* Okay, now we know that a nickname is at the start of the buffer. */
  946. ptr = rp_nickname+nickname_field_len;
  947. len -= nickname_field_len;
  948. len -= rp_nickname - buf; /* also remove header space used by version, if
  949. * any */
  950. router = router_get_by_nickname(rp_nickname, 0);
  951. if (!router) {
  952. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  953. escaped_safe_str(rp_nickname));
  954. /* XXXX Add a no-such-router reason? */
  955. reason = END_CIRC_REASON_TORPROTOCOL;
  956. goto err;
  957. }
  958. extend_info = extend_info_from_router(router);
  959. }
  960. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  961. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  962. reason = END_CIRC_REASON_TORPROTOCOL;
  963. goto err;
  964. }
  965. r_cookie = ptr;
  966. base16_encode(hexcookie,9,r_cookie,4);
  967. /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
  968. digest = crypto_new_digest_env();
  969. crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
  970. crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
  971. crypto_free_digest_env(digest);
  972. /* Check whether there is a past request with the same Diffie-Hellman,
  973. * part 1. */
  974. if (!service->accepted_intros)
  975. service->accepted_intros = digestmap_new();
  976. access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
  977. if (access_time != NULL) {
  978. log_warn(LD_REND, "Possible replay detected! We received an "
  979. "INTRODUCE2 cell with same first part of "
  980. "Diffie-Hellman handshake %d seconds ago. Dropping "
  981. "cell.",
  982. (int) (now - *access_time));
  983. goto err;
  984. }
  985. /* Add request to access history, including time and hash of Diffie-Hellman,
  986. * part 1, and possibly remove requests from the history that are older than
  987. * one hour. */
  988. access_time = tor_malloc(sizeof(time_t));
  989. *access_time = now;
  990. digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
  991. if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
  992. clean_accepted_intros(service, now);
  993. /* If the service performs client authorization, check included auth data. */
  994. if (service->clients) {
  995. if (auth_len > 0) {
  996. if (rend_check_authorization(service, auth_data)) {
  997. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  998. } else {
  999. log_info(LD_REND, "The authorization data that are contained in "
  1000. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1001. reason = END_CIRC_REASON_CONNECTFAILED;
  1002. goto err;
  1003. }
  1004. } else {
  1005. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1006. "data, but we require client authorization. Dropping cell.");
  1007. reason = END_CIRC_REASON_CONNECTFAILED;
  1008. goto err;
  1009. }
  1010. }
  1011. /* Try DH handshake... */
  1012. dh = crypto_dh_new();
  1013. if (!dh || crypto_dh_generate_public(dh)<0) {
  1014. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1015. "or generate public key.");
  1016. reason = END_CIRC_REASON_INTERNAL;
  1017. goto err;
  1018. }
  1019. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  1020. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1021. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1022. reason = END_CIRC_REASON_INTERNAL;
  1023. goto err;
  1024. }
  1025. circ_needs_uptime = rend_service_requires_uptime(service);
  1026. /* help predict this next time */
  1027. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1028. /* Launch a circuit to alice's chosen rendezvous point.
  1029. */
  1030. for (i=0;i<MAX_REND_FAILURES;i++) {
  1031. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1032. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1033. launched = circuit_launch_by_extend_info(
  1034. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1035. if (launched)
  1036. break;
  1037. }
  1038. if (!launched) { /* give up */
  1039. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1040. "point %s for service %s.",
  1041. escaped_safe_str(extend_info->nickname), serviceid);
  1042. reason = END_CIRC_REASON_CONNECTFAILED;
  1043. goto err;
  1044. }
  1045. log_info(LD_REND,
  1046. "Accepted intro; launching circuit to %s "
  1047. "(cookie %s) for service %s.",
  1048. escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
  1049. tor_assert(launched->build_state);
  1050. /* Fill in the circuit's state. */
  1051. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1052. memcpy(launched->rend_data->rend_pk_digest,
  1053. circuit->rend_data->rend_pk_digest,
  1054. DIGEST_LEN);
  1055. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1056. strlcpy(launched->rend_data->onion_address, service->service_id,
  1057. sizeof(launched->rend_data->onion_address));
  1058. launched->build_state->pending_final_cpath = cpath =
  1059. tor_malloc_zero(sizeof(crypt_path_t));
  1060. cpath->magic = CRYPT_PATH_MAGIC;
  1061. launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
  1062. cpath->dh_handshake_state = dh;
  1063. dh = NULL;
  1064. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1065. goto err;
  1066. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1067. if (extend_info) extend_info_free(extend_info);
  1068. return 0;
  1069. err:
  1070. if (dh) crypto_dh_free(dh);
  1071. if (launched)
  1072. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1073. if (extend_info) extend_info_free(extend_info);
  1074. return -1;
  1075. }
  1076. /** Called when we fail building a rendezvous circuit at some point other
  1077. * than the last hop: launches a new circuit to the same rendezvous point.
  1078. */
  1079. void
  1080. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1081. {
  1082. origin_circuit_t *newcirc;
  1083. cpath_build_state_t *newstate, *oldstate;
  1084. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1085. if (!oldcirc->build_state ||
  1086. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1087. oldcirc->build_state->expiry_time < time(NULL)) {
  1088. log_info(LD_REND,
  1089. "Attempt to build circuit to %s for rendezvous has failed "
  1090. "too many times or expired; giving up.",
  1091. oldcirc->build_state ?
  1092. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  1093. return;
  1094. }
  1095. oldstate = oldcirc->build_state;
  1096. tor_assert(oldstate);
  1097. if (oldstate->pending_final_cpath == NULL) {
  1098. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1099. "Initiator will retry.");
  1100. return;
  1101. }
  1102. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1103. oldstate->chosen_exit->nickname);
  1104. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1105. oldstate->chosen_exit,
  1106. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1107. if (!newcirc) {
  1108. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1109. oldstate->chosen_exit->nickname);
  1110. return;
  1111. }
  1112. newstate = newcirc->build_state;
  1113. tor_assert(newstate);
  1114. newstate->failure_count = oldstate->failure_count+1;
  1115. newstate->expiry_time = oldstate->expiry_time;
  1116. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  1117. oldstate->pending_final_cpath = NULL;
  1118. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1119. }
  1120. /** Launch a circuit to serve as an introduction point for the service
  1121. * <b>service</b> at the introduction point <b>nickname</b>
  1122. */
  1123. static int
  1124. rend_service_launch_establish_intro(rend_service_t *service,
  1125. rend_intro_point_t *intro)
  1126. {
  1127. origin_circuit_t *launched;
  1128. log_info(LD_REND,
  1129. "Launching circuit to introduction point %s for service %s",
  1130. escaped_safe_str(intro->extend_info->nickname),
  1131. service->service_id);
  1132. rep_hist_note_used_internal(time(NULL), 1, 0);
  1133. ++service->n_intro_circuits_launched;
  1134. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1135. intro->extend_info,
  1136. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1137. if (!launched) {
  1138. log_info(LD_REND,
  1139. "Can't launch circuit to establish introduction at %s.",
  1140. escaped_safe_str(intro->extend_info->nickname));
  1141. return -1;
  1142. }
  1143. if (memcmp(intro->extend_info->identity_digest,
  1144. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1145. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1146. base16_encode(cann, sizeof(cann),
  1147. launched->build_state->chosen_exit->identity_digest,
  1148. DIGEST_LEN);
  1149. base16_encode(orig, sizeof(orig),
  1150. intro->extend_info->identity_digest, DIGEST_LEN);
  1151. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1152. "but we requested an intro circuit to $%s. Updating "
  1153. "our service.", cann, orig);
  1154. extend_info_free(intro->extend_info);
  1155. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1156. }
  1157. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1158. strlcpy(launched->rend_data->onion_address, service->service_id,
  1159. sizeof(launched->rend_data->onion_address));
  1160. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1161. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1162. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1163. rend_service_intro_has_opened(launched);
  1164. return 0;
  1165. }
  1166. /** Return the number of introduction points that are or have been
  1167. * established for the given service address in <b>query</b>. */
  1168. static int
  1169. count_established_intro_points(const char *query)
  1170. {
  1171. int num_ipos = 0;
  1172. circuit_t *circ;
  1173. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1174. if (!circ->marked_for_close &&
  1175. circ->state == CIRCUIT_STATE_OPEN &&
  1176. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1177. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1178. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1179. if (oc->rend_data &&
  1180. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1181. num_ipos++;
  1182. }
  1183. }
  1184. return num_ipos;
  1185. }
  1186. /** Called when we're done building a circuit to an introduction point:
  1187. * sends a RELAY_ESTABLISH_INTRO cell.
  1188. */
  1189. void
  1190. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1191. {
  1192. rend_service_t *service;
  1193. size_t len;
  1194. int r;
  1195. char buf[RELAY_PAYLOAD_SIZE];
  1196. char auth[DIGEST_LEN + 9];
  1197. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1198. int reason = END_CIRC_REASON_TORPROTOCOL;
  1199. crypto_pk_env_t *intro_key;
  1200. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1201. tor_assert(circuit->cpath);
  1202. tor_assert(circuit->rend_data);
  1203. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1204. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1205. service = rend_service_get_by_pk_digest(
  1206. circuit->rend_data->rend_pk_digest);
  1207. if (!service) {
  1208. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1209. serviceid, circuit->_base.n_circ_id);
  1210. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1211. goto err;
  1212. }
  1213. /* If we already have enough introduction circuits for this service,
  1214. * redefine this one as a general circuit. */
  1215. if (count_established_intro_points(serviceid) > NUM_INTRO_POINTS) {
  1216. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1217. "circuit, but we already have enough. Redefining purpose to "
  1218. "general.");
  1219. TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1220. circuit_has_opened(circuit);
  1221. return;
  1222. }
  1223. log_info(LD_REND,
  1224. "Established circuit %d as introduction point for service %s",
  1225. circuit->_base.n_circ_id, serviceid);
  1226. /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
  1227. intro_key = circuit->intro_key;
  1228. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1229. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1230. RELAY_PAYLOAD_SIZE-2);
  1231. if (r < 0) {
  1232. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1233. reason = END_CIRC_REASON_INTERNAL;
  1234. goto err;
  1235. }
  1236. len = r;
  1237. set_uint16(buf, htons((uint16_t)len));
  1238. len += 2;
  1239. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1240. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1241. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1242. goto err;
  1243. len += 20;
  1244. note_crypto_pk_op(REND_SERVER);
  1245. r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
  1246. if (r<0) {
  1247. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1248. reason = END_CIRC_REASON_INTERNAL;
  1249. goto err;
  1250. }
  1251. len += r;
  1252. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1253. RELAY_COMMAND_ESTABLISH_INTRO,
  1254. buf, len, circuit->cpath->prev)<0) {
  1255. log_info(LD_GENERAL,
  1256. "Couldn't send introduction request for service %s on circuit %d",
  1257. serviceid, circuit->_base.n_circ_id);
  1258. reason = END_CIRC_REASON_INTERNAL;
  1259. goto err;
  1260. }
  1261. return;
  1262. err:
  1263. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1264. }
  1265. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1266. * live introduction point, and note that the service descriptor is
  1267. * now out-of-date.*/
  1268. int
  1269. rend_service_intro_established(origin_circuit_t *circuit, const char *request,
  1270. size_t request_len)
  1271. {
  1272. rend_service_t *service;
  1273. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1274. (void) request;
  1275. (void) request_len;
  1276. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1277. log_warn(LD_PROTOCOL,
  1278. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1279. goto err;
  1280. }
  1281. tor_assert(circuit->rend_data);
  1282. service = rend_service_get_by_pk_digest(
  1283. circuit->rend_data->rend_pk_digest);
  1284. if (!service) {
  1285. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1286. circuit->_base.n_circ_id);
  1287. goto err;
  1288. }
  1289. service->desc_is_dirty = time(NULL);
  1290. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1291. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1292. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1293. log_info(LD_REND,
  1294. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1295. circuit->_base.n_circ_id, serviceid);
  1296. return 0;
  1297. err:
  1298. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1299. return -1;
  1300. }
  1301. /** Called once a circuit to a rendezvous point is established: sends a
  1302. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1303. */
  1304. void
  1305. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1306. {
  1307. rend_service_t *service;
  1308. char buf[RELAY_PAYLOAD_SIZE];
  1309. crypt_path_t *hop;
  1310. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1311. char hexcookie[9];
  1312. int reason;
  1313. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1314. tor_assert(circuit->cpath);
  1315. tor_assert(circuit->build_state);
  1316. tor_assert(circuit->rend_data);
  1317. hop = circuit->build_state->pending_final_cpath;
  1318. tor_assert(hop);
  1319. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1320. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1321. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1322. log_info(LD_REND,
  1323. "Done building circuit %d to rendezvous with "
  1324. "cookie %s for service %s",
  1325. circuit->_base.n_circ_id, hexcookie, serviceid);
  1326. service = rend_service_get_by_pk_digest(
  1327. circuit->rend_data->rend_pk_digest);
  1328. if (!service) {
  1329. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1330. "introduction circuit.");
  1331. reason = END_CIRC_REASON_INTERNAL;
  1332. goto err;
  1333. }
  1334. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1335. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1336. if (crypto_dh_get_public(hop->dh_handshake_state,
  1337. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1338. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1339. reason = END_CIRC_REASON_INTERNAL;
  1340. goto err;
  1341. }
  1342. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1343. DIGEST_LEN);
  1344. /* Send the cell */
  1345. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1346. RELAY_COMMAND_RENDEZVOUS1,
  1347. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1348. circuit->cpath->prev)<0) {
  1349. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1350. reason = END_CIRC_REASON_INTERNAL;
  1351. goto err;
  1352. }
  1353. crypto_dh_free(hop->dh_handshake_state);
  1354. hop->dh_handshake_state = NULL;
  1355. /* Append the cpath entry. */
  1356. hop->state = CPATH_STATE_OPEN;
  1357. /* set the windows to default. these are the windows
  1358. * that bob thinks alice has.
  1359. */
  1360. hop->package_window = circuit_initial_package_window();
  1361. hop->deliver_window = CIRCWINDOW_START;
  1362. onion_append_to_cpath(&circuit->cpath, hop);
  1363. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1364. /* Change the circuit purpose. */
  1365. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1366. return;
  1367. err:
  1368. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1369. }
  1370. /*
  1371. * Manage introduction points
  1372. */
  1373. /** Return the (possibly non-open) introduction circuit ending at
  1374. * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
  1375. * (<b>desc_version</b> is ignored). Return NULL if no such service is
  1376. * found.
  1377. */
  1378. static origin_circuit_t *
  1379. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
  1380. {
  1381. origin_circuit_t *circ = NULL;
  1382. tor_assert(intro);
  1383. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1384. CIRCUIT_PURPOSE_S_INTRO))) {
  1385. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1386. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1387. circ->rend_data) {
  1388. return circ;
  1389. }
  1390. }
  1391. circ = NULL;
  1392. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1393. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1394. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1395. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1396. circ->rend_data) {
  1397. return circ;
  1398. }
  1399. }
  1400. return NULL;
  1401. }
  1402. /** Determine the responsible hidden service directories for the
  1403. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1404. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1405. * purposes. */
  1406. static void
  1407. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1408. smartlist_t *descs, const char *service_id,
  1409. int seconds_valid)
  1410. {
  1411. int i, j, failed_upload = 0;
  1412. smartlist_t *responsible_dirs = smartlist_create();
  1413. smartlist_t *successful_uploads = smartlist_create();
  1414. routerstatus_t *hs_dir;
  1415. for (i = 0; i < smartlist_len(descs); i++) {
  1416. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1417. /* Determine responsible dirs. */
  1418. if (hid_serv_get_responsible_directories(responsible_dirs,
  1419. desc->desc_id) < 0) {
  1420. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1421. "directories to post descriptors to.");
  1422. smartlist_free(responsible_dirs);
  1423. smartlist_free(successful_uploads);
  1424. return;
  1425. }
  1426. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1427. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1428. hs_dir = smartlist_get(responsible_dirs, j);
  1429. if (smartlist_digest_isin(renddesc->successful_uploads,
  1430. hs_dir->identity_digest))
  1431. /* Don't upload descriptor if we succeeded in doing so last time. */
  1432. continue;
  1433. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1434. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1435. "hidden service directory '%s'; we don't have its "
  1436. "router descriptor. Queuing for later upload.",
  1437. hs_dir->nickname);
  1438. failed_upload = -1;
  1439. continue;
  1440. }
  1441. /* Send publish request. */
  1442. directory_initiate_command_routerstatus(hs_dir,
  1443. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1444. ROUTER_PURPOSE_GENERAL,
  1445. 1, NULL, desc->desc_str,
  1446. strlen(desc->desc_str), 0);
  1447. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1448. desc->desc_id, DIGEST_LEN);
  1449. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1450. "service '%s' with descriptor ID '%s' with validity "
  1451. "of %d seconds to hidden service directory '%s' on "
  1452. "port %d.",
  1453. safe_str(service_id),
  1454. safe_str(desc_id_base32),
  1455. seconds_valid,
  1456. hs_dir->nickname,
  1457. hs_dir->dir_port);
  1458. /* Remember successful upload to this router for next time. */
  1459. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1460. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1461. }
  1462. smartlist_clear(responsible_dirs);
  1463. }
  1464. if (!failed_upload) {
  1465. if (renddesc->successful_uploads) {
  1466. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1467. smartlist_free(renddesc->successful_uploads);
  1468. renddesc->successful_uploads = NULL;
  1469. }
  1470. renddesc->all_uploads_performed = 1;
  1471. } else {
  1472. /* Remember which routers worked this time, so that we don't upload the
  1473. * descriptor to them again. */
  1474. if (!renddesc->successful_uploads)
  1475. renddesc->successful_uploads = smartlist_create();
  1476. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1477. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1478. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1479. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1480. }
  1481. });
  1482. }
  1483. smartlist_free(responsible_dirs);
  1484. smartlist_free(successful_uploads);
  1485. }
  1486. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  1487. * and upload it/them to the responsible hidden service directories.
  1488. */
  1489. static void
  1490. upload_service_descriptor(rend_service_t *service)
  1491. {
  1492. time_t now = time(NULL);
  1493. int rendpostperiod;
  1494. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1495. int uploaded = 0;
  1496. rendpostperiod = get_options()->RendPostPeriod;
  1497. /* Upload descriptor? */
  1498. if (get_options()->PublishHidServDescriptors) {
  1499. networkstatus_t *c = networkstatus_get_latest_consensus();
  1500. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1501. int seconds_valid, i, j, num_descs;
  1502. smartlist_t *descs = smartlist_create();
  1503. smartlist_t *client_cookies = smartlist_create();
  1504. /* Either upload a single descriptor (including replicas) or one
  1505. * descriptor for each authorized client in case of authorization
  1506. * type 'stealth'. */
  1507. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1508. smartlist_len(service->clients) : 1;
  1509. for (j = 0; j < num_descs; j++) {
  1510. crypto_pk_env_t *client_key = NULL;
  1511. rend_authorized_client_t *client = NULL;
  1512. smartlist_clear(client_cookies);
  1513. switch (service->auth_type) {
  1514. case REND_NO_AUTH:
  1515. /* Do nothing here. */
  1516. break;
  1517. case REND_BASIC_AUTH:
  1518. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1519. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1520. break;
  1521. case REND_STEALTH_AUTH:
  1522. client = smartlist_get(service->clients, j);
  1523. client_key = client->client_key;
  1524. smartlist_add(client_cookies, client->descriptor_cookie);
  1525. break;
  1526. }
  1527. /* Encode the current descriptor. */
  1528. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1529. now, 0,
  1530. service->auth_type,
  1531. client_key,
  1532. client_cookies);
  1533. if (seconds_valid < 0) {
  1534. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1535. "descriptor; not uploading.");
  1536. smartlist_free(descs);
  1537. smartlist_free(client_cookies);
  1538. return;
  1539. }
  1540. /* Post the current descriptors to the hidden service directories. */
  1541. rend_get_service_id(service->desc->pk, serviceid);
  1542. log_info(LD_REND, "Sending publish request for hidden service %s",
  1543. serviceid);
  1544. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1545. seconds_valid);
  1546. /* Free memory for descriptors. */
  1547. for (i = 0; i < smartlist_len(descs); i++)
  1548. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1549. smartlist_clear(descs);
  1550. /* Update next upload time. */
  1551. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1552. > rendpostperiod)
  1553. service->next_upload_time = now + rendpostperiod;
  1554. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1555. service->next_upload_time = now + seconds_valid + 1;
  1556. else
  1557. service->next_upload_time = now + seconds_valid -
  1558. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1559. /* Post also the next descriptors, if necessary. */
  1560. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1561. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1562. now, 1,
  1563. service->auth_type,
  1564. client_key,
  1565. client_cookies);
  1566. if (seconds_valid < 0) {
  1567. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1568. "descriptor; not uploading.");
  1569. smartlist_free(descs);
  1570. smartlist_free(client_cookies);
  1571. return;
  1572. }
  1573. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1574. seconds_valid);
  1575. /* Free memory for descriptors. */
  1576. for (i = 0; i < smartlist_len(descs); i++)
  1577. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1578. smartlist_clear(descs);
  1579. }
  1580. }
  1581. smartlist_free(descs);
  1582. smartlist_free(client_cookies);
  1583. uploaded = 1;
  1584. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1585. }
  1586. }
  1587. /* If not uploaded, try again in one minute. */
  1588. if (!uploaded)
  1589. service->next_upload_time = now + 60;
  1590. /* Unmark dirty flag of this service. */
  1591. service->desc_is_dirty = 0;
  1592. }
  1593. /** For every service, check how many intro points it currently has, and:
  1594. * - Pick new intro points as necessary.
  1595. * - Launch circuits to any new intro points.
  1596. */
  1597. void
  1598. rend_services_introduce(void)
  1599. {
  1600. int i,j,r;
  1601. routerinfo_t *router;
  1602. rend_service_t *service;
  1603. rend_intro_point_t *intro;
  1604. int changed, prev_intro_nodes;
  1605. smartlist_t *intro_routers;
  1606. time_t now;
  1607. or_options_t *options = get_options();
  1608. intro_routers = smartlist_create();
  1609. now = time(NULL);
  1610. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1611. smartlist_clear(intro_routers);
  1612. service = smartlist_get(rend_service_list, i);
  1613. tor_assert(service);
  1614. changed = 0;
  1615. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1616. /* One period has elapsed; we can try building circuits again. */
  1617. service->intro_period_started = now;
  1618. service->n_intro_circuits_launched = 0;
  1619. } else if (service->n_intro_circuits_launched >=
  1620. MAX_INTRO_CIRCS_PER_PERIOD) {
  1621. /* We have failed too many times in this period; wait for the next
  1622. * one before we try again. */
  1623. continue;
  1624. }
  1625. /* Find out which introduction points we have in progress for this
  1626. service. */
  1627. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1628. intro = smartlist_get(service->intro_nodes, j);
  1629. router = router_get_by_digest(intro->extend_info->identity_digest);
  1630. if (!router || !find_intro_circuit(intro, service->pk_digest)) {
  1631. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1632. intro->extend_info->nickname, service->service_id);
  1633. if (service->desc) {
  1634. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1635. dintro, {
  1636. if (!memcmp(dintro->extend_info->identity_digest,
  1637. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1638. log_info(LD_REND, "The intro point we are giving up on was "
  1639. "included in the last published descriptor. "
  1640. "Marking current descriptor as dirty.");
  1641. service->desc_is_dirty = now;
  1642. }
  1643. });
  1644. }
  1645. rend_intro_point_free(intro);
  1646. smartlist_del(service->intro_nodes,j--);
  1647. changed = 1;
  1648. }
  1649. if (router)
  1650. smartlist_add(intro_routers, router);
  1651. }
  1652. /* We have enough intro points, and the intro points we thought we had were
  1653. * all connected.
  1654. */
  1655. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1656. /* We have all our intro points! Start a fresh period and reset the
  1657. * circuit count. */
  1658. service->intro_period_started = now;
  1659. service->n_intro_circuits_launched = 0;
  1660. continue;
  1661. }
  1662. /* Remember how many introduction circuits we started with. */
  1663. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1664. /* We have enough directory information to start establishing our
  1665. * intro points. We want to end up with three intro points, but if
  1666. * we're just starting, we launch five and pick the first three that
  1667. * complete.
  1668. *
  1669. * The ones after the first three will be converted to 'general'
  1670. * internal circuits in rend_service_intro_has_opened(), and then
  1671. * we'll drop them from the list of intro points next time we
  1672. * go through the above "find out which introduction points we have
  1673. * in progress" loop. */
  1674. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1675. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1676. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1677. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1678. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1679. flags |= CRN_ALLOW_INVALID;
  1680. router = router_choose_random_node(NULL, intro_routers,
  1681. options->ExcludeNodes, flags);
  1682. if (!router) {
  1683. log_warn(LD_REND,
  1684. "Could only establish %d introduction points for %s.",
  1685. smartlist_len(service->intro_nodes), service->service_id);
  1686. break;
  1687. }
  1688. changed = 1;
  1689. smartlist_add(intro_routers, router);
  1690. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1691. intro->extend_info = extend_info_from_router(router);
  1692. intro->intro_key = crypto_new_pk_env();
  1693. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1694. smartlist_add(service->intro_nodes, intro);
  1695. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1696. router->nickname, service->service_id);
  1697. }
  1698. /* If there's no need to launch new circuits, stop here. */
  1699. if (!changed)
  1700. continue;
  1701. /* Establish new introduction points. */
  1702. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1703. intro = smartlist_get(service->intro_nodes, j);
  1704. r = rend_service_launch_establish_intro(service, intro);
  1705. if (r<0) {
  1706. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1707. intro->extend_info->nickname, service->service_id);
  1708. }
  1709. }
  1710. }
  1711. smartlist_free(intro_routers);
  1712. }
  1713. /** Regenerate and upload rendezvous service descriptors for all
  1714. * services, if necessary. If the descriptor has been dirty enough
  1715. * for long enough, definitely upload; else only upload when the
  1716. * periodic timeout has expired.
  1717. *
  1718. * For the first upload, pick a random time between now and two periods
  1719. * from now, and pick it independently for each service.
  1720. */
  1721. void
  1722. rend_consider_services_upload(time_t now)
  1723. {
  1724. int i;
  1725. rend_service_t *service;
  1726. int rendpostperiod = get_options()->RendPostPeriod;
  1727. if (!get_options()->PublishHidServDescriptors)
  1728. return;
  1729. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1730. service = smartlist_get(rend_service_list, i);
  1731. if (!service->next_upload_time) { /* never been uploaded yet */
  1732. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1733. * is stable before being published. See comment below. */
  1734. service->next_upload_time =
  1735. now + 30 + crypto_rand_int(2*rendpostperiod);
  1736. }
  1737. if (service->next_upload_time < now ||
  1738. (service->desc_is_dirty &&
  1739. service->desc_is_dirty < now-30)) {
  1740. /* if it's time, or if the directory servers have a wrong service
  1741. * descriptor and ours has been stable for 30 seconds, upload a
  1742. * new one of each format. */
  1743. rend_service_update_descriptor(service);
  1744. upload_service_descriptor(service);
  1745. }
  1746. }
  1747. }
  1748. /** True if the list of available router descriptors might have changed so
  1749. * that we should have a look whether we can republish previously failed
  1750. * rendezvous service descriptors. */
  1751. static int consider_republishing_rend_descriptors = 1;
  1752. /** Called when our internal view of the directory has changed, so that we
  1753. * might have router descriptors of hidden service directories available that
  1754. * we did not have before. */
  1755. void
  1756. rend_hsdir_routers_changed(void)
  1757. {
  1758. consider_republishing_rend_descriptors = 1;
  1759. }
  1760. /** Consider republication of v2 rendezvous service descriptors that failed
  1761. * previously, but without regenerating descriptor contents.
  1762. */
  1763. void
  1764. rend_consider_descriptor_republication(void)
  1765. {
  1766. int i;
  1767. rend_service_t *service;
  1768. if (!consider_republishing_rend_descriptors)
  1769. return;
  1770. consider_republishing_rend_descriptors = 0;
  1771. if (!get_options()->PublishHidServDescriptors)
  1772. return;
  1773. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1774. service = smartlist_get(rend_service_list, i);
  1775. if (service->desc && !service->desc->all_uploads_performed) {
  1776. /* If we failed in uploading a descriptor last time, try again *without*
  1777. * updating the descriptor's contents. */
  1778. upload_service_descriptor(service);
  1779. }
  1780. }
  1781. }
  1782. /** Log the status of introduction points for all rendezvous services
  1783. * at log severity <b>severity</b>.
  1784. */
  1785. void
  1786. rend_service_dump_stats(int severity)
  1787. {
  1788. int i,j;
  1789. rend_service_t *service;
  1790. rend_intro_point_t *intro;
  1791. const char *safe_name;
  1792. origin_circuit_t *circ;
  1793. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1794. service = smartlist_get(rend_service_list, i);
  1795. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1796. service->directory);
  1797. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1798. intro = smartlist_get(service->intro_nodes, j);
  1799. safe_name = safe_str(intro->extend_info->nickname);
  1800. circ = find_intro_circuit(intro, service->pk_digest);
  1801. if (!circ) {
  1802. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1803. j, safe_name);
  1804. continue;
  1805. }
  1806. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1807. j, safe_name, circuit_state_to_string(circ->_base.state));
  1808. }
  1809. }
  1810. }
  1811. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1812. * 'circ', and look up the port and address based on conn-\>port.
  1813. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1814. * or 0 for success.
  1815. */
  1816. int
  1817. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1818. origin_circuit_t *circ)
  1819. {
  1820. rend_service_t *service;
  1821. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1822. smartlist_t *matching_ports;
  1823. rend_service_port_config_t *chosen_port;
  1824. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1825. tor_assert(circ->rend_data);
  1826. log_debug(LD_REND,"beginning to hunt for addr/port");
  1827. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1828. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1829. service = rend_service_get_by_pk_digest(
  1830. circ->rend_data->rend_pk_digest);
  1831. if (!service) {
  1832. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1833. "rendezvous circuit %d; closing.",
  1834. serviceid, circ->_base.n_circ_id);
  1835. return -1;
  1836. }
  1837. matching_ports = smartlist_create();
  1838. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1839. {
  1840. if (conn->_base.port == p->virtual_port) {
  1841. smartlist_add(matching_ports, p);
  1842. }
  1843. });
  1844. chosen_port = smartlist_choose(matching_ports);
  1845. smartlist_free(matching_ports);
  1846. if (chosen_port) {
  1847. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1848. conn->_base.port = chosen_port->real_port;
  1849. return 0;
  1850. }
  1851. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1852. conn->_base.port,serviceid);
  1853. return -1;
  1854. }