rendservice.c 74 KB

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