rendservice.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  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. #include "rendcommon.h"
  10. #include "router.h"
  11. #include "routerlist.h"
  12. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  13. const char *pk_digest);
  14. /** Represents the mapping from a virtual port of a rendezvous service to
  15. * a real port on some IP.
  16. */
  17. typedef struct rend_service_port_config_t {
  18. uint16_t virtual_port;
  19. uint16_t real_port;
  20. tor_addr_t real_addr;
  21. } rend_service_port_config_t;
  22. /** Try to maintain this many intro points per service if possible. */
  23. #define NUM_INTRO_POINTS 3
  24. /** If we can't build our intro circuits, don't retry for this long. */
  25. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  26. /** Don't try to build more than this many circuits before giving up
  27. * for a while.*/
  28. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  29. /** How many times will a hidden service operator attempt to connect to
  30. * a requested rendezvous point before giving up? */
  31. #define MAX_REND_FAILURES 30
  32. /** How many seconds should we spend trying to connect to a requested
  33. * rendezvous point before giving up? */
  34. #define MAX_REND_TIMEOUT 30
  35. /** Represents a single hidden service running at this OP. */
  36. typedef struct rend_service_t {
  37. /* Fields specified in config file */
  38. char *directory; /**< where in the filesystem it stores it */
  39. smartlist_t *ports; /**< List of rend_service_port_config_t */
  40. rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
  41. * authorization is performed. */
  42. smartlist_t *clients; /**< List of rend_authorized_client_t's of
  43. * clients that may access our service. Can be NULL
  44. * if no client authorization is performed. */
  45. /* Other fields */
  46. crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
  47. char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
  48. * '.onion' */
  49. char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
  50. smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
  51. * or are trying to establish. */
  52. time_t intro_period_started; /**< Start of the current period to build
  53. * introduction points. */
  54. int n_intro_circuits_launched; /**< Count of intro circuits we have
  55. * established in this period. */
  56. rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  57. time_t desc_is_dirty; /**< Time at which changes to the hidden service
  58. * descriptor content occurred, or 0 if it's
  59. * up-to-date. */
  60. time_t next_upload_time; /**< Scheduled next hidden service descriptor
  61. * upload time. */
  62. /** Map from digests of Diffie-Hellman values INTRODUCE2 to time_t of when
  63. * they were received; used to prevent replays. */
  64. digestmap_t *accepted_intros;
  65. /** Time at which we last removed expired values from accepted_intros. */
  66. time_t last_cleaned_accepted_intros;
  67. } rend_service_t;
  68. /** A list of rend_service_t's for services run on this OP.
  69. */
  70. static smartlist_t *rend_service_list = NULL;
  71. /** Return the number of rendezvous services we have configured. */
  72. int
  73. num_rend_services(void)
  74. {
  75. if (!rend_service_list)
  76. return 0;
  77. return smartlist_len(rend_service_list);
  78. }
  79. /** Helper: free storage held by a single service authorized client entry. */
  80. static void
  81. rend_authorized_client_free(rend_authorized_client_t *client)
  82. {
  83. if (!client)
  84. return;
  85. if (client->client_key)
  86. crypto_free_pk_env(client->client_key);
  87. tor_free(client->client_name);
  88. tor_free(client);
  89. }
  90. /** Helper for strmap_free. */
  91. static void
  92. rend_authorized_client_strmap_item_free(void *authorized_client)
  93. {
  94. rend_authorized_client_free(authorized_client);
  95. }
  96. /** Release the storage held by <b>service</b>.
  97. */
  98. static void
  99. rend_service_free(rend_service_t *service)
  100. {
  101. if (!service)
  102. return;
  103. tor_free(service->directory);
  104. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  105. smartlist_free(service->ports);
  106. if (service->private_key)
  107. crypto_free_pk_env(service->private_key);
  108. if (service->intro_nodes) {
  109. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  110. rend_intro_point_free(intro););
  111. smartlist_free(service->intro_nodes);
  112. }
  113. rend_service_descriptor_free(service->desc);
  114. if (service->clients) {
  115. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  116. rend_authorized_client_free(c););
  117. smartlist_free(service->clients);
  118. }
  119. digestmap_free(service->accepted_intros, _tor_free);
  120. tor_free(service);
  121. }
  122. /** Release all the storage held in rend_service_list.
  123. */
  124. void
  125. rend_service_free_all(void)
  126. {
  127. if (!rend_service_list)
  128. return;
  129. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  130. rend_service_free(ptr));
  131. smartlist_free(rend_service_list);
  132. rend_service_list = NULL;
  133. }
  134. /** Validate <b>service</b> and add it to rend_service_list if possible.
  135. */
  136. static void
  137. rend_add_service(rend_service_t *service)
  138. {
  139. int i;
  140. rend_service_port_config_t *p;
  141. service->intro_nodes = smartlist_create();
  142. if (service->auth_type != REND_NO_AUTH &&
  143. smartlist_len(service->clients) == 0) {
  144. log_warn(LD_CONFIG, "Hidden service with client authorization but no "
  145. "clients; ignoring.");
  146. rend_service_free(service);
  147. return;
  148. }
  149. if (!smartlist_len(service->ports)) {
  150. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  151. rend_service_free(service);
  152. } else {
  153. smartlist_add(rend_service_list, service);
  154. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  155. service->directory);
  156. for (i = 0; i < smartlist_len(service->ports); ++i) {
  157. p = smartlist_get(service->ports, i);
  158. log_debug(LD_REND,"Service maps port %d to %s:%d",
  159. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  160. }
  161. }
  162. }
  163. /** Parses a real-port to virtual-port mapping and returns a new
  164. * rend_service_port_config_t.
  165. *
  166. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  167. *
  168. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  169. */
  170. static rend_service_port_config_t *
  171. parse_port_config(const char *string)
  172. {
  173. smartlist_t *sl;
  174. int virtport;
  175. int realport;
  176. uint16_t p;
  177. tor_addr_t addr;
  178. const char *addrport;
  179. rend_service_port_config_t *result = NULL;
  180. sl = smartlist_create();
  181. smartlist_split_string(sl, string, " ",
  182. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  183. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  184. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  185. goto err;
  186. }
  187. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  188. if (!virtport) {
  189. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  190. "configuration", escaped(smartlist_get(sl,0)));
  191. goto err;
  192. }
  193. if (smartlist_len(sl) == 1) {
  194. /* No addr:port part; use default. */
  195. realport = virtport;
  196. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  197. } else {
  198. addrport = smartlist_get(sl,1);
  199. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  200. if (tor_addr_port_parse(addrport, &addr, &p)<0) {
  201. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  202. "configuration.");
  203. goto err;
  204. }
  205. realport = p?p:virtport;
  206. } else {
  207. /* No addr:port, no addr -- must be port. */
  208. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  209. if (!realport) {
  210. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  211. "service port configuration.", escaped(addrport));
  212. goto err;
  213. }
  214. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  215. }
  216. }
  217. result = tor_malloc(sizeof(rend_service_port_config_t));
  218. result->virtual_port = virtport;
  219. result->real_port = realport;
  220. tor_addr_copy(&result->real_addr, &addr);
  221. err:
  222. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  223. smartlist_free(sl);
  224. return result;
  225. }
  226. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  227. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  228. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  229. * normal, but don't actually change the configured services.)
  230. */
  231. int
  232. rend_config_services(or_options_t *options, int validate_only)
  233. {
  234. config_line_t *line;
  235. rend_service_t *service = NULL;
  236. rend_service_port_config_t *portcfg;
  237. smartlist_t *old_service_list = NULL;
  238. if (!validate_only) {
  239. old_service_list = rend_service_list;
  240. rend_service_list = smartlist_create();
  241. }
  242. for (line = options->RendConfigLines; line; line = line->next) {
  243. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  244. if (service) { /* register the one we just finished parsing */
  245. if (validate_only)
  246. rend_service_free(service);
  247. else
  248. rend_add_service(service);
  249. }
  250. service = tor_malloc_zero(sizeof(rend_service_t));
  251. service->directory = tor_strdup(line->value);
  252. service->ports = smartlist_create();
  253. service->intro_period_started = time(NULL);
  254. continue;
  255. }
  256. if (!service) {
  257. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  258. line->key);
  259. rend_service_free(service);
  260. return -1;
  261. }
  262. if (!strcasecmp(line->key, "HiddenServicePort")) {
  263. portcfg = parse_port_config(line->value);
  264. if (!portcfg) {
  265. rend_service_free(service);
  266. return -1;
  267. }
  268. smartlist_add(service->ports, portcfg);
  269. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  270. /* Parse auth type and comma-separated list of client names and add a
  271. * rend_authorized_client_t for each client to the service's list
  272. * of authorized clients. */
  273. smartlist_t *type_names_split, *clients;
  274. const char *authname;
  275. int num_clients;
  276. if (service->auth_type != REND_NO_AUTH) {
  277. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  278. "lines for a single service.");
  279. rend_service_free(service);
  280. return -1;
  281. }
  282. type_names_split = smartlist_create();
  283. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  284. if (smartlist_len(type_names_split) < 1) {
  285. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  286. "should have been prevented when parsing the "
  287. "configuration.");
  288. smartlist_free(type_names_split);
  289. rend_service_free(service);
  290. return -1;
  291. }
  292. authname = smartlist_get(type_names_split, 0);
  293. if (!strcasecmp(authname, "basic")) {
  294. service->auth_type = REND_BASIC_AUTH;
  295. } else if (!strcasecmp(authname, "stealth")) {
  296. service->auth_type = REND_STEALTH_AUTH;
  297. } else {
  298. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  299. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  300. "are recognized.",
  301. (char *) smartlist_get(type_names_split, 0));
  302. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  303. smartlist_free(type_names_split);
  304. rend_service_free(service);
  305. return -1;
  306. }
  307. service->clients = smartlist_create();
  308. if (smartlist_len(type_names_split) < 2) {
  309. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  310. "auth-type '%s', but no client names.",
  311. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  312. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  313. smartlist_free(type_names_split);
  314. continue;
  315. }
  316. clients = smartlist_create();
  317. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  318. ",", SPLIT_SKIP_SPACE, 0);
  319. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  320. smartlist_free(type_names_split);
  321. /* Remove duplicate client names. */
  322. num_clients = smartlist_len(clients);
  323. smartlist_sort_strings(clients);
  324. smartlist_uniq_strings(clients);
  325. if (smartlist_len(clients) < num_clients) {
  326. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  327. "duplicate client name(s); removing.",
  328. num_clients - smartlist_len(clients));
  329. num_clients = smartlist_len(clients);
  330. }
  331. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  332. {
  333. rend_authorized_client_t *client;
  334. size_t len = strlen(client_name);
  335. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  336. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  337. "illegal client name: '%s'. Length must be "
  338. "between 1 and %d characters.",
  339. client_name, REND_CLIENTNAME_MAX_LEN);
  340. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  341. smartlist_free(clients);
  342. rend_service_free(service);
  343. return -1;
  344. }
  345. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  346. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  347. "illegal client name: '%s'. Valid "
  348. "characters are [A-Za-z0-9+-_].",
  349. client_name);
  350. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  351. smartlist_free(clients);
  352. rend_service_free(service);
  353. return -1;
  354. }
  355. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  356. client->client_name = tor_strdup(client_name);
  357. smartlist_add(service->clients, client);
  358. log_debug(LD_REND, "Adding client name '%s'", client_name);
  359. }
  360. SMARTLIST_FOREACH_END(client_name);
  361. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  362. smartlist_free(clients);
  363. /* Ensure maximum number of clients. */
  364. if ((service->auth_type == REND_BASIC_AUTH &&
  365. smartlist_len(service->clients) > 512) ||
  366. (service->auth_type == REND_STEALTH_AUTH &&
  367. smartlist_len(service->clients) > 16)) {
  368. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  369. "client authorization entries, but only a "
  370. "maximum of %d entries is allowed for "
  371. "authorization type '%s'.",
  372. smartlist_len(service->clients),
  373. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  374. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  375. rend_service_free(service);
  376. return -1;
  377. }
  378. } else {
  379. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  380. if (strcmp(line->value, "2")) {
  381. log_warn(LD_CONFIG,
  382. "The only supported HiddenServiceVersion is 2.");
  383. rend_service_free(service);
  384. return -1;
  385. }
  386. }
  387. }
  388. if (service) {
  389. if (validate_only)
  390. rend_service_free(service);
  391. else
  392. rend_add_service(service);
  393. }
  394. /* If this is a reload and there were hidden services configured before,
  395. * keep the introduction points that are still needed and close the
  396. * other ones. */
  397. if (old_service_list && !validate_only) {
  398. smartlist_t *surviving_services = smartlist_create();
  399. circuit_t *circ;
  400. /* Copy introduction points to new services. */
  401. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  402. * probably ok? */
  403. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
  404. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  405. if (!strcmp(old->directory, new->directory)) {
  406. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  407. smartlist_clear(old->intro_nodes);
  408. smartlist_add(surviving_services, old);
  409. break;
  410. }
  411. });
  412. });
  413. /* Close introduction circuits of services we don't serve anymore. */
  414. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  415. * so we could just iterate over the list of services to close, but
  416. * once again, this isn't critical-path code. */
  417. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  418. if (!circ->marked_for_close &&
  419. circ->state == CIRCUIT_STATE_OPEN &&
  420. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  421. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  422. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  423. int keep_it = 0;
  424. tor_assert(oc->rend_data);
  425. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  426. if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  427. DIGEST_LEN)) {
  428. keep_it = 1;
  429. break;
  430. }
  431. });
  432. if (keep_it)
  433. continue;
  434. log_info(LD_REND, "Closing intro point %s for service %s.",
  435. safe_str_client(oc->build_state->chosen_exit->nickname),
  436. oc->rend_data->onion_address);
  437. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  438. /* XXXX Is there another reason we should use here? */
  439. }
  440. }
  441. smartlist_free(surviving_services);
  442. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  443. rend_service_free(ptr));
  444. smartlist_free(old_service_list);
  445. }
  446. return 0;
  447. }
  448. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  449. * the other fields in service.
  450. */
  451. static void
  452. rend_service_update_descriptor(rend_service_t *service)
  453. {
  454. rend_service_descriptor_t *d;
  455. origin_circuit_t *circ;
  456. int i;
  457. rend_service_descriptor_free(service->desc);
  458. service->desc = NULL;
  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_client(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(LOG_PROTOCOL_WARN, dh, ptr+REND_COOKIE_LEN,
  1020. DH_KEY_LEN, keys,
  1021. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1022. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1023. reason = END_CIRC_REASON_INTERNAL;
  1024. goto err;
  1025. }
  1026. circ_needs_uptime = rend_service_requires_uptime(service);
  1027. /* help predict this next time */
  1028. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1029. /* Launch a circuit to alice's chosen rendezvous point.
  1030. */
  1031. for (i=0;i<MAX_REND_FAILURES;i++) {
  1032. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1033. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1034. launched = circuit_launch_by_extend_info(
  1035. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1036. if (launched)
  1037. break;
  1038. }
  1039. if (!launched) { /* give up */
  1040. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1041. "point %s for service %s.",
  1042. escaped_safe_str_client(extend_info->nickname),
  1043. serviceid);
  1044. reason = END_CIRC_REASON_CONNECTFAILED;
  1045. goto err;
  1046. }
  1047. log_info(LD_REND,
  1048. "Accepted intro; launching circuit to %s "
  1049. "(cookie %s) for service %s.",
  1050. escaped_safe_str_client(extend_info->nickname),
  1051. hexcookie, serviceid);
  1052. tor_assert(launched->build_state);
  1053. /* Fill in the circuit's state. */
  1054. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1055. memcpy(launched->rend_data->rend_pk_digest,
  1056. circuit->rend_data->rend_pk_digest,
  1057. DIGEST_LEN);
  1058. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1059. strlcpy(launched->rend_data->onion_address, service->service_id,
  1060. sizeof(launched->rend_data->onion_address));
  1061. launched->build_state->pending_final_cpath = cpath =
  1062. tor_malloc_zero(sizeof(crypt_path_t));
  1063. cpath->magic = CRYPT_PATH_MAGIC;
  1064. launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
  1065. cpath->dh_handshake_state = dh;
  1066. dh = NULL;
  1067. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1068. goto err;
  1069. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1070. if (extend_info) extend_info_free(extend_info);
  1071. return 0;
  1072. err:
  1073. if (dh) crypto_dh_free(dh);
  1074. if (launched)
  1075. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1076. if (extend_info) extend_info_free(extend_info);
  1077. return -1;
  1078. }
  1079. /** Called when we fail building a rendezvous circuit at some point other
  1080. * than the last hop: launches a new circuit to the same rendezvous point.
  1081. */
  1082. void
  1083. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1084. {
  1085. origin_circuit_t *newcirc;
  1086. cpath_build_state_t *newstate, *oldstate;
  1087. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1088. if (!oldcirc->build_state ||
  1089. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1090. oldcirc->build_state->expiry_time < time(NULL)) {
  1091. log_info(LD_REND,
  1092. "Attempt to build circuit to %s for rendezvous has failed "
  1093. "too many times or expired; giving up.",
  1094. oldcirc->build_state ?
  1095. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  1096. return;
  1097. }
  1098. oldstate = oldcirc->build_state;
  1099. tor_assert(oldstate);
  1100. if (oldstate->pending_final_cpath == NULL) {
  1101. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1102. "Initiator will retry.");
  1103. return;
  1104. }
  1105. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1106. oldstate->chosen_exit->nickname);
  1107. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1108. oldstate->chosen_exit,
  1109. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1110. if (!newcirc) {
  1111. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1112. oldstate->chosen_exit->nickname);
  1113. return;
  1114. }
  1115. newstate = newcirc->build_state;
  1116. tor_assert(newstate);
  1117. newstate->failure_count = oldstate->failure_count+1;
  1118. newstate->expiry_time = oldstate->expiry_time;
  1119. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  1120. oldstate->pending_final_cpath = NULL;
  1121. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1122. }
  1123. /** Launch a circuit to serve as an introduction point for the service
  1124. * <b>service</b> at the introduction point <b>nickname</b>
  1125. */
  1126. static int
  1127. rend_service_launch_establish_intro(rend_service_t *service,
  1128. rend_intro_point_t *intro)
  1129. {
  1130. origin_circuit_t *launched;
  1131. log_info(LD_REND,
  1132. "Launching circuit to introduction point %s for service %s",
  1133. escaped_safe_str_client(intro->extend_info->nickname),
  1134. service->service_id);
  1135. rep_hist_note_used_internal(time(NULL), 1, 0);
  1136. ++service->n_intro_circuits_launched;
  1137. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1138. intro->extend_info,
  1139. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1140. if (!launched) {
  1141. log_info(LD_REND,
  1142. "Can't launch circuit to establish introduction at %s.",
  1143. escaped_safe_str_client(intro->extend_info->nickname));
  1144. return -1;
  1145. }
  1146. if (memcmp(intro->extend_info->identity_digest,
  1147. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1148. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1149. base16_encode(cann, sizeof(cann),
  1150. launched->build_state->chosen_exit->identity_digest,
  1151. DIGEST_LEN);
  1152. base16_encode(orig, sizeof(orig),
  1153. intro->extend_info->identity_digest, DIGEST_LEN);
  1154. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1155. "but we requested an intro circuit to $%s. Updating "
  1156. "our service.", cann, orig);
  1157. extend_info_free(intro->extend_info);
  1158. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1159. }
  1160. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1161. strlcpy(launched->rend_data->onion_address, service->service_id,
  1162. sizeof(launched->rend_data->onion_address));
  1163. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1164. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1165. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1166. rend_service_intro_has_opened(launched);
  1167. return 0;
  1168. }
  1169. /** Return the number of introduction points that are or have been
  1170. * established for the given service address in <b>query</b>. */
  1171. static int
  1172. count_established_intro_points(const char *query)
  1173. {
  1174. int num_ipos = 0;
  1175. circuit_t *circ;
  1176. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1177. if (!circ->marked_for_close &&
  1178. circ->state == CIRCUIT_STATE_OPEN &&
  1179. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1180. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1181. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1182. if (oc->rend_data &&
  1183. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1184. num_ipos++;
  1185. }
  1186. }
  1187. return num_ipos;
  1188. }
  1189. /** Called when we're done building a circuit to an introduction point:
  1190. * sends a RELAY_ESTABLISH_INTRO cell.
  1191. */
  1192. void
  1193. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1194. {
  1195. rend_service_t *service;
  1196. size_t len;
  1197. int r;
  1198. char buf[RELAY_PAYLOAD_SIZE];
  1199. char auth[DIGEST_LEN + 9];
  1200. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1201. int reason = END_CIRC_REASON_TORPROTOCOL;
  1202. crypto_pk_env_t *intro_key;
  1203. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1204. tor_assert(circuit->cpath);
  1205. tor_assert(circuit->rend_data);
  1206. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1207. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1208. service = rend_service_get_by_pk_digest(
  1209. circuit->rend_data->rend_pk_digest);
  1210. if (!service) {
  1211. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1212. serviceid, circuit->_base.n_circ_id);
  1213. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1214. goto err;
  1215. }
  1216. /* If we already have enough introduction circuits for this service,
  1217. * redefine this one as a general circuit. */
  1218. if (count_established_intro_points(serviceid) > NUM_INTRO_POINTS) {
  1219. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1220. "circuit, but we already have enough. Redefining purpose to "
  1221. "general.");
  1222. TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1223. circuit_has_opened(circuit);
  1224. return;
  1225. }
  1226. log_info(LD_REND,
  1227. "Established circuit %d as introduction point for service %s",
  1228. circuit->_base.n_circ_id, serviceid);
  1229. /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
  1230. intro_key = circuit->intro_key;
  1231. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1232. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1233. RELAY_PAYLOAD_SIZE-2);
  1234. if (r < 0) {
  1235. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1236. reason = END_CIRC_REASON_INTERNAL;
  1237. goto err;
  1238. }
  1239. len = r;
  1240. set_uint16(buf, htons((uint16_t)len));
  1241. len += 2;
  1242. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1243. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1244. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1245. goto err;
  1246. len += 20;
  1247. note_crypto_pk_op(REND_SERVER);
  1248. r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
  1249. if (r<0) {
  1250. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1251. reason = END_CIRC_REASON_INTERNAL;
  1252. goto err;
  1253. }
  1254. len += r;
  1255. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1256. RELAY_COMMAND_ESTABLISH_INTRO,
  1257. buf, len, circuit->cpath->prev)<0) {
  1258. log_info(LD_GENERAL,
  1259. "Couldn't send introduction request for service %s on circuit %d",
  1260. serviceid, circuit->_base.n_circ_id);
  1261. reason = END_CIRC_REASON_INTERNAL;
  1262. goto err;
  1263. }
  1264. return;
  1265. err:
  1266. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1267. }
  1268. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1269. * live introduction point, and note that the service descriptor is
  1270. * now out-of-date.*/
  1271. int
  1272. rend_service_intro_established(origin_circuit_t *circuit, const char *request,
  1273. size_t request_len)
  1274. {
  1275. rend_service_t *service;
  1276. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1277. (void) request;
  1278. (void) request_len;
  1279. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1280. log_warn(LD_PROTOCOL,
  1281. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1282. goto err;
  1283. }
  1284. tor_assert(circuit->rend_data);
  1285. service = rend_service_get_by_pk_digest(
  1286. circuit->rend_data->rend_pk_digest);
  1287. if (!service) {
  1288. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1289. circuit->_base.n_circ_id);
  1290. goto err;
  1291. }
  1292. service->desc_is_dirty = time(NULL);
  1293. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1294. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1295. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1296. log_info(LD_REND,
  1297. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1298. circuit->_base.n_circ_id, serviceid);
  1299. return 0;
  1300. err:
  1301. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1302. return -1;
  1303. }
  1304. /** Called once a circuit to a rendezvous point is established: sends a
  1305. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1306. */
  1307. void
  1308. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1309. {
  1310. rend_service_t *service;
  1311. char buf[RELAY_PAYLOAD_SIZE];
  1312. crypt_path_t *hop;
  1313. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1314. char hexcookie[9];
  1315. int reason;
  1316. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1317. tor_assert(circuit->cpath);
  1318. tor_assert(circuit->build_state);
  1319. tor_assert(circuit->rend_data);
  1320. hop = circuit->build_state->pending_final_cpath;
  1321. tor_assert(hop);
  1322. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1323. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1324. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1325. log_info(LD_REND,
  1326. "Done building circuit %d to rendezvous with "
  1327. "cookie %s for service %s",
  1328. circuit->_base.n_circ_id, hexcookie, serviceid);
  1329. service = rend_service_get_by_pk_digest(
  1330. circuit->rend_data->rend_pk_digest);
  1331. if (!service) {
  1332. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1333. "introduction circuit.");
  1334. reason = END_CIRC_REASON_INTERNAL;
  1335. goto err;
  1336. }
  1337. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1338. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1339. if (crypto_dh_get_public(hop->dh_handshake_state,
  1340. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1341. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1342. reason = END_CIRC_REASON_INTERNAL;
  1343. goto err;
  1344. }
  1345. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1346. DIGEST_LEN);
  1347. /* Send the cell */
  1348. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1349. RELAY_COMMAND_RENDEZVOUS1,
  1350. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1351. circuit->cpath->prev)<0) {
  1352. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1353. reason = END_CIRC_REASON_INTERNAL;
  1354. goto err;
  1355. }
  1356. crypto_dh_free(hop->dh_handshake_state);
  1357. hop->dh_handshake_state = NULL;
  1358. /* Append the cpath entry. */
  1359. hop->state = CPATH_STATE_OPEN;
  1360. /* set the windows to default. these are the windows
  1361. * that bob thinks alice has.
  1362. */
  1363. hop->package_window = circuit_initial_package_window();
  1364. hop->deliver_window = CIRCWINDOW_START;
  1365. onion_append_to_cpath(&circuit->cpath, hop);
  1366. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1367. /* Change the circuit purpose. */
  1368. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1369. return;
  1370. err:
  1371. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1372. }
  1373. /*
  1374. * Manage introduction points
  1375. */
  1376. /** Return the (possibly non-open) introduction circuit ending at
  1377. * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
  1378. * (<b>desc_version</b> is ignored). Return NULL if no such service is
  1379. * found.
  1380. */
  1381. static origin_circuit_t *
  1382. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
  1383. {
  1384. origin_circuit_t *circ = NULL;
  1385. tor_assert(intro);
  1386. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1387. CIRCUIT_PURPOSE_S_INTRO))) {
  1388. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1389. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1390. circ->rend_data) {
  1391. return circ;
  1392. }
  1393. }
  1394. circ = NULL;
  1395. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1396. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1397. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1398. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1399. circ->rend_data) {
  1400. return circ;
  1401. }
  1402. }
  1403. return NULL;
  1404. }
  1405. /** Determine the responsible hidden service directories for the
  1406. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1407. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1408. * purposes. */
  1409. static void
  1410. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1411. smartlist_t *descs, const char *service_id,
  1412. int seconds_valid)
  1413. {
  1414. int i, j, failed_upload = 0;
  1415. smartlist_t *responsible_dirs = smartlist_create();
  1416. smartlist_t *successful_uploads = smartlist_create();
  1417. routerstatus_t *hs_dir;
  1418. for (i = 0; i < smartlist_len(descs); i++) {
  1419. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1420. /* Determine responsible dirs. */
  1421. if (hid_serv_get_responsible_directories(responsible_dirs,
  1422. desc->desc_id) < 0) {
  1423. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1424. "directories to post descriptors to.");
  1425. smartlist_free(responsible_dirs);
  1426. smartlist_free(successful_uploads);
  1427. return;
  1428. }
  1429. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1430. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1431. char *hs_dir_ip;
  1432. hs_dir = smartlist_get(responsible_dirs, j);
  1433. if (smartlist_digest_isin(renddesc->successful_uploads,
  1434. hs_dir->identity_digest))
  1435. /* Don't upload descriptor if we succeeded in doing so last time. */
  1436. continue;
  1437. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1438. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1439. "hidden service directory '%s'; we don't have its "
  1440. "router descriptor. Queuing for later upload.",
  1441. hs_dir->nickname);
  1442. failed_upload = -1;
  1443. continue;
  1444. }
  1445. /* Send publish request. */
  1446. directory_initiate_command_routerstatus(hs_dir,
  1447. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1448. ROUTER_PURPOSE_GENERAL,
  1449. 1, NULL, desc->desc_str,
  1450. strlen(desc->desc_str), 0);
  1451. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1452. desc->desc_id, DIGEST_LEN);
  1453. hs_dir_ip = tor_dup_ip(hs_dir->addr);
  1454. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1455. "service '%s' with descriptor ID '%s' with validity "
  1456. "of %d seconds to hidden service directory '%s' on "
  1457. "%s:%d.",
  1458. safe_str_client(service_id),
  1459. safe_str_client(desc_id_base32),
  1460. seconds_valid,
  1461. hs_dir->nickname,
  1462. hs_dir_ip,
  1463. hs_dir->or_port);
  1464. tor_free(hs_dir_ip);
  1465. /* Remember successful upload to this router for next time. */
  1466. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1467. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1468. }
  1469. smartlist_clear(responsible_dirs);
  1470. }
  1471. if (!failed_upload) {
  1472. if (renddesc->successful_uploads) {
  1473. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1474. smartlist_free(renddesc->successful_uploads);
  1475. renddesc->successful_uploads = NULL;
  1476. }
  1477. renddesc->all_uploads_performed = 1;
  1478. } else {
  1479. /* Remember which routers worked this time, so that we don't upload the
  1480. * descriptor to them again. */
  1481. if (!renddesc->successful_uploads)
  1482. renddesc->successful_uploads = smartlist_create();
  1483. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1484. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1485. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1486. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1487. }
  1488. });
  1489. }
  1490. smartlist_free(responsible_dirs);
  1491. smartlist_free(successful_uploads);
  1492. }
  1493. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  1494. * and upload it/them to the responsible hidden service directories.
  1495. */
  1496. static void
  1497. upload_service_descriptor(rend_service_t *service)
  1498. {
  1499. time_t now = time(NULL);
  1500. int rendpostperiod;
  1501. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1502. int uploaded = 0;
  1503. rendpostperiod = get_options()->RendPostPeriod;
  1504. /* Upload descriptor? */
  1505. if (get_options()->PublishHidServDescriptors) {
  1506. networkstatus_t *c = networkstatus_get_latest_consensus();
  1507. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1508. int seconds_valid, i, j, num_descs;
  1509. smartlist_t *descs = smartlist_create();
  1510. smartlist_t *client_cookies = smartlist_create();
  1511. /* Either upload a single descriptor (including replicas) or one
  1512. * descriptor for each authorized client in case of authorization
  1513. * type 'stealth'. */
  1514. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1515. smartlist_len(service->clients) : 1;
  1516. for (j = 0; j < num_descs; j++) {
  1517. crypto_pk_env_t *client_key = NULL;
  1518. rend_authorized_client_t *client = NULL;
  1519. smartlist_clear(client_cookies);
  1520. switch (service->auth_type) {
  1521. case REND_NO_AUTH:
  1522. /* Do nothing here. */
  1523. break;
  1524. case REND_BASIC_AUTH:
  1525. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1526. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1527. break;
  1528. case REND_STEALTH_AUTH:
  1529. client = smartlist_get(service->clients, j);
  1530. client_key = client->client_key;
  1531. smartlist_add(client_cookies, client->descriptor_cookie);
  1532. break;
  1533. }
  1534. /* Encode the current descriptor. */
  1535. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1536. now, 0,
  1537. service->auth_type,
  1538. client_key,
  1539. client_cookies);
  1540. if (seconds_valid < 0) {
  1541. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1542. "descriptor; not uploading.");
  1543. smartlist_free(descs);
  1544. smartlist_free(client_cookies);
  1545. return;
  1546. }
  1547. /* Post the current descriptors to the hidden service directories. */
  1548. rend_get_service_id(service->desc->pk, serviceid);
  1549. log_info(LD_REND, "Sending publish request for hidden service %s",
  1550. serviceid);
  1551. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1552. seconds_valid);
  1553. /* Free memory for descriptors. */
  1554. for (i = 0; i < smartlist_len(descs); i++)
  1555. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1556. smartlist_clear(descs);
  1557. /* Update next upload time. */
  1558. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1559. > rendpostperiod)
  1560. service->next_upload_time = now + rendpostperiod;
  1561. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1562. service->next_upload_time = now + seconds_valid + 1;
  1563. else
  1564. service->next_upload_time = now + seconds_valid -
  1565. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1566. /* Post also the next descriptors, if necessary. */
  1567. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1568. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1569. now, 1,
  1570. service->auth_type,
  1571. client_key,
  1572. client_cookies);
  1573. if (seconds_valid < 0) {
  1574. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1575. "descriptor; not uploading.");
  1576. smartlist_free(descs);
  1577. smartlist_free(client_cookies);
  1578. return;
  1579. }
  1580. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1581. seconds_valid);
  1582. /* Free memory for descriptors. */
  1583. for (i = 0; i < smartlist_len(descs); i++)
  1584. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1585. smartlist_clear(descs);
  1586. }
  1587. }
  1588. smartlist_free(descs);
  1589. smartlist_free(client_cookies);
  1590. uploaded = 1;
  1591. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1592. }
  1593. }
  1594. /* If not uploaded, try again in one minute. */
  1595. if (!uploaded)
  1596. service->next_upload_time = now + 60;
  1597. /* Unmark dirty flag of this service. */
  1598. service->desc_is_dirty = 0;
  1599. }
  1600. /** For every service, check how many intro points it currently has, and:
  1601. * - Pick new intro points as necessary.
  1602. * - Launch circuits to any new intro points.
  1603. */
  1604. void
  1605. rend_services_introduce(void)
  1606. {
  1607. int i,j,r;
  1608. routerinfo_t *router;
  1609. rend_service_t *service;
  1610. rend_intro_point_t *intro;
  1611. int changed, prev_intro_nodes;
  1612. smartlist_t *intro_routers;
  1613. time_t now;
  1614. or_options_t *options = get_options();
  1615. intro_routers = smartlist_create();
  1616. now = time(NULL);
  1617. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1618. smartlist_clear(intro_routers);
  1619. service = smartlist_get(rend_service_list, i);
  1620. tor_assert(service);
  1621. changed = 0;
  1622. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1623. /* One period has elapsed; we can try building circuits again. */
  1624. service->intro_period_started = now;
  1625. service->n_intro_circuits_launched = 0;
  1626. } else if (service->n_intro_circuits_launched >=
  1627. MAX_INTRO_CIRCS_PER_PERIOD) {
  1628. /* We have failed too many times in this period; wait for the next
  1629. * one before we try again. */
  1630. continue;
  1631. }
  1632. /* Find out which introduction points we have in progress for this
  1633. service. */
  1634. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1635. intro = smartlist_get(service->intro_nodes, j);
  1636. router = router_get_by_digest(intro->extend_info->identity_digest);
  1637. if (!router || !find_intro_circuit(intro, service->pk_digest)) {
  1638. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1639. intro->extend_info->nickname, service->service_id);
  1640. if (service->desc) {
  1641. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1642. dintro, {
  1643. if (!memcmp(dintro->extend_info->identity_digest,
  1644. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1645. log_info(LD_REND, "The intro point we are giving up on was "
  1646. "included in the last published descriptor. "
  1647. "Marking current descriptor as dirty.");
  1648. service->desc_is_dirty = now;
  1649. }
  1650. });
  1651. }
  1652. rend_intro_point_free(intro);
  1653. smartlist_del(service->intro_nodes,j--);
  1654. changed = 1;
  1655. }
  1656. if (router)
  1657. smartlist_add(intro_routers, router);
  1658. }
  1659. /* We have enough intro points, and the intro points we thought we had were
  1660. * all connected.
  1661. */
  1662. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1663. /* We have all our intro points! Start a fresh period and reset the
  1664. * circuit count. */
  1665. service->intro_period_started = now;
  1666. service->n_intro_circuits_launched = 0;
  1667. continue;
  1668. }
  1669. /* Remember how many introduction circuits we started with. */
  1670. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1671. /* We have enough directory information to start establishing our
  1672. * intro points. We want to end up with three intro points, but if
  1673. * we're just starting, we launch five and pick the first three that
  1674. * complete.
  1675. *
  1676. * The ones after the first three will be converted to 'general'
  1677. * internal circuits in rend_service_intro_has_opened(), and then
  1678. * we'll drop them from the list of intro points next time we
  1679. * go through the above "find out which introduction points we have
  1680. * in progress" loop. */
  1681. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1682. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1683. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1684. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1685. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1686. flags |= CRN_ALLOW_INVALID;
  1687. router = router_choose_random_node(intro_routers,
  1688. options->ExcludeNodes, flags);
  1689. if (!router) {
  1690. log_warn(LD_REND,
  1691. "Could only establish %d introduction points for %s.",
  1692. smartlist_len(service->intro_nodes), service->service_id);
  1693. break;
  1694. }
  1695. changed = 1;
  1696. smartlist_add(intro_routers, router);
  1697. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1698. intro->extend_info = extend_info_from_router(router);
  1699. intro->intro_key = crypto_new_pk_env();
  1700. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1701. smartlist_add(service->intro_nodes, intro);
  1702. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1703. router->nickname, service->service_id);
  1704. }
  1705. /* If there's no need to launch new circuits, stop here. */
  1706. if (!changed)
  1707. continue;
  1708. /* Establish new introduction points. */
  1709. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1710. intro = smartlist_get(service->intro_nodes, j);
  1711. r = rend_service_launch_establish_intro(service, intro);
  1712. if (r<0) {
  1713. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1714. intro->extend_info->nickname, service->service_id);
  1715. }
  1716. }
  1717. }
  1718. smartlist_free(intro_routers);
  1719. }
  1720. /** Regenerate and upload rendezvous service descriptors for all
  1721. * services, if necessary. If the descriptor has been dirty enough
  1722. * for long enough, definitely upload; else only upload when the
  1723. * periodic timeout has expired.
  1724. *
  1725. * For the first upload, pick a random time between now and two periods
  1726. * from now, and pick it independently for each service.
  1727. */
  1728. void
  1729. rend_consider_services_upload(time_t now)
  1730. {
  1731. int i;
  1732. rend_service_t *service;
  1733. int rendpostperiod = get_options()->RendPostPeriod;
  1734. if (!get_options()->PublishHidServDescriptors)
  1735. return;
  1736. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1737. service = smartlist_get(rend_service_list, i);
  1738. if (!service->next_upload_time) { /* never been uploaded yet */
  1739. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1740. * is stable before being published. See comment below. */
  1741. service->next_upload_time =
  1742. now + 30 + crypto_rand_int(2*rendpostperiod);
  1743. }
  1744. if (service->next_upload_time < now ||
  1745. (service->desc_is_dirty &&
  1746. service->desc_is_dirty < now-30)) {
  1747. /* if it's time, or if the directory servers have a wrong service
  1748. * descriptor and ours has been stable for 30 seconds, upload a
  1749. * new one of each format. */
  1750. rend_service_update_descriptor(service);
  1751. upload_service_descriptor(service);
  1752. }
  1753. }
  1754. }
  1755. /** True if the list of available router descriptors might have changed so
  1756. * that we should have a look whether we can republish previously failed
  1757. * rendezvous service descriptors. */
  1758. static int consider_republishing_rend_descriptors = 1;
  1759. /** Called when our internal view of the directory has changed, so that we
  1760. * might have router descriptors of hidden service directories available that
  1761. * we did not have before. */
  1762. void
  1763. rend_hsdir_routers_changed(void)
  1764. {
  1765. consider_republishing_rend_descriptors = 1;
  1766. }
  1767. /** Consider republication of v2 rendezvous service descriptors that failed
  1768. * previously, but without regenerating descriptor contents.
  1769. */
  1770. void
  1771. rend_consider_descriptor_republication(void)
  1772. {
  1773. int i;
  1774. rend_service_t *service;
  1775. if (!consider_republishing_rend_descriptors)
  1776. return;
  1777. consider_republishing_rend_descriptors = 0;
  1778. if (!get_options()->PublishHidServDescriptors)
  1779. return;
  1780. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1781. service = smartlist_get(rend_service_list, i);
  1782. if (service->desc && !service->desc->all_uploads_performed) {
  1783. /* If we failed in uploading a descriptor last time, try again *without*
  1784. * updating the descriptor's contents. */
  1785. upload_service_descriptor(service);
  1786. }
  1787. }
  1788. }
  1789. /** Log the status of introduction points for all rendezvous services
  1790. * at log severity <b>severity</b>.
  1791. */
  1792. void
  1793. rend_service_dump_stats(int severity)
  1794. {
  1795. int i,j;
  1796. rend_service_t *service;
  1797. rend_intro_point_t *intro;
  1798. const char *safe_name;
  1799. origin_circuit_t *circ;
  1800. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1801. service = smartlist_get(rend_service_list, i);
  1802. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1803. service->directory);
  1804. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1805. intro = smartlist_get(service->intro_nodes, j);
  1806. safe_name = safe_str_client(intro->extend_info->nickname);
  1807. circ = find_intro_circuit(intro, service->pk_digest);
  1808. if (!circ) {
  1809. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1810. j, safe_name);
  1811. continue;
  1812. }
  1813. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1814. j, safe_name, circuit_state_to_string(circ->_base.state));
  1815. }
  1816. }
  1817. }
  1818. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1819. * 'circ', and look up the port and address based on conn-\>port.
  1820. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1821. * or 0 for success.
  1822. */
  1823. int
  1824. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1825. origin_circuit_t *circ)
  1826. {
  1827. rend_service_t *service;
  1828. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1829. smartlist_t *matching_ports;
  1830. rend_service_port_config_t *chosen_port;
  1831. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1832. tor_assert(circ->rend_data);
  1833. log_debug(LD_REND,"beginning to hunt for addr/port");
  1834. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1835. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1836. service = rend_service_get_by_pk_digest(
  1837. circ->rend_data->rend_pk_digest);
  1838. if (!service) {
  1839. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1840. "rendezvous circuit %d; closing.",
  1841. serviceid, circ->_base.n_circ_id);
  1842. return -1;
  1843. }
  1844. matching_ports = smartlist_create();
  1845. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1846. {
  1847. if (conn->_base.port == p->virtual_port) {
  1848. smartlist_add(matching_ports, p);
  1849. }
  1850. });
  1851. chosen_port = smartlist_choose(matching_ports);
  1852. smartlist_free(matching_ports);
  1853. if (chosen_port) {
  1854. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1855. conn->_base.port = chosen_port->real_port;
  1856. return 0;
  1857. }
  1858. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1859. conn->_base.port,serviceid);
  1860. return -1;
  1861. }