rendservice.c 73 KB

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