rendservice.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2010, 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)
  81. return;
  82. if (client->client_key)
  83. crypto_free_pk_env(client->client_key);
  84. tor_free(client->client_name);
  85. tor_free(client);
  86. }
  87. /** Helper for strmap_free. */
  88. static void
  89. rend_authorized_client_strmap_item_free(void *authorized_client)
  90. {
  91. rend_authorized_client_free(authorized_client);
  92. }
  93. /** Release the storage held by <b>service</b>.
  94. */
  95. static void
  96. rend_service_free(rend_service_t *service)
  97. {
  98. if (!service)
  99. return;
  100. tor_free(service->directory);
  101. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  102. smartlist_free(service->ports);
  103. if (service->private_key)
  104. crypto_free_pk_env(service->private_key);
  105. if (service->intro_nodes) {
  106. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  107. rend_intro_point_free(intro););
  108. smartlist_free(service->intro_nodes);
  109. }
  110. rend_service_descriptor_free(service->desc);
  111. if (service->clients) {
  112. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  113. rend_authorized_client_free(c););
  114. smartlist_free(service->clients);
  115. }
  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. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  127. rend_service_free(ptr));
  128. smartlist_free(rend_service_list);
  129. rend_service_list = NULL;
  130. }
  131. /** Validate <b>service</b> and add it to rend_service_list if possible.
  132. */
  133. static void
  134. rend_add_service(rend_service_t *service)
  135. {
  136. int i;
  137. rend_service_port_config_t *p;
  138. service->intro_nodes = smartlist_create();
  139. if (service->auth_type != REND_NO_AUTH &&
  140. smartlist_len(service->clients) == 0) {
  141. log_warn(LD_CONFIG, "Hidden service with client authorization but no "
  142. "clients; ignoring.");
  143. rend_service_free(service);
  144. return;
  145. }
  146. if (!smartlist_len(service->ports)) {
  147. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  148. rend_service_free(service);
  149. } else {
  150. smartlist_add(rend_service_list, service);
  151. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  152. service->directory);
  153. for (i = 0; i < smartlist_len(service->ports); ++i) {
  154. p = smartlist_get(service->ports, i);
  155. log_debug(LD_REND,"Service maps port %d to %s:%d",
  156. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  157. }
  158. }
  159. }
  160. /** Parses a real-port to virtual-port mapping and returns a new
  161. * rend_service_port_config_t.
  162. *
  163. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  164. *
  165. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  166. */
  167. static rend_service_port_config_t *
  168. parse_port_config(const char *string)
  169. {
  170. smartlist_t *sl;
  171. int virtport;
  172. int realport;
  173. uint16_t p;
  174. tor_addr_t addr;
  175. const char *addrport;
  176. rend_service_port_config_t *result = NULL;
  177. sl = smartlist_create();
  178. smartlist_split_string(sl, string, " ",
  179. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  180. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  181. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  182. goto err;
  183. }
  184. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  185. if (!virtport) {
  186. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  187. "configuration", escaped(smartlist_get(sl,0)));
  188. goto err;
  189. }
  190. if (smartlist_len(sl) == 1) {
  191. /* No addr:port part; use default. */
  192. realport = virtport;
  193. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  194. } else {
  195. addrport = smartlist_get(sl,1);
  196. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  197. if (tor_addr_port_parse(addrport, &addr, &p)<0) {
  198. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  199. "configuration.");
  200. goto err;
  201. }
  202. realport = p?p:virtport;
  203. } else {
  204. /* No addr:port, no addr -- must be port. */
  205. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  206. if (!realport) {
  207. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  208. "service port configuration.", escaped(addrport));
  209. goto err;
  210. }
  211. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  212. }
  213. }
  214. result = tor_malloc(sizeof(rend_service_port_config_t));
  215. result->virtual_port = virtport;
  216. result->real_port = realport;
  217. tor_addr_copy(&result->real_addr, &addr);
  218. err:
  219. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  220. smartlist_free(sl);
  221. return result;
  222. }
  223. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  224. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  225. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  226. * normal, but don't actually change the configured services.)
  227. */
  228. int
  229. rend_config_services(or_options_t *options, int validate_only)
  230. {
  231. config_line_t *line;
  232. rend_service_t *service = NULL;
  233. rend_service_port_config_t *portcfg;
  234. smartlist_t *old_service_list = NULL;
  235. if (!validate_only) {
  236. old_service_list = rend_service_list;
  237. rend_service_list = smartlist_create();
  238. }
  239. for (line = options->RendConfigLines; line; line = line->next) {
  240. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  241. if (service) { /* register the one we just finished parsing */
  242. if (validate_only)
  243. rend_service_free(service);
  244. else
  245. rend_add_service(service);
  246. }
  247. service = tor_malloc_zero(sizeof(rend_service_t));
  248. service->directory = tor_strdup(line->value);
  249. service->ports = smartlist_create();
  250. service->intro_period_started = time(NULL);
  251. continue;
  252. }
  253. if (!service) {
  254. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  255. line->key);
  256. rend_service_free(service);
  257. return -1;
  258. }
  259. if (!strcasecmp(line->key, "HiddenServicePort")) {
  260. portcfg = parse_port_config(line->value);
  261. if (!portcfg) {
  262. rend_service_free(service);
  263. return -1;
  264. }
  265. smartlist_add(service->ports, portcfg);
  266. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  267. /* Parse auth type and comma-separated list of client names and add a
  268. * rend_authorized_client_t for each client to the service's list
  269. * of authorized clients. */
  270. smartlist_t *type_names_split, *clients;
  271. const char *authname;
  272. int num_clients;
  273. if (service->auth_type != REND_NO_AUTH) {
  274. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  275. "lines for a single service.");
  276. rend_service_free(service);
  277. return -1;
  278. }
  279. type_names_split = smartlist_create();
  280. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  281. if (smartlist_len(type_names_split) < 1) {
  282. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  283. "should have been prevented when parsing the "
  284. "configuration.");
  285. smartlist_free(type_names_split);
  286. rend_service_free(service);
  287. return -1;
  288. }
  289. authname = smartlist_get(type_names_split, 0);
  290. if (!strcasecmp(authname, "basic")) {
  291. service->auth_type = REND_BASIC_AUTH;
  292. } else if (!strcasecmp(authname, "stealth")) {
  293. service->auth_type = REND_STEALTH_AUTH;
  294. } else {
  295. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  296. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  297. "are recognized.",
  298. (char *) smartlist_get(type_names_split, 0));
  299. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  300. smartlist_free(type_names_split);
  301. rend_service_free(service);
  302. return -1;
  303. }
  304. service->clients = smartlist_create();
  305. if (smartlist_len(type_names_split) < 2) {
  306. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  307. "auth-type '%s', but no client names.",
  308. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  309. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  310. smartlist_free(type_names_split);
  311. continue;
  312. }
  313. clients = smartlist_create();
  314. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  315. ",", SPLIT_SKIP_SPACE, 0);
  316. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  317. smartlist_free(type_names_split);
  318. /* Remove duplicate client names. */
  319. num_clients = smartlist_len(clients);
  320. smartlist_sort_strings(clients);
  321. smartlist_uniq_strings(clients);
  322. if (smartlist_len(clients) < num_clients) {
  323. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  324. "duplicate client name(s); removing.",
  325. num_clients - smartlist_len(clients));
  326. num_clients = smartlist_len(clients);
  327. }
  328. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  329. {
  330. rend_authorized_client_t *client;
  331. size_t len = strlen(client_name);
  332. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  333. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  334. "illegal client name: '%s'. Length must be "
  335. "between 1 and %d characters.",
  336. client_name, REND_CLIENTNAME_MAX_LEN);
  337. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  338. smartlist_free(clients);
  339. rend_service_free(service);
  340. return -1;
  341. }
  342. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  343. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  344. "illegal client name: '%s'. Valid "
  345. "characters are [A-Za-z0-9+-_].",
  346. client_name);
  347. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  348. smartlist_free(clients);
  349. rend_service_free(service);
  350. return -1;
  351. }
  352. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  353. client->client_name = tor_strdup(client_name);
  354. smartlist_add(service->clients, client);
  355. log_debug(LD_REND, "Adding client name '%s'", client_name);
  356. }
  357. SMARTLIST_FOREACH_END(client_name);
  358. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  359. smartlist_free(clients);
  360. /* Ensure maximum number of clients. */
  361. if ((service->auth_type == REND_BASIC_AUTH &&
  362. smartlist_len(service->clients) > 512) ||
  363. (service->auth_type == REND_STEALTH_AUTH &&
  364. smartlist_len(service->clients) > 16)) {
  365. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  366. "client authorization entries, but only a "
  367. "maximum of %d entries is allowed for "
  368. "authorization type '%s'.",
  369. smartlist_len(service->clients),
  370. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  371. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  372. rend_service_free(service);
  373. return -1;
  374. }
  375. } else {
  376. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  377. if (strcmp(line->value, "2")) {
  378. log_warn(LD_CONFIG,
  379. "The only supported HiddenServiceVersion is 2.");
  380. rend_service_free(service);
  381. return -1;
  382. }
  383. }
  384. }
  385. if (service) {
  386. if (validate_only)
  387. rend_service_free(service);
  388. else
  389. rend_add_service(service);
  390. }
  391. /* If this is a reload and there were hidden services configured before,
  392. * keep the introduction points that are still needed and close the
  393. * other ones. */
  394. if (old_service_list && !validate_only) {
  395. smartlist_t *surviving_services = smartlist_create();
  396. circuit_t *circ;
  397. /* Copy introduction points to new services. */
  398. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  399. * probably ok? */
  400. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
  401. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  402. if (!strcmp(old->directory, new->directory)) {
  403. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  404. smartlist_clear(old->intro_nodes);
  405. smartlist_add(surviving_services, old);
  406. break;
  407. }
  408. });
  409. });
  410. /* Close introduction circuits of services we don't serve anymore. */
  411. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  412. * so we could just iterate over the list of services to close, but
  413. * once again, this isn't critical-path code. */
  414. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  415. if (!circ->marked_for_close &&
  416. circ->state == CIRCUIT_STATE_OPEN &&
  417. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  418. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  419. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  420. int keep_it = 0;
  421. tor_assert(oc->rend_data);
  422. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  423. if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  424. DIGEST_LEN)) {
  425. keep_it = 1;
  426. break;
  427. }
  428. });
  429. if (keep_it)
  430. continue;
  431. log_info(LD_REND, "Closing intro point %s for service %s.",
  432. safe_str_client(oc->build_state->chosen_exit->nickname),
  433. oc->rend_data->onion_address);
  434. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  435. /* XXXX Is there another reason we should use here? */
  436. }
  437. }
  438. smartlist_free(surviving_services);
  439. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  440. rend_service_free(ptr));
  441. smartlist_free(old_service_list);
  442. }
  443. return 0;
  444. }
  445. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  446. * the other fields in service.
  447. */
  448. static void
  449. rend_service_update_descriptor(rend_service_t *service)
  450. {
  451. rend_service_descriptor_t *d;
  452. origin_circuit_t *circ;
  453. int i;
  454. rend_service_descriptor_free(service->desc);
  455. service->desc = NULL;
  456. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  457. d->pk = crypto_pk_dup_key(service->private_key);
  458. d->timestamp = time(NULL);
  459. d->intro_nodes = smartlist_create();
  460. /* Support intro protocols 2 and 3. */
  461. d->protocols = (1 << 2) + (1 << 3);
  462. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  463. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  464. rend_intro_point_t *intro_desc;
  465. circ = find_intro_circuit(intro_svc, service->pk_digest);
  466. if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
  467. continue;
  468. /* We have an entirely established intro circuit. */
  469. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  470. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  471. if (intro_svc->intro_key)
  472. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  473. smartlist_add(d->intro_nodes, intro_desc);
  474. }
  475. }
  476. /** Load and/or generate private keys for all hidden services, possibly
  477. * including keys for client authorization. Return 0 on success, -1 on
  478. * failure.
  479. */
  480. int
  481. rend_service_load_keys(void)
  482. {
  483. int r = 0;
  484. char fname[512];
  485. char buf[1500];
  486. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  487. if (s->private_key)
  488. continue;
  489. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  490. s->directory);
  491. /* Check/create directory */
  492. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  493. return -1;
  494. /* Load key */
  495. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  496. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  497. >= sizeof(fname)) {
  498. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  499. s->directory);
  500. return -1;
  501. }
  502. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  503. if (!s->private_key)
  504. return -1;
  505. /* Create service file */
  506. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  507. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  508. return -1;
  509. }
  510. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  511. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  512. return -1;
  513. }
  514. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  515. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  516. >= sizeof(fname)) {
  517. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  518. " \"%s\".", s->directory);
  519. return -1;
  520. }
  521. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  522. if (write_str_to_file(fname,buf,0)<0) {
  523. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  524. return -1;
  525. }
  526. /* If client authorization is configured, load or generate keys. */
  527. if (s->auth_type != REND_NO_AUTH) {
  528. char *client_keys_str = NULL;
  529. strmap_t *parsed_clients = strmap_new();
  530. char cfname[512];
  531. FILE *cfile, *hfile;
  532. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  533. /* Load client keys and descriptor cookies, if available. */
  534. if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
  535. s->directory)<0) {
  536. log_warn(LD_CONFIG, "Directory name too long to store client keys "
  537. "file: \"%s\".", s->directory);
  538. goto err;
  539. }
  540. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  541. if (client_keys_str) {
  542. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  543. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  544. "be parsed.");
  545. goto err;
  546. } else {
  547. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  548. strmap_size(parsed_clients));
  549. tor_free(client_keys_str);
  550. }
  551. }
  552. /* Prepare client_keys and hostname files. */
  553. if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
  554. 0600, &open_cfile))) {
  555. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  556. escaped(cfname));
  557. goto err;
  558. }
  559. if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
  560. 0600, &open_hfile))) {
  561. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
  562. goto err;
  563. }
  564. /* Either use loaded keys for configured clients or generate new
  565. * ones if a client is new. */
  566. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
  567. {
  568. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  569. char service_id[16+1];
  570. rend_authorized_client_t *parsed =
  571. strmap_get(parsed_clients, client->client_name);
  572. int written;
  573. size_t len;
  574. /* Copy descriptor cookie from parsed entry or create new one. */
  575. if (parsed) {
  576. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  577. REND_DESC_COOKIE_LEN);
  578. } else {
  579. crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  580. }
  581. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  582. client->descriptor_cookie,
  583. REND_DESC_COOKIE_LEN) < 0) {
  584. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  585. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  586. return -1;
  587. }
  588. /* Copy client key from parsed entry or create new one if required. */
  589. if (parsed && parsed->client_key) {
  590. client->client_key = crypto_pk_dup_key(parsed->client_key);
  591. } else if (s->auth_type == REND_STEALTH_AUTH) {
  592. /* Create private key for client. */
  593. crypto_pk_env_t *prkey = NULL;
  594. if (!(prkey = crypto_new_pk_env())) {
  595. log_warn(LD_BUG,"Error constructing client key");
  596. goto err;
  597. }
  598. if (crypto_pk_generate_key(prkey)) {
  599. log_warn(LD_BUG,"Error generating client key");
  600. crypto_free_pk_env(prkey);
  601. goto err;
  602. }
  603. if (crypto_pk_check_key(prkey) <= 0) {
  604. log_warn(LD_BUG,"Generated client key seems invalid");
  605. crypto_free_pk_env(prkey);
  606. goto err;
  607. }
  608. client->client_key = prkey;
  609. }
  610. /* Add entry to client_keys file. */
  611. desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
  612. written = tor_snprintf(buf, sizeof(buf),
  613. "client-name %s\ndescriptor-cookie %s\n",
  614. client->client_name, desc_cook_out);
  615. if (written < 0) {
  616. log_warn(LD_BUG, "Could not write client entry.");
  617. goto err;
  618. }
  619. if (client->client_key) {
  620. char *client_key_out = NULL;
  621. crypto_pk_write_private_key_to_string(client->client_key,
  622. &client_key_out, &len);
  623. if (rend_get_service_id(client->client_key, service_id)<0) {
  624. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  625. tor_free(client_key_out);
  626. goto err;
  627. }
  628. written = tor_snprintf(buf + written, sizeof(buf) - written,
  629. "client-key\n%s", client_key_out);
  630. tor_free(client_key_out);
  631. if (written < 0) {
  632. log_warn(LD_BUG, "Could not write client entry.");
  633. goto err;
  634. }
  635. }
  636. if (fputs(buf, cfile) < 0) {
  637. log_warn(LD_FS, "Could not append client entry to file: %s",
  638. strerror(errno));
  639. goto err;
  640. }
  641. /* Add line to hostname file. */
  642. if (s->auth_type == REND_BASIC_AUTH) {
  643. /* Remove == signs (newline has been removed above). */
  644. desc_cook_out[strlen(desc_cook_out)-2] = '\0';
  645. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  646. s->service_id, desc_cook_out, client->client_name);
  647. } else {
  648. char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
  649. memcpy(extended_desc_cookie, client->descriptor_cookie,
  650. REND_DESC_COOKIE_LEN);
  651. extended_desc_cookie[REND_DESC_COOKIE_LEN] =
  652. ((int)s->auth_type - 1) << 4;
  653. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  654. extended_desc_cookie,
  655. REND_DESC_COOKIE_LEN+1) < 0) {
  656. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  657. goto err;
  658. }
  659. desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
  660. newline. */
  661. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  662. service_id, desc_cook_out, client->client_name);
  663. }
  664. if (fputs(buf, hfile)<0) {
  665. log_warn(LD_FS, "Could not append host entry to file: %s",
  666. strerror(errno));
  667. goto err;
  668. }
  669. }
  670. SMARTLIST_FOREACH_END(client);
  671. goto done;
  672. err:
  673. r = -1;
  674. done:
  675. tor_free(client_keys_str);
  676. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  677. if (r<0) {
  678. if (open_cfile)
  679. abort_writing_to_file(open_cfile);
  680. if (open_hfile)
  681. abort_writing_to_file(open_hfile);
  682. return r;
  683. } else {
  684. finish_writing_to_file(open_cfile);
  685. finish_writing_to_file(open_hfile);
  686. }
  687. }
  688. } SMARTLIST_FOREACH_END(s);
  689. return r;
  690. }
  691. /** Return the service whose public key has a digest of <b>digest</b>, or
  692. * NULL if no such service exists.
  693. */
  694. static rend_service_t *
  695. rend_service_get_by_pk_digest(const char* digest)
  696. {
  697. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  698. if (!memcmp(s->pk_digest,digest,DIGEST_LEN))
  699. return s);
  700. return NULL;
  701. }
  702. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  703. * to have good uptime. Else return 0.
  704. */
  705. static int
  706. rend_service_requires_uptime(rend_service_t *service)
  707. {
  708. int i;
  709. rend_service_port_config_t *p;
  710. for (i=0; i < smartlist_len(service->ports); ++i) {
  711. p = smartlist_get(service->ports, i);
  712. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  713. p->virtual_port))
  714. return 1;
  715. }
  716. return 0;
  717. }
  718. /** Check client authorization of a given <b>descriptor_cookie</b> for
  719. * <b>service</b>. Return 1 for success and 0 for failure. */
  720. static int
  721. rend_check_authorization(rend_service_t *service,
  722. const char *descriptor_cookie)
  723. {
  724. rend_authorized_client_t *auth_client = NULL;
  725. tor_assert(service);
  726. tor_assert(descriptor_cookie);
  727. if (!service->clients) {
  728. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  729. "authorized clients configured.");
  730. return 0;
  731. }
  732. /* Look up client authorization by descriptor cookie. */
  733. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  734. if (!memcmp(client->descriptor_cookie, descriptor_cookie,
  735. REND_DESC_COOKIE_LEN)) {
  736. auth_client = client;
  737. break;
  738. }
  739. });
  740. if (!auth_client) {
  741. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  742. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  743. descriptor_cookie, REND_DESC_COOKIE_LEN);
  744. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  745. "Dropping cell!",
  746. descriptor_cookie_base64);
  747. return 0;
  748. }
  749. /* Allow the request. */
  750. log_debug(LD_REND, "Client %s authorized for service %s.",
  751. auth_client->client_name, service->service_id);
  752. return 1;
  753. }
  754. /** Remove elements from <b>service</b>'s replay cache that are old enough to
  755. * be noticed by timestamp checking. */
  756. static void
  757. clean_accepted_intros(rend_service_t *service, time_t now)
  758. {
  759. const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
  760. service->last_cleaned_accepted_intros = now;
  761. if (!service->accepted_intros)
  762. return;
  763. DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
  764. if (*t < cutoff) {
  765. tor_free(t);
  766. MAP_DEL_CURRENT(digest);
  767. }
  768. } DIGESTMAP_FOREACH_END;
  769. }
  770. /******
  771. * Handle cells
  772. ******/
  773. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  774. * rendezvous point.
  775. */
  776. int
  777. rend_service_introduce(origin_circuit_t *circuit, const char *request,
  778. size_t request_len)
  779. {
  780. char *ptr, *r_cookie;
  781. extend_info_t *extend_info = NULL;
  782. char buf[RELAY_PAYLOAD_SIZE];
  783. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  784. rend_service_t *service;
  785. int r, i, v3_shift = 0;
  786. size_t len, keylen;
  787. crypto_dh_env_t *dh = NULL;
  788. origin_circuit_t *launched = NULL;
  789. crypt_path_t *cpath = NULL;
  790. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  791. char hexcookie[9];
  792. int circ_needs_uptime;
  793. int reason = END_CIRC_REASON_TORPROTOCOL;
  794. crypto_pk_env_t *intro_key;
  795. char intro_key_digest[DIGEST_LEN];
  796. int auth_type;
  797. size_t auth_len = 0;
  798. char auth_data[REND_DESC_COOKIE_LEN];
  799. crypto_digest_env_t *digest = NULL;
  800. time_t now = time(NULL);
  801. char diffie_hellman_hash[DIGEST_LEN];
  802. time_t *access_time;
  803. tor_assert(circuit->rend_data);
  804. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  805. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  806. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  807. escaped(serviceid), circuit->_base.n_circ_id);
  808. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  809. log_warn(LD_PROTOCOL,
  810. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  811. circuit->_base.n_circ_id);
  812. return -1;
  813. }
  814. /* min key length plus digest length plus nickname length */
  815. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  816. DH_KEY_LEN+42) {
  817. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  818. circuit->_base.n_circ_id);
  819. return -1;
  820. }
  821. /* look up service depending on circuit. */
  822. service = rend_service_get_by_pk_digest(
  823. circuit->rend_data->rend_pk_digest);
  824. if (!service) {
  825. log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
  826. escaped(serviceid));
  827. return -1;
  828. }
  829. /* use intro key instead of service key. */
  830. intro_key = circuit->intro_key;
  831. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  832. crypto_pk_get_digest(intro_key, intro_key_digest);
  833. if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
  834. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  835. request, REND_SERVICE_ID_LEN);
  836. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  837. escaped(serviceid));
  838. return -1;
  839. }
  840. keylen = crypto_pk_keysize(intro_key);
  841. if (request_len < keylen+DIGEST_LEN) {
  842. log_warn(LD_PROTOCOL,
  843. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  844. return -1;
  845. }
  846. /* Next N bytes is encrypted with service key */
  847. note_crypto_pk_op(REND_SERVER);
  848. r = crypto_pk_private_hybrid_decrypt(
  849. intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
  850. PK_PKCS1_OAEP_PADDING,1);
  851. if (r<0) {
  852. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  853. return -1;
  854. }
  855. len = r;
  856. if (*buf == 3) {
  857. /* Version 3 INTRODUCE2 cell. */
  858. time_t ts = 0;
  859. v3_shift = 1;
  860. auth_type = buf[1];
  861. switch (auth_type) {
  862. case REND_BASIC_AUTH:
  863. /* fall through */
  864. case REND_STEALTH_AUTH:
  865. auth_len = ntohs(get_uint16(buf+2));
  866. if (auth_len != REND_DESC_COOKIE_LEN) {
  867. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  868. (int)auth_len, REND_DESC_COOKIE_LEN);
  869. return -1;
  870. }
  871. memcpy(auth_data, buf+4, sizeof(auth_data));
  872. v3_shift += 2+REND_DESC_COOKIE_LEN;
  873. break;
  874. case REND_NO_AUTH:
  875. break;
  876. default:
  877. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  878. }
  879. /* Check timestamp. */
  880. ts = ntohl(get_uint32(buf+1+v3_shift));
  881. v3_shift += 4;
  882. if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
  883. (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
  884. log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
  885. (now - ts) < 0 ? "old" : "new");
  886. return -1;
  887. }
  888. }
  889. if (*buf == 2 || *buf == 3) {
  890. /* Version 2 INTRODUCE2 cell. */
  891. int klen;
  892. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  893. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  894. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  895. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  896. DIGEST_LEN);
  897. extend_info->nickname[0] = '$';
  898. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  899. extend_info->identity_digest, DIGEST_LEN);
  900. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  901. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  902. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  903. (int)len, *buf);
  904. reason = END_CIRC_REASON_TORPROTOCOL;
  905. goto err;
  906. }
  907. extend_info->onion_key =
  908. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  909. if (!extend_info->onion_key) {
  910. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  911. "INTRODUCE2 cell.", *buf);
  912. reason = END_CIRC_REASON_TORPROTOCOL;
  913. goto err;
  914. }
  915. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  916. len -= v3_shift+7+DIGEST_LEN+2+klen;
  917. } else {
  918. char *rp_nickname;
  919. size_t nickname_field_len;
  920. routerinfo_t *router;
  921. int version;
  922. if (*buf == 1) {
  923. rp_nickname = buf+1;
  924. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  925. version = 1;
  926. } else {
  927. nickname_field_len = MAX_NICKNAME_LEN+1;
  928. rp_nickname = buf;
  929. version = 0;
  930. }
  931. ptr=memchr(rp_nickname,0,nickname_field_len);
  932. if (!ptr || ptr == rp_nickname) {
  933. log_warn(LD_PROTOCOL,
  934. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  935. return -1;
  936. }
  937. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  938. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  939. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  940. return -1;
  941. }
  942. /* Okay, now we know that a nickname is at the start of the buffer. */
  943. ptr = rp_nickname+nickname_field_len;
  944. len -= nickname_field_len;
  945. len -= rp_nickname - buf; /* also remove header space used by version, if
  946. * any */
  947. router = router_get_by_nickname(rp_nickname, 0);
  948. if (!router) {
  949. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  950. escaped_safe_str_client(rp_nickname));
  951. /* XXXX Add a no-such-router reason? */
  952. reason = END_CIRC_REASON_TORPROTOCOL;
  953. goto err;
  954. }
  955. extend_info = extend_info_from_router(router);
  956. }
  957. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  958. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  959. reason = END_CIRC_REASON_TORPROTOCOL;
  960. goto err;
  961. }
  962. r_cookie = ptr;
  963. base16_encode(hexcookie,9,r_cookie,4);
  964. /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
  965. digest = crypto_new_digest_env();
  966. crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
  967. crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
  968. crypto_free_digest_env(digest);
  969. /* Check whether there is a past request with the same Diffie-Hellman,
  970. * part 1. */
  971. if (!service->accepted_intros)
  972. service->accepted_intros = digestmap_new();
  973. access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
  974. if (access_time != NULL) {
  975. log_warn(LD_REND, "Possible replay detected! We received an "
  976. "INTRODUCE2 cell with same first part of "
  977. "Diffie-Hellman handshake %d seconds ago. Dropping "
  978. "cell.",
  979. (int) (now - *access_time));
  980. goto err;
  981. }
  982. /* Add request to access history, including time and hash of Diffie-Hellman,
  983. * part 1, and possibly remove requests from the history that are older than
  984. * one hour. */
  985. access_time = tor_malloc(sizeof(time_t));
  986. *access_time = now;
  987. digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
  988. if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
  989. clean_accepted_intros(service, now);
  990. /* If the service performs client authorization, check included auth data. */
  991. if (service->clients) {
  992. if (auth_len > 0) {
  993. if (rend_check_authorization(service, auth_data)) {
  994. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  995. } else {
  996. log_info(LD_REND, "The authorization data that are contained in "
  997. "the INTRODUCE2 cell are invalid. Dropping cell.");
  998. reason = END_CIRC_REASON_CONNECTFAILED;
  999. goto err;
  1000. }
  1001. } else {
  1002. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1003. "data, but we require client authorization. Dropping cell.");
  1004. reason = END_CIRC_REASON_CONNECTFAILED;
  1005. goto err;
  1006. }
  1007. }
  1008. /* Try DH handshake... */
  1009. dh = crypto_dh_new();
  1010. if (!dh || crypto_dh_generate_public(dh)<0) {
  1011. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1012. "or generate public key.");
  1013. reason = END_CIRC_REASON_INTERNAL;
  1014. goto err;
  1015. }
  1016. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh, ptr+REND_COOKIE_LEN,
  1017. DH_KEY_LEN, keys,
  1018. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1019. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1020. reason = END_CIRC_REASON_INTERNAL;
  1021. goto err;
  1022. }
  1023. circ_needs_uptime = rend_service_requires_uptime(service);
  1024. /* help predict this next time */
  1025. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1026. /* Launch a circuit to alice's chosen rendezvous point.
  1027. */
  1028. for (i=0;i<MAX_REND_FAILURES;i++) {
  1029. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1030. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1031. launched = circuit_launch_by_extend_info(
  1032. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1033. if (launched)
  1034. break;
  1035. }
  1036. if (!launched) { /* give up */
  1037. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1038. "point %s for service %s.",
  1039. escaped_safe_str_client(extend_info->nickname),
  1040. serviceid);
  1041. reason = END_CIRC_REASON_CONNECTFAILED;
  1042. goto err;
  1043. }
  1044. log_info(LD_REND,
  1045. "Accepted intro; launching circuit to %s "
  1046. "(cookie %s) for service %s.",
  1047. escaped_safe_str_client(extend_info->nickname),
  1048. 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_client(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_client(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. char *hs_dir_ip;
  1429. hs_dir = smartlist_get(responsible_dirs, j);
  1430. if (smartlist_digest_isin(renddesc->successful_uploads,
  1431. hs_dir->identity_digest))
  1432. /* Don't upload descriptor if we succeeded in doing so last time. */
  1433. continue;
  1434. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1435. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1436. "hidden service directory '%s'; we don't have its "
  1437. "router descriptor. Queuing for later upload.",
  1438. hs_dir->nickname);
  1439. failed_upload = -1;
  1440. continue;
  1441. }
  1442. /* Send publish request. */
  1443. directory_initiate_command_routerstatus(hs_dir,
  1444. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1445. ROUTER_PURPOSE_GENERAL,
  1446. 1, NULL, desc->desc_str,
  1447. strlen(desc->desc_str), 0);
  1448. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1449. desc->desc_id, DIGEST_LEN);
  1450. hs_dir_ip = tor_dup_ip(hs_dir->addr);
  1451. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1452. "service '%s' with descriptor ID '%s' with validity "
  1453. "of %d seconds to hidden service directory '%s' on "
  1454. "%s:%d.",
  1455. safe_str_client(service_id),
  1456. safe_str_client(desc_id_base32),
  1457. seconds_valid,
  1458. hs_dir->nickname,
  1459. hs_dir_ip,
  1460. hs_dir->or_port);
  1461. tor_free(hs_dir_ip);
  1462. /* Remember successful upload to this router for next time. */
  1463. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1464. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1465. }
  1466. smartlist_clear(responsible_dirs);
  1467. }
  1468. if (!failed_upload) {
  1469. if (renddesc->successful_uploads) {
  1470. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1471. smartlist_free(renddesc->successful_uploads);
  1472. renddesc->successful_uploads = NULL;
  1473. }
  1474. renddesc->all_uploads_performed = 1;
  1475. } else {
  1476. /* Remember which routers worked this time, so that we don't upload the
  1477. * descriptor to them again. */
  1478. if (!renddesc->successful_uploads)
  1479. renddesc->successful_uploads = smartlist_create();
  1480. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1481. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1482. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1483. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1484. }
  1485. });
  1486. }
  1487. smartlist_free(responsible_dirs);
  1488. smartlist_free(successful_uploads);
  1489. }
  1490. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  1491. * and upload it/them to the responsible hidden service directories.
  1492. */
  1493. static void
  1494. upload_service_descriptor(rend_service_t *service)
  1495. {
  1496. time_t now = time(NULL);
  1497. int rendpostperiod;
  1498. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1499. int uploaded = 0;
  1500. rendpostperiod = get_options()->RendPostPeriod;
  1501. /* Upload descriptor? */
  1502. if (get_options()->PublishHidServDescriptors) {
  1503. networkstatus_t *c = networkstatus_get_latest_consensus();
  1504. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1505. int seconds_valid, i, j, num_descs;
  1506. smartlist_t *descs = smartlist_create();
  1507. smartlist_t *client_cookies = smartlist_create();
  1508. /* Either upload a single descriptor (including replicas) or one
  1509. * descriptor for each authorized client in case of authorization
  1510. * type 'stealth'. */
  1511. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1512. smartlist_len(service->clients) : 1;
  1513. for (j = 0; j < num_descs; j++) {
  1514. crypto_pk_env_t *client_key = NULL;
  1515. rend_authorized_client_t *client = NULL;
  1516. smartlist_clear(client_cookies);
  1517. switch (service->auth_type) {
  1518. case REND_NO_AUTH:
  1519. /* Do nothing here. */
  1520. break;
  1521. case REND_BASIC_AUTH:
  1522. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1523. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1524. break;
  1525. case REND_STEALTH_AUTH:
  1526. client = smartlist_get(service->clients, j);
  1527. client_key = client->client_key;
  1528. smartlist_add(client_cookies, client->descriptor_cookie);
  1529. break;
  1530. }
  1531. /* Encode the current descriptor. */
  1532. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1533. now, 0,
  1534. service->auth_type,
  1535. client_key,
  1536. client_cookies);
  1537. if (seconds_valid < 0) {
  1538. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1539. "descriptor; not uploading.");
  1540. smartlist_free(descs);
  1541. smartlist_free(client_cookies);
  1542. return;
  1543. }
  1544. /* Post the current descriptors to the hidden service directories. */
  1545. rend_get_service_id(service->desc->pk, serviceid);
  1546. log_info(LD_REND, "Sending publish request for hidden service %s",
  1547. serviceid);
  1548. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1549. seconds_valid);
  1550. /* Free memory for descriptors. */
  1551. for (i = 0; i < smartlist_len(descs); i++)
  1552. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1553. smartlist_clear(descs);
  1554. /* Update next upload time. */
  1555. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1556. > rendpostperiod)
  1557. service->next_upload_time = now + rendpostperiod;
  1558. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1559. service->next_upload_time = now + seconds_valid + 1;
  1560. else
  1561. service->next_upload_time = now + seconds_valid -
  1562. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1563. /* Post also the next descriptors, if necessary. */
  1564. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1565. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1566. now, 1,
  1567. service->auth_type,
  1568. client_key,
  1569. client_cookies);
  1570. if (seconds_valid < 0) {
  1571. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1572. "descriptor; not uploading.");
  1573. smartlist_free(descs);
  1574. smartlist_free(client_cookies);
  1575. return;
  1576. }
  1577. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1578. seconds_valid);
  1579. /* Free memory for descriptors. */
  1580. for (i = 0; i < smartlist_len(descs); i++)
  1581. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1582. smartlist_clear(descs);
  1583. }
  1584. }
  1585. smartlist_free(descs);
  1586. smartlist_free(client_cookies);
  1587. uploaded = 1;
  1588. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1589. }
  1590. }
  1591. /* If not uploaded, try again in one minute. */
  1592. if (!uploaded)
  1593. service->next_upload_time = now + 60;
  1594. /* Unmark dirty flag of this service. */
  1595. service->desc_is_dirty = 0;
  1596. }
  1597. /** For every service, check how many intro points it currently has, and:
  1598. * - Pick new intro points as necessary.
  1599. * - Launch circuits to any new intro points.
  1600. */
  1601. void
  1602. rend_services_introduce(void)
  1603. {
  1604. int i,j,r;
  1605. routerinfo_t *router;
  1606. rend_service_t *service;
  1607. rend_intro_point_t *intro;
  1608. int changed, prev_intro_nodes;
  1609. smartlist_t *intro_routers;
  1610. time_t now;
  1611. or_options_t *options = get_options();
  1612. intro_routers = smartlist_create();
  1613. now = time(NULL);
  1614. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1615. smartlist_clear(intro_routers);
  1616. service = smartlist_get(rend_service_list, i);
  1617. tor_assert(service);
  1618. changed = 0;
  1619. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1620. /* One period has elapsed; we can try building circuits again. */
  1621. service->intro_period_started = now;
  1622. service->n_intro_circuits_launched = 0;
  1623. } else if (service->n_intro_circuits_launched >=
  1624. MAX_INTRO_CIRCS_PER_PERIOD) {
  1625. /* We have failed too many times in this period; wait for the next
  1626. * one before we try again. */
  1627. continue;
  1628. }
  1629. /* Find out which introduction points we have in progress for this
  1630. service. */
  1631. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1632. intro = smartlist_get(service->intro_nodes, j);
  1633. router = router_get_by_digest(intro->extend_info->identity_digest);
  1634. if (!router || !find_intro_circuit(intro, service->pk_digest)) {
  1635. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1636. intro->extend_info->nickname, service->service_id);
  1637. if (service->desc) {
  1638. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1639. dintro, {
  1640. if (!memcmp(dintro->extend_info->identity_digest,
  1641. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1642. log_info(LD_REND, "The intro point we are giving up on was "
  1643. "included in the last published descriptor. "
  1644. "Marking current descriptor as dirty.");
  1645. service->desc_is_dirty = now;
  1646. }
  1647. });
  1648. }
  1649. rend_intro_point_free(intro);
  1650. smartlist_del(service->intro_nodes,j--);
  1651. changed = 1;
  1652. }
  1653. if (router)
  1654. smartlist_add(intro_routers, router);
  1655. }
  1656. /* We have enough intro points, and the intro points we thought we had were
  1657. * all connected.
  1658. */
  1659. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1660. /* We have all our intro points! Start a fresh period and reset the
  1661. * circuit count. */
  1662. service->intro_period_started = now;
  1663. service->n_intro_circuits_launched = 0;
  1664. continue;
  1665. }
  1666. /* Remember how many introduction circuits we started with. */
  1667. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1668. /* We have enough directory information to start establishing our
  1669. * intro points. We want to end up with three intro points, but if
  1670. * we're just starting, we launch five and pick the first three that
  1671. * complete.
  1672. *
  1673. * The ones after the first three will be converted to 'general'
  1674. * internal circuits in rend_service_intro_has_opened(), and then
  1675. * we'll drop them from the list of intro points next time we
  1676. * go through the above "find out which introduction points we have
  1677. * in progress" loop. */
  1678. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1679. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1680. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1681. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1682. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1683. flags |= CRN_ALLOW_INVALID;
  1684. router = router_choose_random_node(intro_routers,
  1685. options->ExcludeNodes, flags);
  1686. if (!router) {
  1687. log_warn(LD_REND,
  1688. "Could only establish %d introduction points for %s.",
  1689. smartlist_len(service->intro_nodes), service->service_id);
  1690. break;
  1691. }
  1692. changed = 1;
  1693. smartlist_add(intro_routers, router);
  1694. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1695. intro->extend_info = extend_info_from_router(router);
  1696. intro->intro_key = crypto_new_pk_env();
  1697. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1698. smartlist_add(service->intro_nodes, intro);
  1699. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1700. router->nickname, service->service_id);
  1701. }
  1702. /* If there's no need to launch new circuits, stop here. */
  1703. if (!changed)
  1704. continue;
  1705. /* Establish new introduction points. */
  1706. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1707. intro = smartlist_get(service->intro_nodes, j);
  1708. r = rend_service_launch_establish_intro(service, intro);
  1709. if (r<0) {
  1710. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1711. intro->extend_info->nickname, service->service_id);
  1712. }
  1713. }
  1714. }
  1715. smartlist_free(intro_routers);
  1716. }
  1717. /** Regenerate and upload rendezvous service descriptors for all
  1718. * services, if necessary. If the descriptor has been dirty enough
  1719. * for long enough, definitely upload; else only upload when the
  1720. * periodic timeout has expired.
  1721. *
  1722. * For the first upload, pick a random time between now and two periods
  1723. * from now, and pick it independently for each service.
  1724. */
  1725. void
  1726. rend_consider_services_upload(time_t now)
  1727. {
  1728. int i;
  1729. rend_service_t *service;
  1730. int rendpostperiod = get_options()->RendPostPeriod;
  1731. if (!get_options()->PublishHidServDescriptors)
  1732. return;
  1733. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1734. service = smartlist_get(rend_service_list, i);
  1735. if (!service->next_upload_time) { /* never been uploaded yet */
  1736. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1737. * is stable before being published. See comment below. */
  1738. service->next_upload_time =
  1739. now + 30 + crypto_rand_int(2*rendpostperiod);
  1740. }
  1741. if (service->next_upload_time < now ||
  1742. (service->desc_is_dirty &&
  1743. service->desc_is_dirty < now-30)) {
  1744. /* if it's time, or if the directory servers have a wrong service
  1745. * descriptor and ours has been stable for 30 seconds, upload a
  1746. * new one of each format. */
  1747. rend_service_update_descriptor(service);
  1748. upload_service_descriptor(service);
  1749. }
  1750. }
  1751. }
  1752. /** True if the list of available router descriptors might have changed so
  1753. * that we should have a look whether we can republish previously failed
  1754. * rendezvous service descriptors. */
  1755. static int consider_republishing_rend_descriptors = 1;
  1756. /** Called when our internal view of the directory has changed, so that we
  1757. * might have router descriptors of hidden service directories available that
  1758. * we did not have before. */
  1759. void
  1760. rend_hsdir_routers_changed(void)
  1761. {
  1762. consider_republishing_rend_descriptors = 1;
  1763. }
  1764. /** Consider republication of v2 rendezvous service descriptors that failed
  1765. * previously, but without regenerating descriptor contents.
  1766. */
  1767. void
  1768. rend_consider_descriptor_republication(void)
  1769. {
  1770. int i;
  1771. rend_service_t *service;
  1772. if (!consider_republishing_rend_descriptors)
  1773. return;
  1774. consider_republishing_rend_descriptors = 0;
  1775. if (!get_options()->PublishHidServDescriptors)
  1776. return;
  1777. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1778. service = smartlist_get(rend_service_list, i);
  1779. if (service->desc && !service->desc->all_uploads_performed) {
  1780. /* If we failed in uploading a descriptor last time, try again *without*
  1781. * updating the descriptor's contents. */
  1782. upload_service_descriptor(service);
  1783. }
  1784. }
  1785. }
  1786. /** Log the status of introduction points for all rendezvous services
  1787. * at log severity <b>severity</b>.
  1788. */
  1789. void
  1790. rend_service_dump_stats(int severity)
  1791. {
  1792. int i,j;
  1793. rend_service_t *service;
  1794. rend_intro_point_t *intro;
  1795. const char *safe_name;
  1796. origin_circuit_t *circ;
  1797. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1798. service = smartlist_get(rend_service_list, i);
  1799. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1800. service->directory);
  1801. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1802. intro = smartlist_get(service->intro_nodes, j);
  1803. safe_name = safe_str_client(intro->extend_info->nickname);
  1804. circ = find_intro_circuit(intro, service->pk_digest);
  1805. if (!circ) {
  1806. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1807. j, safe_name);
  1808. continue;
  1809. }
  1810. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1811. j, safe_name, circuit_state_to_string(circ->_base.state));
  1812. }
  1813. }
  1814. }
  1815. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1816. * 'circ', and look up the port and address based on conn-\>port.
  1817. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1818. * or 0 for success.
  1819. */
  1820. int
  1821. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1822. origin_circuit_t *circ)
  1823. {
  1824. rend_service_t *service;
  1825. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1826. smartlist_t *matching_ports;
  1827. rend_service_port_config_t *chosen_port;
  1828. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1829. tor_assert(circ->rend_data);
  1830. log_debug(LD_REND,"beginning to hunt for addr/port");
  1831. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1832. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1833. service = rend_service_get_by_pk_digest(
  1834. circ->rend_data->rend_pk_digest);
  1835. if (!service) {
  1836. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1837. "rendezvous circuit %d; closing.",
  1838. serviceid, circ->_base.n_circ_id);
  1839. return -1;
  1840. }
  1841. matching_ports = smartlist_create();
  1842. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1843. {
  1844. if (conn->_base.port == p->virtual_port) {
  1845. smartlist_add(matching_ports, p);
  1846. }
  1847. });
  1848. chosen_port = smartlist_choose(matching_ports);
  1849. smartlist_free(matching_ports);
  1850. if (chosen_port) {
  1851. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1852. conn->_base.port = chosen_port->real_port;
  1853. return 0;
  1854. }
  1855. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1856. conn->_base.port,serviceid);
  1857. return -1;
  1858. }