rendservice.c 73 KB

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