rendservice.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2012, 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 "nodelist.h"
  16. #include "rendclient.h"
  17. #include "rendcommon.h"
  18. #include "rendservice.h"
  19. #include "router.h"
  20. #include "relay.h"
  21. #include "rephist.h"
  22. #include "replaycache.h"
  23. #include "routerlist.h"
  24. #include "routerparse.h"
  25. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  26. const char *pk_digest);
  27. static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
  28. static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
  29. static int intro_point_should_expire_now(rend_intro_point_t *intro,
  30. time_t now);
  31. struct rend_service_t;
  32. static int rend_service_load_keys(struct rend_service_t *s);
  33. static int rend_service_load_auth_keys(struct rend_service_t *s,
  34. const char *hfname);
  35. /** Represents the mapping from a virtual port of a rendezvous service to
  36. * a real port on some IP.
  37. */
  38. typedef struct rend_service_port_config_t {
  39. uint16_t virtual_port;
  40. uint16_t real_port;
  41. tor_addr_t real_addr;
  42. } rend_service_port_config_t;
  43. /** Try to maintain this many intro points per service by default. */
  44. #define NUM_INTRO_POINTS_DEFAULT 3
  45. /** Maintain no more than this many intro points per hidden service. */
  46. #define NUM_INTRO_POINTS_MAX 10
  47. /** If we can't build our intro circuits, don't retry for this long. */
  48. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  49. /** Don't try to build more than this many circuits before giving up
  50. * for a while.*/
  51. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  52. /** How many times will a hidden service operator attempt to connect to
  53. * a requested rendezvous point before giving up? */
  54. #define MAX_REND_FAILURES 30
  55. /** How many seconds should we spend trying to connect to a requested
  56. * rendezvous point before giving up? */
  57. #define MAX_REND_TIMEOUT 30
  58. /** How many seconds should we wait for new HS descriptors to reach
  59. * our clients before we close an expiring intro point? */
  60. #define INTRO_POINT_EXPIRATION_GRACE_PERIOD 5*60
  61. /** Represents a single hidden service running at this OP. */
  62. typedef struct rend_service_t {
  63. /* Fields specified in config file */
  64. char *directory; /**< where in the filesystem it stores it */
  65. smartlist_t *ports; /**< List of rend_service_port_config_t */
  66. rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
  67. * authorization is performed. */
  68. smartlist_t *clients; /**< List of rend_authorized_client_t's of
  69. * clients that may access our service. Can be NULL
  70. * if no client authorization is performed. */
  71. /* Other fields */
  72. crypto_pk_t *private_key; /**< Permanent hidden-service key. */
  73. char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
  74. * '.onion' */
  75. char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
  76. smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
  77. * or are trying to establish. */
  78. time_t intro_period_started; /**< Start of the current period to build
  79. * introduction points. */
  80. int n_intro_circuits_launched; /**< Count of intro circuits we have
  81. * established in this period. */
  82. unsigned int n_intro_points_wanted; /**< Number of intro points this
  83. * service wants to have open. */
  84. rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  85. time_t desc_is_dirty; /**< Time at which changes to the hidden service
  86. * descriptor content occurred, or 0 if it's
  87. * up-to-date. */
  88. time_t next_upload_time; /**< Scheduled next hidden service descriptor
  89. * upload time. */
  90. /** Replay cache for Diffie-Hellman values of INTRODUCE2 cells, to
  91. * detect repeats. Clients may send INTRODUCE1 cells for the same
  92. * rendezvous point through two or more different introduction points;
  93. * when they do, this keeps us from launching multiple simultaneous attempts
  94. * to connect to the same rend point. */
  95. replaycache_t *accepted_intro_dh_parts;
  96. } rend_service_t;
  97. /** A list of rend_service_t's for services run on this OP.
  98. */
  99. static smartlist_t *rend_service_list = NULL;
  100. /** Return the number of rendezvous services we have configured. */
  101. int
  102. num_rend_services(void)
  103. {
  104. if (!rend_service_list)
  105. return 0;
  106. return smartlist_len(rend_service_list);
  107. }
  108. /** Return a string identifying <b>service</b>, suitable for use in a
  109. * log message. The result does not need to be freed, but may be
  110. * overwritten by the next call to this function. */
  111. static const char *
  112. rend_service_describe_for_log(rend_service_t *service)
  113. {
  114. /* XXX024 Use this function throughout rendservice.c. */
  115. /* XXX024 Return a more useful description? */
  116. return safe_str_client(service->service_id);
  117. }
  118. /** Helper: free storage held by a single service authorized client entry. */
  119. static void
  120. rend_authorized_client_free(rend_authorized_client_t *client)
  121. {
  122. if (!client)
  123. return;
  124. if (client->client_key)
  125. crypto_pk_free(client->client_key);
  126. tor_strclear(client->client_name);
  127. tor_free(client->client_name);
  128. memset(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
  129. tor_free(client);
  130. }
  131. /** Helper for strmap_free. */
  132. static void
  133. rend_authorized_client_strmap_item_free(void *authorized_client)
  134. {
  135. rend_authorized_client_free(authorized_client);
  136. }
  137. /** Release the storage held by <b>service</b>.
  138. */
  139. static void
  140. rend_service_free(rend_service_t *service)
  141. {
  142. if (!service)
  143. return;
  144. tor_free(service->directory);
  145. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  146. smartlist_free(service->ports);
  147. if (service->private_key)
  148. crypto_pk_free(service->private_key);
  149. if (service->intro_nodes) {
  150. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  151. rend_intro_point_free(intro););
  152. smartlist_free(service->intro_nodes);
  153. }
  154. rend_service_descriptor_free(service->desc);
  155. if (service->clients) {
  156. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  157. rend_authorized_client_free(c););
  158. smartlist_free(service->clients);
  159. }
  160. if (service->accepted_intro_dh_parts) {
  161. replaycache_free(service->accepted_intro_dh_parts);
  162. }
  163. tor_free(service);
  164. }
  165. /** Release all the storage held in rend_service_list.
  166. */
  167. void
  168. rend_service_free_all(void)
  169. {
  170. if (!rend_service_list)
  171. return;
  172. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  173. rend_service_free(ptr));
  174. smartlist_free(rend_service_list);
  175. rend_service_list = NULL;
  176. }
  177. /** Validate <b>service</b> and add it to rend_service_list if possible.
  178. */
  179. static void
  180. rend_add_service(rend_service_t *service)
  181. {
  182. int i;
  183. rend_service_port_config_t *p;
  184. service->intro_nodes = smartlist_new();
  185. if (service->auth_type != REND_NO_AUTH &&
  186. smartlist_len(service->clients) == 0) {
  187. log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but no "
  188. "clients; ignoring.",
  189. escaped(service->directory));
  190. rend_service_free(service);
  191. return;
  192. }
  193. if (!smartlist_len(service->ports)) {
  194. log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured; "
  195. "ignoring.",
  196. escaped(service->directory));
  197. rend_service_free(service);
  198. } else {
  199. int dupe = 0;
  200. /* XXX This duplicate check has two problems:
  201. *
  202. * a) It's O(n^2), but the same comment from the bottom of
  203. * rend_config_services() should apply.
  204. *
  205. * b) We only compare directory paths as strings, so we can't
  206. * detect two distinct paths that specify the same directory
  207. * (which can arise from symlinks, case-insensitivity, bind
  208. * mounts, etc.).
  209. *
  210. * It also can't detect that two separate Tor instances are trying
  211. * to use the same HiddenServiceDir; for that, we would need a
  212. * lock file. But this is enough to detect a simple mistake that
  213. * at least one person has actually made.
  214. */
  215. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  216. dupe = dupe ||
  217. !strcmp(ptr->directory, service->directory));
  218. if (dupe) {
  219. log_warn(LD_REND, "Another hidden service is already configured for "
  220. "directory %s, ignoring.", service->directory);
  221. rend_service_free(service);
  222. return;
  223. }
  224. smartlist_add(rend_service_list, service);
  225. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  226. service->directory);
  227. for (i = 0; i < smartlist_len(service->ports); ++i) {
  228. p = smartlist_get(service->ports, i);
  229. log_debug(LD_REND,"Service maps port %d to %s:%d",
  230. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  231. }
  232. }
  233. }
  234. /** Parses a real-port to virtual-port mapping and returns a new
  235. * rend_service_port_config_t.
  236. *
  237. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  238. *
  239. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  240. */
  241. static rend_service_port_config_t *
  242. parse_port_config(const char *string)
  243. {
  244. smartlist_t *sl;
  245. int virtport;
  246. int realport;
  247. uint16_t p;
  248. tor_addr_t addr;
  249. const char *addrport;
  250. rend_service_port_config_t *result = NULL;
  251. sl = smartlist_new();
  252. smartlist_split_string(sl, string, " ",
  253. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  254. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  255. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  256. goto err;
  257. }
  258. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  259. if (!virtport) {
  260. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  261. "configuration", escaped(smartlist_get(sl,0)));
  262. goto err;
  263. }
  264. if (smartlist_len(sl) == 1) {
  265. /* No addr:port part; use default. */
  266. realport = virtport;
  267. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  268. } else {
  269. addrport = smartlist_get(sl,1);
  270. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  271. if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
  272. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  273. "configuration.");
  274. goto err;
  275. }
  276. realport = p?p:virtport;
  277. } else {
  278. /* No addr:port, no addr -- must be port. */
  279. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  280. if (!realport) {
  281. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  282. "service port configuration.", escaped(addrport));
  283. goto err;
  284. }
  285. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  286. }
  287. }
  288. result = tor_malloc(sizeof(rend_service_port_config_t));
  289. result->virtual_port = virtport;
  290. result->real_port = realport;
  291. tor_addr_copy(&result->real_addr, &addr);
  292. err:
  293. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  294. smartlist_free(sl);
  295. return result;
  296. }
  297. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  298. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  299. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  300. * normal, but don't actually change the configured services.)
  301. */
  302. int
  303. rend_config_services(const or_options_t *options, int validate_only)
  304. {
  305. config_line_t *line;
  306. rend_service_t *service = NULL;
  307. rend_service_port_config_t *portcfg;
  308. smartlist_t *old_service_list = NULL;
  309. if (!validate_only) {
  310. old_service_list = rend_service_list;
  311. rend_service_list = smartlist_new();
  312. }
  313. for (line = options->RendConfigLines; line; line = line->next) {
  314. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  315. if (service) { /* register the one we just finished parsing */
  316. if (validate_only)
  317. rend_service_free(service);
  318. else
  319. rend_add_service(service);
  320. }
  321. service = tor_malloc_zero(sizeof(rend_service_t));
  322. service->directory = tor_strdup(line->value);
  323. service->ports = smartlist_new();
  324. service->intro_period_started = time(NULL);
  325. service->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
  326. continue;
  327. }
  328. if (!service) {
  329. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  330. line->key);
  331. rend_service_free(service);
  332. return -1;
  333. }
  334. if (!strcasecmp(line->key, "HiddenServicePort")) {
  335. portcfg = parse_port_config(line->value);
  336. if (!portcfg) {
  337. rend_service_free(service);
  338. return -1;
  339. }
  340. smartlist_add(service->ports, portcfg);
  341. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  342. /* Parse auth type and comma-separated list of client names and add a
  343. * rend_authorized_client_t for each client to the service's list
  344. * of authorized clients. */
  345. smartlist_t *type_names_split, *clients;
  346. const char *authname;
  347. int num_clients;
  348. if (service->auth_type != REND_NO_AUTH) {
  349. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  350. "lines for a single service.");
  351. rend_service_free(service);
  352. return -1;
  353. }
  354. type_names_split = smartlist_new();
  355. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  356. if (smartlist_len(type_names_split) < 1) {
  357. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  358. "should have been prevented when parsing the "
  359. "configuration.");
  360. smartlist_free(type_names_split);
  361. rend_service_free(service);
  362. return -1;
  363. }
  364. authname = smartlist_get(type_names_split, 0);
  365. if (!strcasecmp(authname, "basic")) {
  366. service->auth_type = REND_BASIC_AUTH;
  367. } else if (!strcasecmp(authname, "stealth")) {
  368. service->auth_type = REND_STEALTH_AUTH;
  369. } else {
  370. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  371. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  372. "are recognized.",
  373. (char *) smartlist_get(type_names_split, 0));
  374. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  375. smartlist_free(type_names_split);
  376. rend_service_free(service);
  377. return -1;
  378. }
  379. service->clients = smartlist_new();
  380. if (smartlist_len(type_names_split) < 2) {
  381. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  382. "auth-type '%s', but no client names.",
  383. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  384. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  385. smartlist_free(type_names_split);
  386. continue;
  387. }
  388. clients = smartlist_new();
  389. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  390. ",", SPLIT_SKIP_SPACE, 0);
  391. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  392. smartlist_free(type_names_split);
  393. /* Remove duplicate client names. */
  394. num_clients = smartlist_len(clients);
  395. smartlist_sort_strings(clients);
  396. smartlist_uniq_strings(clients);
  397. if (smartlist_len(clients) < num_clients) {
  398. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  399. "duplicate client name(s); removing.",
  400. num_clients - smartlist_len(clients));
  401. num_clients = smartlist_len(clients);
  402. }
  403. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  404. {
  405. rend_authorized_client_t *client;
  406. size_t len = strlen(client_name);
  407. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  408. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  409. "illegal client name: '%s'. Length must be "
  410. "between 1 and %d characters.",
  411. client_name, REND_CLIENTNAME_MAX_LEN);
  412. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  413. smartlist_free(clients);
  414. rend_service_free(service);
  415. return -1;
  416. }
  417. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  418. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  419. "illegal client name: '%s'. Valid "
  420. "characters are [A-Za-z0-9+_-].",
  421. client_name);
  422. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  423. smartlist_free(clients);
  424. rend_service_free(service);
  425. return -1;
  426. }
  427. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  428. client->client_name = tor_strdup(client_name);
  429. smartlist_add(service->clients, client);
  430. log_debug(LD_REND, "Adding client name '%s'", client_name);
  431. }
  432. SMARTLIST_FOREACH_END(client_name);
  433. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  434. smartlist_free(clients);
  435. /* Ensure maximum number of clients. */
  436. if ((service->auth_type == REND_BASIC_AUTH &&
  437. smartlist_len(service->clients) > 512) ||
  438. (service->auth_type == REND_STEALTH_AUTH &&
  439. smartlist_len(service->clients) > 16)) {
  440. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  441. "client authorization entries, but only a "
  442. "maximum of %d entries is allowed for "
  443. "authorization type '%s'.",
  444. smartlist_len(service->clients),
  445. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  446. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  447. rend_service_free(service);
  448. return -1;
  449. }
  450. } else {
  451. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  452. if (strcmp(line->value, "2")) {
  453. log_warn(LD_CONFIG,
  454. "The only supported HiddenServiceVersion is 2.");
  455. rend_service_free(service);
  456. return -1;
  457. }
  458. }
  459. }
  460. if (service) {
  461. if (validate_only)
  462. rend_service_free(service);
  463. else
  464. rend_add_service(service);
  465. }
  466. /* If this is a reload and there were hidden services configured before,
  467. * keep the introduction points that are still needed and close the
  468. * other ones. */
  469. if (old_service_list && !validate_only) {
  470. smartlist_t *surviving_services = smartlist_new();
  471. circuit_t *circ;
  472. /* Copy introduction points to new services. */
  473. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  474. * probably ok? */
  475. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, new) {
  476. SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
  477. if (!strcmp(old->directory, new->directory)) {
  478. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  479. smartlist_clear(old->intro_nodes);
  480. smartlist_add(surviving_services, old);
  481. break;
  482. }
  483. } SMARTLIST_FOREACH_END(old);
  484. } SMARTLIST_FOREACH_END(new);
  485. /* Close introduction circuits of services we don't serve anymore. */
  486. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  487. * so we could just iterate over the list of services to close, but
  488. * once again, this isn't critical-path code. */
  489. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  490. if (!circ->marked_for_close &&
  491. circ->state == CIRCUIT_STATE_OPEN &&
  492. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  493. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  494. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  495. int keep_it = 0;
  496. tor_assert(oc->rend_data);
  497. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  498. if (tor_memeq(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  499. DIGEST_LEN)) {
  500. keep_it = 1;
  501. break;
  502. }
  503. });
  504. if (keep_it)
  505. continue;
  506. log_info(LD_REND, "Closing intro point %s for service %s.",
  507. safe_str_client(extend_info_describe(
  508. oc->build_state->chosen_exit)),
  509. oc->rend_data->onion_address);
  510. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  511. /* XXXX Is there another reason we should use here? */
  512. }
  513. }
  514. smartlist_free(surviving_services);
  515. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  516. rend_service_free(ptr));
  517. smartlist_free(old_service_list);
  518. }
  519. return 0;
  520. }
  521. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  522. * the other fields in service.
  523. */
  524. static void
  525. rend_service_update_descriptor(rend_service_t *service)
  526. {
  527. rend_service_descriptor_t *d;
  528. origin_circuit_t *circ;
  529. int i;
  530. rend_service_descriptor_free(service->desc);
  531. service->desc = NULL;
  532. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  533. d->pk = crypto_pk_dup_key(service->private_key);
  534. d->timestamp = time(NULL);
  535. d->intro_nodes = smartlist_new();
  536. /* Support intro protocols 2 and 3. */
  537. d->protocols = (1 << 2) + (1 << 3);
  538. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  539. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  540. rend_intro_point_t *intro_desc;
  541. /* This intro point won't be listed in the descriptor... */
  542. intro_svc->listed_in_last_desc = 0;
  543. if (intro_svc->time_expiring != -1) {
  544. /* This intro point is expiring. Don't list it. */
  545. continue;
  546. }
  547. circ = find_intro_circuit(intro_svc, service->pk_digest);
  548. if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  549. /* This intro point's circuit isn't finished yet. Don't list it. */
  550. continue;
  551. }
  552. /* ...unless this intro point is listed in the descriptor. */
  553. intro_svc->listed_in_last_desc = 1;
  554. /* We have an entirely established intro circuit. Publish it in
  555. * our descriptor. */
  556. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  557. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  558. if (intro_svc->intro_key)
  559. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  560. smartlist_add(d->intro_nodes, intro_desc);
  561. if (intro_svc->time_published == -1) {
  562. /* We are publishing this intro point in a descriptor for the
  563. * first time -- note the current time in the service's copy of
  564. * the intro point. */
  565. intro_svc->time_published = time(NULL);
  566. }
  567. }
  568. }
  569. /** Load and/or generate private keys for all hidden services, possibly
  570. * including keys for client authorization. Return 0 on success, -1 on
  571. * failure. */
  572. int
  573. rend_service_load_all_keys(void)
  574. {
  575. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  576. if (s->private_key)
  577. continue;
  578. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  579. s->directory);
  580. if (rend_service_load_keys(s) < 0)
  581. return -1;
  582. } SMARTLIST_FOREACH_END(s);
  583. return 0;
  584. }
  585. /** Load and/or generate private keys for the hidden service <b>s</b>,
  586. * possibly including keys for client authorization. Return 0 on success, -1
  587. * on failure. */
  588. static int
  589. rend_service_load_keys(rend_service_t *s)
  590. {
  591. char fname[512];
  592. char buf[128];
  593. /* Check/create directory */
  594. if (check_private_dir(s->directory, CPD_CREATE, get_options()->User) < 0)
  595. return -1;
  596. /* Load key */
  597. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  598. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  599. >= sizeof(fname)) {
  600. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  601. s->directory);
  602. return -1;
  603. }
  604. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  605. if (!s->private_key)
  606. return -1;
  607. /* Create service file */
  608. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  609. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  610. return -1;
  611. }
  612. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  613. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  614. return -1;
  615. }
  616. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  617. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  618. >= sizeof(fname)) {
  619. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  620. " \"%s\".", s->directory);
  621. return -1;
  622. }
  623. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  624. if (write_str_to_file(fname,buf,0)<0) {
  625. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  626. memset(buf, 0, sizeof(buf));
  627. return -1;
  628. }
  629. memset(buf, 0, sizeof(buf));
  630. /* If client authorization is configured, load or generate keys. */
  631. if (s->auth_type != REND_NO_AUTH) {
  632. if (rend_service_load_auth_keys(s, fname) < 0)
  633. return -1;
  634. }
  635. return 0;
  636. }
  637. /** Load and/or generate client authorization keys for the hidden service
  638. * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
  639. * -1 on failure. */
  640. static int
  641. rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
  642. {
  643. int r = 0;
  644. char cfname[512];
  645. char *client_keys_str = NULL;
  646. strmap_t *parsed_clients = strmap_new();
  647. FILE *cfile, *hfile;
  648. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  649. char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
  650. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  651. char service_id[16+1];
  652. char buf[1500];
  653. /* Load client keys and descriptor cookies, if available. */
  654. if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
  655. s->directory)<0) {
  656. log_warn(LD_CONFIG, "Directory name too long to store client keys "
  657. "file: \"%s\".", s->directory);
  658. goto err;
  659. }
  660. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  661. if (client_keys_str) {
  662. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  663. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  664. "be parsed.");
  665. goto err;
  666. } else {
  667. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  668. strmap_size(parsed_clients));
  669. }
  670. }
  671. /* Prepare client_keys and hostname files. */
  672. if (!(cfile = start_writing_to_stdio_file(cfname,
  673. OPEN_FLAGS_REPLACE | O_TEXT,
  674. 0600, &open_cfile))) {
  675. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  676. escaped(cfname));
  677. goto err;
  678. }
  679. if (!(hfile = start_writing_to_stdio_file(hfname,
  680. OPEN_FLAGS_REPLACE | O_TEXT,
  681. 0600, &open_hfile))) {
  682. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
  683. goto err;
  684. }
  685. /* Either use loaded keys for configured clients or generate new
  686. * ones if a client is new. */
  687. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
  688. rend_authorized_client_t *parsed =
  689. strmap_get(parsed_clients, client->client_name);
  690. int written;
  691. size_t len;
  692. /* Copy descriptor cookie from parsed entry or create new one. */
  693. if (parsed) {
  694. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  695. REND_DESC_COOKIE_LEN);
  696. } else {
  697. crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  698. }
  699. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  700. client->descriptor_cookie,
  701. REND_DESC_COOKIE_LEN) < 0) {
  702. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  703. goto err;
  704. }
  705. /* Copy client key from parsed entry or create new one if required. */
  706. if (parsed && parsed->client_key) {
  707. client->client_key = crypto_pk_dup_key(parsed->client_key);
  708. } else if (s->auth_type == REND_STEALTH_AUTH) {
  709. /* Create private key for client. */
  710. crypto_pk_t *prkey = NULL;
  711. if (!(prkey = crypto_pk_new())) {
  712. log_warn(LD_BUG,"Error constructing client key");
  713. goto err;
  714. }
  715. if (crypto_pk_generate_key(prkey)) {
  716. log_warn(LD_BUG,"Error generating client key");
  717. crypto_pk_free(prkey);
  718. goto err;
  719. }
  720. if (crypto_pk_check_key(prkey) <= 0) {
  721. log_warn(LD_BUG,"Generated client key seems invalid");
  722. crypto_pk_free(prkey);
  723. goto err;
  724. }
  725. client->client_key = prkey;
  726. }
  727. /* Add entry to client_keys file. */
  728. desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
  729. written = tor_snprintf(buf, sizeof(buf),
  730. "client-name %s\ndescriptor-cookie %s\n",
  731. client->client_name, desc_cook_out);
  732. if (written < 0) {
  733. log_warn(LD_BUG, "Could not write client entry.");
  734. goto err;
  735. }
  736. if (client->client_key) {
  737. char *client_key_out = NULL;
  738. if (crypto_pk_write_private_key_to_string(client->client_key,
  739. &client_key_out, &len) != 0) {
  740. log_warn(LD_BUG, "Internal error: "
  741. "crypto_pk_write_private_key_to_string() failed.");
  742. goto err;
  743. }
  744. if (rend_get_service_id(client->client_key, service_id)<0) {
  745. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  746. /*
  747. * len is string length, not buffer length, but last byte is NUL
  748. * anyway.
  749. */
  750. memset(client_key_out, 0, len);
  751. tor_free(client_key_out);
  752. goto err;
  753. }
  754. written = tor_snprintf(buf + written, sizeof(buf) - written,
  755. "client-key\n%s", client_key_out);
  756. memset(client_key_out, 0, len);
  757. tor_free(client_key_out);
  758. if (written < 0) {
  759. log_warn(LD_BUG, "Could not write client entry.");
  760. goto err;
  761. }
  762. }
  763. if (fputs(buf, cfile) < 0) {
  764. log_warn(LD_FS, "Could not append client entry to file: %s",
  765. strerror(errno));
  766. goto err;
  767. }
  768. /* Add line to hostname file. */
  769. if (s->auth_type == REND_BASIC_AUTH) {
  770. /* Remove == signs (newline has been removed above). */
  771. desc_cook_out[strlen(desc_cook_out)-2] = '\0';
  772. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  773. s->service_id, desc_cook_out, client->client_name);
  774. } else {
  775. memcpy(extended_desc_cookie, client->descriptor_cookie,
  776. REND_DESC_COOKIE_LEN);
  777. extended_desc_cookie[REND_DESC_COOKIE_LEN] =
  778. ((int)s->auth_type - 1) << 4;
  779. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  780. extended_desc_cookie,
  781. REND_DESC_COOKIE_LEN+1) < 0) {
  782. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  783. goto err;
  784. }
  785. desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
  786. newline. */
  787. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  788. service_id, desc_cook_out, client->client_name);
  789. }
  790. if (fputs(buf, hfile)<0) {
  791. log_warn(LD_FS, "Could not append host entry to file: %s",
  792. strerror(errno));
  793. goto err;
  794. }
  795. } SMARTLIST_FOREACH_END(client);
  796. finish_writing_to_file(open_cfile);
  797. finish_writing_to_file(open_hfile);
  798. goto done;
  799. err:
  800. r = -1;
  801. if (open_cfile)
  802. abort_writing_to_file(open_cfile);
  803. if (open_hfile)
  804. abort_writing_to_file(open_hfile);
  805. done:
  806. if (client_keys_str) {
  807. tor_strclear(client_keys_str);
  808. tor_free(client_keys_str);
  809. }
  810. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  811. memset(cfname, 0, sizeof(cfname));
  812. /* Clear stack buffers that held key-derived material. */
  813. memset(buf, 0, sizeof(buf));
  814. memset(desc_cook_out, 0, sizeof(desc_cook_out));
  815. memset(service_id, 0, sizeof(service_id));
  816. memset(extended_desc_cookie, 0, sizeof(extended_desc_cookie));
  817. return r;
  818. }
  819. /** Return the service whose public key has a digest of <b>digest</b>, or
  820. * NULL if no such service exists.
  821. */
  822. static rend_service_t *
  823. rend_service_get_by_pk_digest(const char* digest)
  824. {
  825. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  826. if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
  827. return s);
  828. return NULL;
  829. }
  830. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  831. * to have good uptime. Else return 0.
  832. */
  833. static int
  834. rend_service_requires_uptime(rend_service_t *service)
  835. {
  836. int i;
  837. rend_service_port_config_t *p;
  838. for (i=0; i < smartlist_len(service->ports); ++i) {
  839. p = smartlist_get(service->ports, i);
  840. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  841. p->virtual_port))
  842. return 1;
  843. }
  844. return 0;
  845. }
  846. /** Check client authorization of a given <b>descriptor_cookie</b> for
  847. * <b>service</b>. Return 1 for success and 0 for failure. */
  848. static int
  849. rend_check_authorization(rend_service_t *service,
  850. const char *descriptor_cookie)
  851. {
  852. rend_authorized_client_t *auth_client = NULL;
  853. tor_assert(service);
  854. tor_assert(descriptor_cookie);
  855. if (!service->clients) {
  856. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  857. "authorized clients configured.");
  858. return 0;
  859. }
  860. /* Look up client authorization by descriptor cookie. */
  861. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  862. if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
  863. REND_DESC_COOKIE_LEN)) {
  864. auth_client = client;
  865. break;
  866. }
  867. });
  868. if (!auth_client) {
  869. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  870. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  871. descriptor_cookie, REND_DESC_COOKIE_LEN);
  872. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  873. "Dropping cell!",
  874. descriptor_cookie_base64);
  875. return 0;
  876. }
  877. /* Allow the request. */
  878. log_debug(LD_REND, "Client %s authorized for service %s.",
  879. auth_client->client_name, service->service_id);
  880. return 1;
  881. }
  882. /** Called when <b>intro</b> will soon be removed from
  883. * <b>service</b>'s list of intro points. */
  884. static void
  885. rend_service_note_removing_intro_point(rend_service_t *service,
  886. rend_intro_point_t *intro)
  887. {
  888. time_t now = time(NULL);
  889. /* Don't process an intro point twice here. */
  890. if (intro->rend_service_note_removing_intro_point_called) {
  891. return;
  892. } else {
  893. intro->rend_service_note_removing_intro_point_called = 1;
  894. }
  895. /* Update service->n_intro_points_wanted based on how long intro
  896. * lasted and how many introductions it handled. */
  897. if (intro->time_published == -1) {
  898. /* This intro point was never used. Don't change
  899. * n_intro_points_wanted. */
  900. } else {
  901. /* We want to increase the number of introduction points service
  902. * operates if intro was heavily used, or decrease the number of
  903. * intro points if intro was lightly used.
  904. *
  905. * We consider an intro point's target 'usage' to be
  906. * INTRO_POINT_LIFETIME_INTRODUCTIONS introductions in
  907. * INTRO_POINT_LIFETIME_MIN_SECONDS seconds. To calculate intro's
  908. * fraction of target usage, we divide the fraction of
  909. * _LIFETIME_INTRODUCTIONS introductions that it has handled by
  910. * the fraction of _LIFETIME_MIN_SECONDS for which it existed.
  911. *
  912. * Then we multiply that fraction of desired usage by a fudge
  913. * factor of 1.5, to decide how many new introduction points
  914. * should ideally replace intro (which is now closed or soon to be
  915. * closed). In theory, assuming that introduction load is
  916. * distributed equally across all intro points and ignoring the
  917. * fact that different intro points are established and closed at
  918. * different times, that number of intro points should bring all
  919. * of our intro points exactly to our target usage.
  920. *
  921. * Then we clamp that number to a number of intro points we might
  922. * be willing to replace this intro point with and turn it into an
  923. * integer. then we clamp it again to the number of new intro
  924. * points we could establish now, then we adjust
  925. * service->n_intro_points_wanted and let rend_services_introduce
  926. * create the new intro points we want (if any).
  927. */
  928. const double intro_point_usage =
  929. intro_point_accepted_intro_count(intro) /
  930. (double)(now - intro->time_published);
  931. const double intro_point_target_usage =
  932. INTRO_POINT_LIFETIME_INTRODUCTIONS /
  933. (double)INTRO_POINT_LIFETIME_MIN_SECONDS;
  934. const double fractional_n_intro_points_wanted_to_replace_this_one =
  935. (1.5 * (intro_point_usage / intro_point_target_usage));
  936. unsigned int n_intro_points_wanted_to_replace_this_one;
  937. unsigned int n_intro_points_wanted_now;
  938. unsigned int n_intro_points_really_wanted_now;
  939. int n_intro_points_really_replacing_this_one;
  940. if (fractional_n_intro_points_wanted_to_replace_this_one >
  941. NUM_INTRO_POINTS_MAX) {
  942. n_intro_points_wanted_to_replace_this_one = NUM_INTRO_POINTS_MAX;
  943. } else if (fractional_n_intro_points_wanted_to_replace_this_one < 0) {
  944. n_intro_points_wanted_to_replace_this_one = 0;
  945. } else {
  946. n_intro_points_wanted_to_replace_this_one = (unsigned)
  947. fractional_n_intro_points_wanted_to_replace_this_one;
  948. }
  949. n_intro_points_wanted_now =
  950. service->n_intro_points_wanted +
  951. n_intro_points_wanted_to_replace_this_one - 1;
  952. if (n_intro_points_wanted_now < NUM_INTRO_POINTS_DEFAULT) {
  953. /* XXXX This should be NUM_INTRO_POINTS_MIN instead. Perhaps
  954. * another use of NUM_INTRO_POINTS_DEFAULT should be, too. */
  955. n_intro_points_really_wanted_now = NUM_INTRO_POINTS_DEFAULT;
  956. } else if (n_intro_points_wanted_now > NUM_INTRO_POINTS_MAX) {
  957. n_intro_points_really_wanted_now = NUM_INTRO_POINTS_MAX;
  958. } else {
  959. n_intro_points_really_wanted_now = n_intro_points_wanted_now;
  960. }
  961. n_intro_points_really_replacing_this_one =
  962. n_intro_points_really_wanted_now - service->n_intro_points_wanted + 1;
  963. log_info(LD_REND, "Replacing closing intro point for service %s "
  964. "with %d new intro points (wanted %g replacements); "
  965. "service will now try to have %u intro points",
  966. rend_service_describe_for_log(service),
  967. n_intro_points_really_replacing_this_one,
  968. fractional_n_intro_points_wanted_to_replace_this_one,
  969. n_intro_points_really_wanted_now);
  970. service->n_intro_points_wanted = n_intro_points_really_wanted_now;
  971. }
  972. }
  973. /******
  974. * Handle cells
  975. ******/
  976. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  977. * rendezvous point.
  978. */
  979. /* XXXX024 this function sure could use some organizing. -RD */
  980. int
  981. rend_service_introduce(origin_circuit_t *circuit, const uint8_t *request,
  982. size_t request_len)
  983. {
  984. int status = 0;
  985. char *ptr, *r_cookie;
  986. extend_info_t *extend_info = NULL;
  987. char buf[RELAY_PAYLOAD_SIZE];
  988. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  989. rend_service_t *service;
  990. rend_intro_point_t *intro_point;
  991. int r, i, v3_shift = 0;
  992. size_t len, keylen;
  993. crypto_dh_t *dh = NULL;
  994. origin_circuit_t *launched = NULL;
  995. crypt_path_t *cpath = NULL;
  996. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  997. char hexcookie[9];
  998. int circ_needs_uptime;
  999. int reason = END_CIRC_REASON_TORPROTOCOL;
  1000. crypto_pk_t *intro_key;
  1001. char intro_key_digest[DIGEST_LEN];
  1002. int auth_type;
  1003. size_t auth_len = 0;
  1004. char auth_data[REND_DESC_COOKIE_LEN];
  1005. time_t now = time(NULL);
  1006. char diffie_hellman_hash[DIGEST_LEN];
  1007. time_t elapsed;
  1008. int replay;
  1009. const or_options_t *options = get_options();
  1010. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1011. log_warn(LD_PROTOCOL,
  1012. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  1013. circuit->_base.n_circ_id);
  1014. goto err;
  1015. }
  1016. #ifndef NON_ANONYMOUS_MODE_ENABLED
  1017. tor_assert(!(circuit->build_state->onehop_tunnel));
  1018. #endif
  1019. tor_assert(circuit->rend_data);
  1020. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1021. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1022. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  1023. escaped(serviceid), circuit->_base.n_circ_id);
  1024. /* min key length plus digest length plus nickname length */
  1025. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  1026. DH_KEY_LEN+42) {
  1027. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  1028. circuit->_base.n_circ_id);
  1029. goto err;
  1030. }
  1031. /* look up service depending on circuit. */
  1032. service = rend_service_get_by_pk_digest(
  1033. circuit->rend_data->rend_pk_digest);
  1034. if (!service) {
  1035. log_warn(LD_BUG, "Internal error: Got an INTRODUCE2 cell on an intro "
  1036. "circ for an unrecognized service %s.",
  1037. escaped(serviceid));
  1038. goto err;
  1039. }
  1040. /* use intro key instead of service key. */
  1041. intro_key = circuit->intro_key;
  1042. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  1043. crypto_pk_get_digest(intro_key, intro_key_digest);
  1044. if (tor_memneq(intro_key_digest, request, DIGEST_LEN)) {
  1045. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1046. (char*)request, REND_SERVICE_ID_LEN);
  1047. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  1048. escaped(serviceid));
  1049. goto err;
  1050. }
  1051. keylen = crypto_pk_keysize(intro_key);
  1052. if (request_len < keylen+DIGEST_LEN) {
  1053. log_warn(LD_PROTOCOL,
  1054. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  1055. goto err;
  1056. }
  1057. intro_point = find_intro_point(circuit);
  1058. if (intro_point == NULL) {
  1059. log_warn(LD_BUG, "Internal error: Got an INTRODUCE2 cell on an intro circ "
  1060. "(for service %s) with no corresponding rend_intro_point_t.",
  1061. escaped(serviceid));
  1062. goto err;
  1063. }
  1064. if (!service->accepted_intro_dh_parts) {
  1065. service->accepted_intro_dh_parts =
  1066. replaycache_new(REND_REPLAY_TIME_INTERVAL,
  1067. REND_REPLAY_TIME_INTERVAL);
  1068. }
  1069. if (!intro_point->accepted_intro_rsa_parts) {
  1070. intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
  1071. }
  1072. /* Check for replay of PK-encrypted portion. */
  1073. replay = replaycache_add_test_and_elapsed(
  1074. intro_point->accepted_intro_rsa_parts,
  1075. ((char*)request)+DIGEST_LEN, keylen,
  1076. &elapsed);
  1077. if (replay) {
  1078. log_warn(LD_REND, "Possible replay detected! We received an "
  1079. "INTRODUCE2 cell with same PK-encrypted part %d seconds ago. "
  1080. "Dropping cell.", (int)elapsed);
  1081. goto err;
  1082. }
  1083. /* Increment INTRODUCE2 counter */
  1084. ++(intro_point->accepted_introduce2_count);
  1085. /* Next N bytes is encrypted with service key */
  1086. note_crypto_pk_op(REND_SERVER);
  1087. r = crypto_pk_private_hybrid_decrypt(
  1088. intro_key,buf,sizeof(buf),
  1089. (char*)(request+DIGEST_LEN),request_len-DIGEST_LEN,
  1090. PK_PKCS1_OAEP_PADDING,1);
  1091. if (r<0) {
  1092. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  1093. goto err;
  1094. }
  1095. len = r;
  1096. if (*buf == 3) {
  1097. /* Version 3 INTRODUCE2 cell. */
  1098. v3_shift = 1;
  1099. auth_type = buf[1];
  1100. switch (auth_type) {
  1101. case REND_BASIC_AUTH:
  1102. /* fall through */
  1103. case REND_STEALTH_AUTH:
  1104. auth_len = ntohs(get_uint16(buf+2));
  1105. if (auth_len != REND_DESC_COOKIE_LEN) {
  1106. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  1107. (int)auth_len, REND_DESC_COOKIE_LEN);
  1108. goto err;
  1109. }
  1110. memcpy(auth_data, buf+4, sizeof(auth_data));
  1111. v3_shift += 2+REND_DESC_COOKIE_LEN;
  1112. break;
  1113. case REND_NO_AUTH:
  1114. break;
  1115. default:
  1116. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  1117. }
  1118. /* Skip the timestamp field. We no longer use it. */
  1119. v3_shift += 4;
  1120. }
  1121. if (*buf == 2 || *buf == 3) {
  1122. /* Version 2 INTRODUCE2 cell. */
  1123. int klen;
  1124. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  1125. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  1126. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  1127. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  1128. DIGEST_LEN);
  1129. extend_info->nickname[0] = '$';
  1130. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  1131. extend_info->identity_digest, DIGEST_LEN);
  1132. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  1133. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  1134. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  1135. (int)len, *buf);
  1136. reason = END_CIRC_REASON_TORPROTOCOL;
  1137. goto err;
  1138. }
  1139. extend_info->onion_key =
  1140. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  1141. if (!extend_info->onion_key) {
  1142. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  1143. "INTRODUCE2 cell.", *buf);
  1144. reason = END_CIRC_REASON_TORPROTOCOL;
  1145. goto err;
  1146. }
  1147. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  1148. len -= v3_shift+7+DIGEST_LEN+2+klen;
  1149. } else {
  1150. char *rp_nickname;
  1151. size_t nickname_field_len;
  1152. const node_t *node;
  1153. int version;
  1154. if (*buf == 1) {
  1155. rp_nickname = buf+1;
  1156. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  1157. version = 1;
  1158. } else {
  1159. nickname_field_len = MAX_NICKNAME_LEN+1;
  1160. rp_nickname = buf;
  1161. version = 0;
  1162. }
  1163. ptr=memchr(rp_nickname,0,nickname_field_len);
  1164. if (!ptr || ptr == rp_nickname) {
  1165. log_warn(LD_PROTOCOL,
  1166. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  1167. goto err;
  1168. }
  1169. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  1170. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  1171. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  1172. goto err;
  1173. }
  1174. /* Okay, now we know that a nickname is at the start of the buffer. */
  1175. ptr = rp_nickname+nickname_field_len;
  1176. len -= nickname_field_len;
  1177. len -= rp_nickname - buf; /* also remove header space used by version, if
  1178. * any */
  1179. node = node_get_by_nickname(rp_nickname, 0);
  1180. if (!node) {
  1181. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  1182. escaped_safe_str_client(rp_nickname));
  1183. /* XXXX Add a no-such-router reason? */
  1184. reason = END_CIRC_REASON_TORPROTOCOL;
  1185. goto err;
  1186. }
  1187. extend_info = extend_info_from_node(node, 0);
  1188. }
  1189. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  1190. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  1191. reason = END_CIRC_REASON_TORPROTOCOL;
  1192. goto err;
  1193. }
  1194. /* Check if we'd refuse to talk to this router */
  1195. if (options->StrictNodes &&
  1196. routerset_contains_extendinfo(options->ExcludeNodes, extend_info)) {
  1197. log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
  1198. "exclude, and StrictNodes is set. Refusing service.");
  1199. reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
  1200. goto err;
  1201. }
  1202. r_cookie = ptr;
  1203. base16_encode(hexcookie,9,r_cookie,4);
  1204. /* Check whether there is a past request with the same Diffie-Hellman,
  1205. * part 1. */
  1206. replay = replaycache_add_test_and_elapsed(
  1207. service->accepted_intro_dh_parts,
  1208. ptr+REND_COOKIE_LEN, DH_KEY_LEN,
  1209. &elapsed);
  1210. if (replay) {
  1211. /* A Tor client will send a new INTRODUCE1 cell with the same rend
  1212. * cookie and DH public key as its previous one if its intro circ
  1213. * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
  1214. * If we received the first INTRODUCE1 cell (the intro-point relay
  1215. * converts it into an INTRODUCE2 cell), we are already trying to
  1216. * connect to that rend point (and may have already succeeded);
  1217. * drop this cell. */
  1218. log_info(LD_REND, "We received an "
  1219. "INTRODUCE2 cell with same first part of "
  1220. "Diffie-Hellman handshake %d seconds ago. Dropping "
  1221. "cell.",
  1222. (int) elapsed);
  1223. goto err;
  1224. }
  1225. /* If the service performs client authorization, check included auth data. */
  1226. if (service->clients) {
  1227. if (auth_len > 0) {
  1228. if (rend_check_authorization(service, auth_data)) {
  1229. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1230. } else {
  1231. log_info(LD_REND, "The authorization data that are contained in "
  1232. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1233. reason = END_CIRC_REASON_CONNECTFAILED;
  1234. goto err;
  1235. }
  1236. } else {
  1237. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1238. "data, but we require client authorization. Dropping cell.");
  1239. reason = END_CIRC_REASON_CONNECTFAILED;
  1240. goto err;
  1241. }
  1242. }
  1243. /* Try DH handshake... */
  1244. dh = crypto_dh_new(DH_TYPE_REND);
  1245. if (!dh || crypto_dh_generate_public(dh)<0) {
  1246. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1247. "or generate public key.");
  1248. reason = END_CIRC_REASON_INTERNAL;
  1249. goto err;
  1250. }
  1251. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh, ptr+REND_COOKIE_LEN,
  1252. DH_KEY_LEN, keys,
  1253. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1254. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1255. reason = END_CIRC_REASON_INTERNAL;
  1256. goto err;
  1257. }
  1258. circ_needs_uptime = rend_service_requires_uptime(service);
  1259. /* help predict this next time */
  1260. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1261. /* Launch a circuit to alice's chosen rendezvous point.
  1262. */
  1263. for (i=0;i<MAX_REND_FAILURES;i++) {
  1264. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1265. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1266. launched = circuit_launch_by_extend_info(
  1267. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1268. if (launched)
  1269. break;
  1270. }
  1271. if (!launched) { /* give up */
  1272. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1273. "point %s for service %s.",
  1274. safe_str_client(extend_info_describe(extend_info)),
  1275. serviceid);
  1276. reason = END_CIRC_REASON_CONNECTFAILED;
  1277. goto err;
  1278. }
  1279. log_info(LD_REND,
  1280. "Accepted intro; launching circuit to %s "
  1281. "(cookie %s) for service %s.",
  1282. safe_str_client(extend_info_describe(extend_info)),
  1283. hexcookie, serviceid);
  1284. tor_assert(launched->build_state);
  1285. /* Fill in the circuit's state. */
  1286. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1287. memcpy(launched->rend_data->rend_pk_digest,
  1288. circuit->rend_data->rend_pk_digest,
  1289. DIGEST_LEN);
  1290. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1291. strlcpy(launched->rend_data->onion_address, service->service_id,
  1292. sizeof(launched->rend_data->onion_address));
  1293. launched->build_state->service_pending_final_cpath_ref =
  1294. tor_malloc_zero(sizeof(crypt_path_reference_t));
  1295. launched->build_state->service_pending_final_cpath_ref->refcount = 1;
  1296. launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
  1297. tor_malloc_zero(sizeof(crypt_path_t));
  1298. cpath->magic = CRYPT_PATH_MAGIC;
  1299. launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
  1300. cpath->dh_handshake_state = dh;
  1301. dh = NULL;
  1302. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1303. goto err;
  1304. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1305. if (extend_info) extend_info_free(extend_info);
  1306. goto done;
  1307. err:
  1308. status = -1;
  1309. if (dh) crypto_dh_free(dh);
  1310. if (launched)
  1311. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1312. if (extend_info) extend_info_free(extend_info);
  1313. done:
  1314. memset(keys, 0, sizeof(keys));
  1315. memset(buf, 0, sizeof(buf));
  1316. memset(serviceid, 0, sizeof(serviceid));
  1317. memset(hexcookie, 0, sizeof(hexcookie));
  1318. memset(intro_key_digest, 0, sizeof(intro_key_digest));
  1319. memset(auth_data, 0, sizeof(auth_data));
  1320. memset(diffie_hellman_hash, 0, sizeof(diffie_hellman_hash));
  1321. return status;
  1322. }
  1323. /** Called when we fail building a rendezvous circuit at some point other
  1324. * than the last hop: launches a new circuit to the same rendezvous point.
  1325. */
  1326. void
  1327. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1328. {
  1329. origin_circuit_t *newcirc;
  1330. cpath_build_state_t *newstate, *oldstate;
  1331. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1332. /* Don't relaunch the same rend circ twice. */
  1333. if (oldcirc->hs_service_side_rend_circ_has_been_relaunched) {
  1334. log_info(LD_REND, "Rendezvous circuit to %s has already been relaunched; "
  1335. "not relaunching it again.",
  1336. oldcirc->build_state ?
  1337. safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
  1338. : "*unknown*");
  1339. return;
  1340. }
  1341. oldcirc->hs_service_side_rend_circ_has_been_relaunched = 1;
  1342. if (!oldcirc->build_state ||
  1343. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1344. oldcirc->build_state->expiry_time < time(NULL)) {
  1345. log_info(LD_REND,
  1346. "Attempt to build circuit to %s for rendezvous has failed "
  1347. "too many times or expired; giving up.",
  1348. oldcirc->build_state ?
  1349. safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
  1350. : "*unknown*");
  1351. return;
  1352. }
  1353. oldstate = oldcirc->build_state;
  1354. tor_assert(oldstate);
  1355. if (oldstate->service_pending_final_cpath_ref == NULL) {
  1356. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1357. "Initiator will retry.");
  1358. return;
  1359. }
  1360. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1361. safe_str(extend_info_describe(oldstate->chosen_exit)));
  1362. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1363. oldstate->chosen_exit,
  1364. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1365. if (!newcirc) {
  1366. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1367. safe_str(extend_info_describe(oldstate->chosen_exit)));
  1368. return;
  1369. }
  1370. newstate = newcirc->build_state;
  1371. tor_assert(newstate);
  1372. newstate->failure_count = oldstate->failure_count+1;
  1373. newstate->expiry_time = oldstate->expiry_time;
  1374. newstate->service_pending_final_cpath_ref =
  1375. oldstate->service_pending_final_cpath_ref;
  1376. ++(newstate->service_pending_final_cpath_ref->refcount);
  1377. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1378. }
  1379. /** Launch a circuit to serve as an introduction point for the service
  1380. * <b>service</b> at the introduction point <b>nickname</b>
  1381. */
  1382. static int
  1383. rend_service_launch_establish_intro(rend_service_t *service,
  1384. rend_intro_point_t *intro)
  1385. {
  1386. origin_circuit_t *launched;
  1387. log_info(LD_REND,
  1388. "Launching circuit to introduction point %s for service %s",
  1389. safe_str_client(extend_info_describe(intro->extend_info)),
  1390. service->service_id);
  1391. rep_hist_note_used_internal(time(NULL), 1, 0);
  1392. ++service->n_intro_circuits_launched;
  1393. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1394. intro->extend_info,
  1395. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1396. if (!launched) {
  1397. log_info(LD_REND,
  1398. "Can't launch circuit to establish introduction at %s.",
  1399. safe_str_client(extend_info_describe(intro->extend_info)));
  1400. return -1;
  1401. }
  1402. if (tor_memneq(intro->extend_info->identity_digest,
  1403. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1404. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1405. base16_encode(cann, sizeof(cann),
  1406. launched->build_state->chosen_exit->identity_digest,
  1407. DIGEST_LEN);
  1408. base16_encode(orig, sizeof(orig),
  1409. intro->extend_info->identity_digest, DIGEST_LEN);
  1410. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1411. "but we requested an intro circuit to $%s. Updating "
  1412. "our service.", cann, orig);
  1413. extend_info_free(intro->extend_info);
  1414. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1415. }
  1416. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1417. strlcpy(launched->rend_data->onion_address, service->service_id,
  1418. sizeof(launched->rend_data->onion_address));
  1419. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1420. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1421. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1422. rend_service_intro_has_opened(launched);
  1423. return 0;
  1424. }
  1425. /** Return the number of introduction points that are or have been
  1426. * established for the given service address in <b>query</b>. */
  1427. static int
  1428. count_established_intro_points(const char *query)
  1429. {
  1430. int num_ipos = 0;
  1431. circuit_t *circ;
  1432. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1433. if (!circ->marked_for_close &&
  1434. circ->state == CIRCUIT_STATE_OPEN &&
  1435. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1436. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1437. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1438. if (oc->rend_data &&
  1439. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1440. num_ipos++;
  1441. }
  1442. }
  1443. return num_ipos;
  1444. }
  1445. /** Called when we're done building a circuit to an introduction point:
  1446. * sends a RELAY_ESTABLISH_INTRO cell.
  1447. */
  1448. void
  1449. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1450. {
  1451. rend_service_t *service;
  1452. size_t len;
  1453. int r;
  1454. char buf[RELAY_PAYLOAD_SIZE];
  1455. char auth[DIGEST_LEN + 9];
  1456. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1457. int reason = END_CIRC_REASON_TORPROTOCOL;
  1458. crypto_pk_t *intro_key;
  1459. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1460. #ifndef NON_ANONYMOUS_MODE_ENABLED
  1461. tor_assert(!(circuit->build_state->onehop_tunnel));
  1462. #endif
  1463. tor_assert(circuit->cpath);
  1464. tor_assert(circuit->rend_data);
  1465. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1466. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1467. service = rend_service_get_by_pk_digest(
  1468. circuit->rend_data->rend_pk_digest);
  1469. if (!service) {
  1470. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1471. serviceid, circuit->_base.n_circ_id);
  1472. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1473. goto err;
  1474. }
  1475. /* If we already have enough introduction circuits for this service,
  1476. * redefine this one as a general circuit or close it, depending. */
  1477. if (count_established_intro_points(serviceid) >
  1478. (int)service->n_intro_points_wanted) { /* XXX023 remove cast */
  1479. const or_options_t *options = get_options();
  1480. if (options->ExcludeNodes) {
  1481. /* XXXX in some future version, we can test whether the transition is
  1482. allowed or not given the actual nodes in the circuit. But for now,
  1483. this case, we might as well close the thing. */
  1484. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1485. "circuit, but we already have enough. Closing it.");
  1486. reason = END_CIRC_REASON_NONE;
  1487. goto err;
  1488. } else {
  1489. tor_assert(circuit->build_state->is_internal);
  1490. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1491. "circuit, but we already have enough. Redefining purpose to "
  1492. "general; leaving as internal.");
  1493. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
  1494. {
  1495. rend_data_t *rend_data = circuit->rend_data;
  1496. circuit->rend_data = NULL;
  1497. rend_data_free(rend_data);
  1498. }
  1499. {
  1500. crypto_pk_t *intro_key = circuit->intro_key;
  1501. circuit->intro_key = NULL;
  1502. crypto_pk_free(intro_key);
  1503. }
  1504. circuit_has_opened(circuit);
  1505. goto done;
  1506. }
  1507. }
  1508. log_info(LD_REND,
  1509. "Established circuit %d as introduction point for service %s",
  1510. circuit->_base.n_circ_id, serviceid);
  1511. /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
  1512. intro_key = circuit->intro_key;
  1513. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1514. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1515. RELAY_PAYLOAD_SIZE-2);
  1516. if (r < 0) {
  1517. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1518. reason = END_CIRC_REASON_INTERNAL;
  1519. goto err;
  1520. }
  1521. len = r;
  1522. set_uint16(buf, htons((uint16_t)len));
  1523. len += 2;
  1524. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1525. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1526. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1527. goto err;
  1528. len += 20;
  1529. note_crypto_pk_op(REND_SERVER);
  1530. r = crypto_pk_private_sign_digest(intro_key, buf+len, sizeof(buf)-len,
  1531. buf, len);
  1532. if (r<0) {
  1533. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1534. reason = END_CIRC_REASON_INTERNAL;
  1535. goto err;
  1536. }
  1537. len += r;
  1538. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1539. RELAY_COMMAND_ESTABLISH_INTRO,
  1540. buf, len, circuit->cpath->prev)<0) {
  1541. log_info(LD_GENERAL,
  1542. "Couldn't send introduction request for service %s on circuit %d",
  1543. serviceid, circuit->_base.n_circ_id);
  1544. reason = END_CIRC_REASON_INTERNAL;
  1545. goto err;
  1546. }
  1547. goto done;
  1548. err:
  1549. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1550. done:
  1551. memset(buf, 0, sizeof(buf));
  1552. memset(auth, 0, sizeof(auth));
  1553. memset(serviceid, 0, sizeof(serviceid));
  1554. return;
  1555. }
  1556. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1557. * live introduction point, and note that the service descriptor is
  1558. * now out-of-date. */
  1559. int
  1560. rend_service_intro_established(origin_circuit_t *circuit,
  1561. const uint8_t *request,
  1562. size_t request_len)
  1563. {
  1564. rend_service_t *service;
  1565. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1566. (void) request;
  1567. (void) request_len;
  1568. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1569. log_warn(LD_PROTOCOL,
  1570. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1571. goto err;
  1572. }
  1573. tor_assert(circuit->rend_data);
  1574. service = rend_service_get_by_pk_digest(
  1575. circuit->rend_data->rend_pk_digest);
  1576. if (!service) {
  1577. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1578. circuit->_base.n_circ_id);
  1579. goto err;
  1580. }
  1581. service->desc_is_dirty = time(NULL);
  1582. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
  1583. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1584. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1585. log_info(LD_REND,
  1586. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1587. circuit->_base.n_circ_id, serviceid);
  1588. return 0;
  1589. err:
  1590. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1591. return -1;
  1592. }
  1593. /** Called once a circuit to a rendezvous point is established: sends a
  1594. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1595. */
  1596. void
  1597. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1598. {
  1599. rend_service_t *service;
  1600. char buf[RELAY_PAYLOAD_SIZE];
  1601. crypt_path_t *hop;
  1602. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1603. char hexcookie[9];
  1604. int reason;
  1605. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1606. tor_assert(circuit->cpath);
  1607. tor_assert(circuit->build_state);
  1608. #ifndef NON_ANONYMOUS_MODE_ENABLED
  1609. tor_assert(!(circuit->build_state->onehop_tunnel));
  1610. #endif
  1611. tor_assert(circuit->rend_data);
  1612. hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
  1613. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1614. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1615. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1616. log_info(LD_REND,
  1617. "Done building circuit %d to rendezvous with "
  1618. "cookie %s for service %s",
  1619. circuit->_base.n_circ_id, hexcookie, serviceid);
  1620. /* Clear the 'in-progress HS circ has timed out' flag for
  1621. * consistency with what happens on the client side; this line has
  1622. * no effect on Tor's behaviour. */
  1623. circuit->hs_circ_has_timed_out = 0;
  1624. /* If hop is NULL, another rend circ has already connected to this
  1625. * rend point. Close this circ. */
  1626. if (hop == NULL) {
  1627. log_info(LD_REND, "Another rend circ has already reached this rend point; "
  1628. "closing this rend circ.");
  1629. reason = END_CIRC_REASON_NONE;
  1630. goto err;
  1631. }
  1632. /* Remove our final cpath element from the reference, so that no
  1633. * other circuit will try to use it. Store it in
  1634. * pending_final_cpath for now to ensure that it will be freed if
  1635. * our rendezvous attempt fails. */
  1636. circuit->build_state->pending_final_cpath = hop;
  1637. circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
  1638. service = rend_service_get_by_pk_digest(
  1639. circuit->rend_data->rend_pk_digest);
  1640. if (!service) {
  1641. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1642. "rendezvous circuit.");
  1643. reason = END_CIRC_REASON_INTERNAL;
  1644. goto err;
  1645. }
  1646. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1647. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1648. if (crypto_dh_get_public(hop->dh_handshake_state,
  1649. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1650. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1651. reason = END_CIRC_REASON_INTERNAL;
  1652. goto err;
  1653. }
  1654. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1655. DIGEST_LEN);
  1656. /* Send the cell */
  1657. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1658. RELAY_COMMAND_RENDEZVOUS1,
  1659. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1660. circuit->cpath->prev)<0) {
  1661. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1662. reason = END_CIRC_REASON_INTERNAL;
  1663. goto err;
  1664. }
  1665. crypto_dh_free(hop->dh_handshake_state);
  1666. hop->dh_handshake_state = NULL;
  1667. /* Append the cpath entry. */
  1668. hop->state = CPATH_STATE_OPEN;
  1669. /* set the windows to default. these are the windows
  1670. * that bob thinks alice has.
  1671. */
  1672. hop->package_window = circuit_initial_package_window();
  1673. hop->deliver_window = CIRCWINDOW_START;
  1674. onion_append_to_cpath(&circuit->cpath, hop);
  1675. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1676. /* Change the circuit purpose. */
  1677. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
  1678. goto done;
  1679. err:
  1680. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1681. done:
  1682. memset(buf, 0, sizeof(buf));
  1683. memset(serviceid, 0, sizeof(serviceid));
  1684. memset(hexcookie, 0, sizeof(hexcookie));
  1685. return;
  1686. }
  1687. /*
  1688. * Manage introduction points
  1689. */
  1690. /** Return the (possibly non-open) introduction circuit ending at
  1691. * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
  1692. * (<b>desc_version</b> is ignored). Return NULL if no such service is
  1693. * found.
  1694. */
  1695. static origin_circuit_t *
  1696. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
  1697. {
  1698. origin_circuit_t *circ = NULL;
  1699. tor_assert(intro);
  1700. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1701. CIRCUIT_PURPOSE_S_INTRO))) {
  1702. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  1703. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1704. circ->rend_data) {
  1705. return circ;
  1706. }
  1707. }
  1708. circ = NULL;
  1709. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1710. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1711. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  1712. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1713. circ->rend_data) {
  1714. return circ;
  1715. }
  1716. }
  1717. return NULL;
  1718. }
  1719. /** Return a pointer to the rend_intro_point_t corresponding to the
  1720. * service-side introduction circuit <b>circ</b>. */
  1721. static rend_intro_point_t *
  1722. find_intro_point(origin_circuit_t *circ)
  1723. {
  1724. const char *serviceid;
  1725. rend_service_t *service = NULL;
  1726. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1727. TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  1728. tor_assert(circ->rend_data);
  1729. serviceid = circ->rend_data->onion_address;
  1730. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
  1731. if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
  1732. service = s;
  1733. break;
  1734. });
  1735. if (service == NULL) return NULL;
  1736. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
  1737. if (crypto_pk_cmp_keys(intro_point->intro_key, circ->intro_key) == 0) {
  1738. return intro_point;
  1739. });
  1740. return NULL;
  1741. }
  1742. /** Determine the responsible hidden service directories for the
  1743. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1744. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1745. * purposes. */
  1746. static void
  1747. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1748. smartlist_t *descs, const char *service_id,
  1749. int seconds_valid)
  1750. {
  1751. int i, j, failed_upload = 0;
  1752. smartlist_t *responsible_dirs = smartlist_new();
  1753. smartlist_t *successful_uploads = smartlist_new();
  1754. routerstatus_t *hs_dir;
  1755. for (i = 0; i < smartlist_len(descs); i++) {
  1756. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1757. /* Determine responsible dirs. */
  1758. if (hid_serv_get_responsible_directories(responsible_dirs,
  1759. desc->desc_id) < 0) {
  1760. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1761. "directories to post descriptors to.");
  1762. smartlist_free(responsible_dirs);
  1763. smartlist_free(successful_uploads);
  1764. return;
  1765. }
  1766. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1767. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1768. char *hs_dir_ip;
  1769. const node_t *node;
  1770. hs_dir = smartlist_get(responsible_dirs, j);
  1771. if (smartlist_digest_isin(renddesc->successful_uploads,
  1772. hs_dir->identity_digest))
  1773. /* Don't upload descriptor if we succeeded in doing so last time. */
  1774. continue;
  1775. node = node_get_by_id(hs_dir->identity_digest);
  1776. if (!node || !node_has_descriptor(node)) {
  1777. log_info(LD_REND, "Not launching upload for for v2 descriptor to "
  1778. "hidden service directory %s; we don't have its "
  1779. "router descriptor. Queuing for later upload.",
  1780. safe_str_client(routerstatus_describe(hs_dir)));
  1781. failed_upload = -1;
  1782. continue;
  1783. }
  1784. /* Send publish request. */
  1785. directory_initiate_command_routerstatus(hs_dir,
  1786. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1787. ROUTER_PURPOSE_GENERAL,
  1788. 1, NULL, desc->desc_str,
  1789. strlen(desc->desc_str), 0);
  1790. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1791. desc->desc_id, DIGEST_LEN);
  1792. hs_dir_ip = tor_dup_ip(hs_dir->addr);
  1793. log_info(LD_REND, "Launching upload for v2 descriptor for "
  1794. "service '%s' with descriptor ID '%s' with validity "
  1795. "of %d seconds to hidden service directory '%s' on "
  1796. "%s:%d.",
  1797. safe_str_client(service_id),
  1798. safe_str_client(desc_id_base32),
  1799. seconds_valid,
  1800. hs_dir->nickname,
  1801. hs_dir_ip,
  1802. hs_dir->or_port);
  1803. tor_free(hs_dir_ip);
  1804. /* Remember successful upload to this router for next time. */
  1805. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1806. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1807. }
  1808. smartlist_clear(responsible_dirs);
  1809. }
  1810. if (!failed_upload) {
  1811. if (renddesc->successful_uploads) {
  1812. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1813. smartlist_free(renddesc->successful_uploads);
  1814. renddesc->successful_uploads = NULL;
  1815. }
  1816. renddesc->all_uploads_performed = 1;
  1817. } else {
  1818. /* Remember which routers worked this time, so that we don't upload the
  1819. * descriptor to them again. */
  1820. if (!renddesc->successful_uploads)
  1821. renddesc->successful_uploads = smartlist_new();
  1822. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1823. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1824. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1825. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1826. }
  1827. });
  1828. }
  1829. smartlist_free(responsible_dirs);
  1830. smartlist_free(successful_uploads);
  1831. }
  1832. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  1833. * and upload it/them to the responsible hidden service directories.
  1834. */
  1835. static void
  1836. upload_service_descriptor(rend_service_t *service)
  1837. {
  1838. time_t now = time(NULL);
  1839. int rendpostperiod;
  1840. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1841. int uploaded = 0;
  1842. rendpostperiod = get_options()->RendPostPeriod;
  1843. /* Upload descriptor? */
  1844. if (get_options()->PublishHidServDescriptors) {
  1845. networkstatus_t *c = networkstatus_get_latest_consensus();
  1846. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1847. int seconds_valid, i, j, num_descs;
  1848. smartlist_t *descs = smartlist_new();
  1849. smartlist_t *client_cookies = smartlist_new();
  1850. /* Either upload a single descriptor (including replicas) or one
  1851. * descriptor for each authorized client in case of authorization
  1852. * type 'stealth'. */
  1853. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1854. smartlist_len(service->clients) : 1;
  1855. for (j = 0; j < num_descs; j++) {
  1856. crypto_pk_t *client_key = NULL;
  1857. rend_authorized_client_t *client = NULL;
  1858. smartlist_clear(client_cookies);
  1859. switch (service->auth_type) {
  1860. case REND_NO_AUTH:
  1861. /* Do nothing here. */
  1862. break;
  1863. case REND_BASIC_AUTH:
  1864. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1865. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1866. break;
  1867. case REND_STEALTH_AUTH:
  1868. client = smartlist_get(service->clients, j);
  1869. client_key = client->client_key;
  1870. smartlist_add(client_cookies, client->descriptor_cookie);
  1871. break;
  1872. }
  1873. /* Encode the current descriptor. */
  1874. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1875. now, 0,
  1876. service->auth_type,
  1877. client_key,
  1878. client_cookies);
  1879. if (seconds_valid < 0) {
  1880. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1881. "descriptor; not uploading.");
  1882. smartlist_free(descs);
  1883. smartlist_free(client_cookies);
  1884. return;
  1885. }
  1886. /* Post the current descriptors to the hidden service directories. */
  1887. rend_get_service_id(service->desc->pk, serviceid);
  1888. log_info(LD_REND, "Launching upload for hidden service %s",
  1889. serviceid);
  1890. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1891. seconds_valid);
  1892. /* Free memory for descriptors. */
  1893. for (i = 0; i < smartlist_len(descs); i++)
  1894. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1895. smartlist_clear(descs);
  1896. /* Update next upload time. */
  1897. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1898. > rendpostperiod)
  1899. service->next_upload_time = now + rendpostperiod;
  1900. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1901. service->next_upload_time = now + seconds_valid + 1;
  1902. else
  1903. service->next_upload_time = now + seconds_valid -
  1904. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1905. /* Post also the next descriptors, if necessary. */
  1906. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1907. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1908. now, 1,
  1909. service->auth_type,
  1910. client_key,
  1911. client_cookies);
  1912. if (seconds_valid < 0) {
  1913. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1914. "descriptor; not uploading.");
  1915. smartlist_free(descs);
  1916. smartlist_free(client_cookies);
  1917. return;
  1918. }
  1919. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1920. seconds_valid);
  1921. /* Free memory for descriptors. */
  1922. for (i = 0; i < smartlist_len(descs); i++)
  1923. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1924. smartlist_clear(descs);
  1925. }
  1926. }
  1927. smartlist_free(descs);
  1928. smartlist_free(client_cookies);
  1929. uploaded = 1;
  1930. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1931. }
  1932. }
  1933. /* If not uploaded, try again in one minute. */
  1934. if (!uploaded)
  1935. service->next_upload_time = now + 60;
  1936. /* Unmark dirty flag of this service. */
  1937. service->desc_is_dirty = 0;
  1938. }
  1939. /** Return the number of INTRODUCE2 cells this hidden service has received
  1940. * from this intro point. */
  1941. static int
  1942. intro_point_accepted_intro_count(rend_intro_point_t *intro)
  1943. {
  1944. return intro->accepted_introduce2_count;
  1945. }
  1946. /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
  1947. * should stop publishing it in new descriptors and eventually close
  1948. * it). */
  1949. static int
  1950. intro_point_should_expire_now(rend_intro_point_t *intro,
  1951. time_t now)
  1952. {
  1953. tor_assert(intro != NULL);
  1954. if (intro->time_published == -1) {
  1955. /* Don't expire an intro point if we haven't even published it yet. */
  1956. return 0;
  1957. }
  1958. if (intro->time_expiring != -1) {
  1959. /* We've already started expiring this intro point. *Don't* let
  1960. * this function's result 'flap'. */
  1961. return 1;
  1962. }
  1963. if (intro_point_accepted_intro_count(intro) >=
  1964. INTRO_POINT_LIFETIME_INTRODUCTIONS) {
  1965. /* This intro point has been used too many times. Expire it now. */
  1966. return 1;
  1967. }
  1968. if (intro->time_to_expire == -1) {
  1969. /* This intro point has been published, but we haven't picked an
  1970. * expiration time for it. Pick one now. */
  1971. int intro_point_lifetime_seconds =
  1972. INTRO_POINT_LIFETIME_MIN_SECONDS +
  1973. crypto_rand_int(INTRO_POINT_LIFETIME_MAX_SECONDS -
  1974. INTRO_POINT_LIFETIME_MIN_SECONDS);
  1975. /* Start the expiration timer now, rather than when the intro
  1976. * point was first published. There shouldn't be much of a time
  1977. * difference. */
  1978. intro->time_to_expire = now + intro_point_lifetime_seconds;
  1979. return 0;
  1980. }
  1981. /* This intro point has a time to expire set already. Use it. */
  1982. return (now >= intro->time_to_expire);
  1983. }
  1984. /** For every service, check how many intro points it currently has, and:
  1985. * - Pick new intro points as necessary.
  1986. * - Launch circuits to any new intro points.
  1987. */
  1988. void
  1989. rend_services_introduce(void)
  1990. {
  1991. int i,j,r;
  1992. const node_t *node;
  1993. rend_service_t *service;
  1994. rend_intro_point_t *intro;
  1995. int intro_point_set_changed, prev_intro_nodes;
  1996. unsigned int n_intro_points_unexpired;
  1997. unsigned int n_intro_points_to_open;
  1998. smartlist_t *intro_nodes;
  1999. time_t now;
  2000. const or_options_t *options = get_options();
  2001. intro_nodes = smartlist_new();
  2002. now = time(NULL);
  2003. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  2004. smartlist_clear(intro_nodes);
  2005. service = smartlist_get(rend_service_list, i);
  2006. tor_assert(service);
  2007. /* intro_point_set_changed becomes non-zero iff the set of intro
  2008. * points to be published in service's descriptor has changed. */
  2009. intro_point_set_changed = 0;
  2010. /* n_intro_points_unexpired collects the number of non-expiring
  2011. * intro points we have, so that we know how many new intro
  2012. * circuits we need to launch for this service. */
  2013. n_intro_points_unexpired = 0;
  2014. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  2015. /* One period has elapsed; we can try building circuits again. */
  2016. service->intro_period_started = now;
  2017. service->n_intro_circuits_launched = 0;
  2018. } else if (service->n_intro_circuits_launched >=
  2019. MAX_INTRO_CIRCS_PER_PERIOD) {
  2020. /* We have failed too many times in this period; wait for the next
  2021. * one before we try again. */
  2022. continue;
  2023. }
  2024. /* Find out which introduction points we have in progress for this
  2025. service. */
  2026. SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
  2027. intro) {
  2028. origin_circuit_t *intro_circ =
  2029. find_intro_circuit(intro, service->pk_digest);
  2030. if (intro->time_expiring + INTRO_POINT_EXPIRATION_GRACE_PERIOD > now) {
  2031. /* This intro point has completely expired. Remove it, and
  2032. * mark the circuit for close if it's still alive. */
  2033. if (intro_circ != NULL) {
  2034. circuit_mark_for_close(TO_CIRCUIT(intro_circ),
  2035. END_CIRC_REASON_FINISHED);
  2036. }
  2037. rend_intro_point_free(intro);
  2038. intro = NULL; /* SMARTLIST_DEL_CURRENT takes a name, not a value. */
  2039. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  2040. /* We don't need to set intro_point_set_changed here, because
  2041. * this intro point wouldn't have been published in a current
  2042. * descriptor anyway. */
  2043. continue;
  2044. }
  2045. node = node_get_by_id(intro->extend_info->identity_digest);
  2046. if (!node || !intro_circ) {
  2047. int removing_this_intro_point_changes_the_intro_point_set = 1;
  2048. log_info(LD_REND, "Giving up on %s as intro point for %s"
  2049. " (circuit disappeared).",
  2050. safe_str_client(extend_info_describe(intro->extend_info)),
  2051. safe_str_client(service->service_id));
  2052. rend_service_note_removing_intro_point(service, intro);
  2053. if (intro->time_expiring != -1) {
  2054. log_info(LD_REND, "We were already expiring the intro point; "
  2055. "no need to mark the HS descriptor as dirty over this.");
  2056. removing_this_intro_point_changes_the_intro_point_set = 0;
  2057. } else if (intro->listed_in_last_desc) {
  2058. log_info(LD_REND, "The intro point we are giving up on was "
  2059. "included in the last published descriptor. "
  2060. "Marking current descriptor as dirty.");
  2061. service->desc_is_dirty = now;
  2062. }
  2063. rend_intro_point_free(intro);
  2064. intro = NULL; /* SMARTLIST_DEL_CURRENT takes a name, not a value. */
  2065. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  2066. if (removing_this_intro_point_changes_the_intro_point_set)
  2067. intro_point_set_changed = 1;
  2068. }
  2069. if (intro != NULL && intro_point_should_expire_now(intro, now)) {
  2070. log_info(LD_REND, "Expiring %s as intro point for %s.",
  2071. safe_str_client(extend_info_describe(intro->extend_info)),
  2072. safe_str_client(service->service_id));
  2073. rend_service_note_removing_intro_point(service, intro);
  2074. /* The polite (and generally Right) way to expire an intro
  2075. * point is to establish a new one to replace it, publish a
  2076. * new descriptor that doesn't list any expiring intro points,
  2077. * and *then*, once our upload attempts for the new descriptor
  2078. * have ended (whether in success or failure), close the
  2079. * expiring intro points.
  2080. *
  2081. * Unfortunately, we can't find out when the new descriptor
  2082. * has actually been uploaded, so we'll have to settle for a
  2083. * five-minute timer. Start it. XXXX024 This sucks. */
  2084. intro->time_expiring = now;
  2085. intro_point_set_changed = 1;
  2086. }
  2087. if (intro != NULL && intro->time_expiring == -1)
  2088. ++n_intro_points_unexpired;
  2089. if (node)
  2090. smartlist_add(intro_nodes, (void*)node);
  2091. } SMARTLIST_FOREACH_END(intro);
  2092. if (!intro_point_set_changed &&
  2093. (n_intro_points_unexpired >= service->n_intro_points_wanted)) {
  2094. continue;
  2095. }
  2096. /* Remember how many introduction circuits we started with.
  2097. *
  2098. * prev_intro_nodes serves a different purpose than
  2099. * n_intro_points_unexpired -- this variable tells us where our
  2100. * previously-created intro points end and our new ones begin in
  2101. * the intro-point list, so we don't have to launch the circuits
  2102. * at the same time as we create the intro points they correspond
  2103. * to. XXXX This is daft. */
  2104. prev_intro_nodes = smartlist_len(service->intro_nodes);
  2105. /* We have enough directory information to start establishing our
  2106. * intro points. We want to end up with n_intro_points_wanted
  2107. * intro points, but if we're just starting, we launch two extra
  2108. * circuits and use the first n_intro_points_wanted that complete.
  2109. *
  2110. * The ones after the first three will be converted to 'general'
  2111. * internal circuits in rend_service_intro_has_opened(), and then
  2112. * we'll drop them from the list of intro points next time we
  2113. * go through the above "find out which introduction points we have
  2114. * in progress" loop. */
  2115. n_intro_points_to_open = (service->n_intro_points_wanted +
  2116. (prev_intro_nodes == 0 ? 2 : 0));
  2117. for (j = (int)n_intro_points_unexpired;
  2118. j < (int)n_intro_points_to_open;
  2119. ++j) { /* XXXX remove casts */
  2120. router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
  2121. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  2122. flags |= CRN_ALLOW_INVALID;
  2123. node = router_choose_random_node(intro_nodes,
  2124. options->ExcludeNodes, flags);
  2125. if (!node) {
  2126. log_warn(LD_REND,
  2127. "Could only establish %d introduction points for %s; "
  2128. "wanted %u.",
  2129. smartlist_len(service->intro_nodes), service->service_id,
  2130. n_intro_points_to_open);
  2131. break;
  2132. }
  2133. intro_point_set_changed = 1;
  2134. smartlist_add(intro_nodes, (void*)node);
  2135. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  2136. intro->extend_info = extend_info_from_node(node, 0);
  2137. intro->intro_key = crypto_pk_new();
  2138. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  2139. intro->time_published = -1;
  2140. intro->time_to_expire = -1;
  2141. intro->time_expiring = -1;
  2142. smartlist_add(service->intro_nodes, intro);
  2143. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  2144. safe_str_client(node_describe(node)),
  2145. safe_str_client(service->service_id));
  2146. }
  2147. /* If there's no need to launch new circuits, stop here. */
  2148. if (!intro_point_set_changed)
  2149. continue;
  2150. /* Establish new introduction points. */
  2151. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  2152. intro = smartlist_get(service->intro_nodes, j);
  2153. r = rend_service_launch_establish_intro(service, intro);
  2154. if (r<0) {
  2155. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  2156. safe_str_client(extend_info_describe(intro->extend_info)),
  2157. safe_str_client(service->service_id));
  2158. }
  2159. }
  2160. }
  2161. smartlist_free(intro_nodes);
  2162. }
  2163. /** Regenerate and upload rendezvous service descriptors for all
  2164. * services, if necessary. If the descriptor has been dirty enough
  2165. * for long enough, definitely upload; else only upload when the
  2166. * periodic timeout has expired.
  2167. *
  2168. * For the first upload, pick a random time between now and two periods
  2169. * from now, and pick it independently for each service.
  2170. */
  2171. void
  2172. rend_consider_services_upload(time_t now)
  2173. {
  2174. int i;
  2175. rend_service_t *service;
  2176. int rendpostperiod = get_options()->RendPostPeriod;
  2177. if (!get_options()->PublishHidServDescriptors)
  2178. return;
  2179. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  2180. service = smartlist_get(rend_service_list, i);
  2181. if (!service->next_upload_time) { /* never been uploaded yet */
  2182. /* The fixed lower bound of 30 seconds ensures that the descriptor
  2183. * is stable before being published. See comment below. */
  2184. service->next_upload_time =
  2185. now + 30 + crypto_rand_int(2*rendpostperiod);
  2186. }
  2187. if (service->next_upload_time < now ||
  2188. (service->desc_is_dirty &&
  2189. service->desc_is_dirty < now-30)) {
  2190. /* if it's time, or if the directory servers have a wrong service
  2191. * descriptor and ours has been stable for 30 seconds, upload a
  2192. * new one of each format. */
  2193. rend_service_update_descriptor(service);
  2194. upload_service_descriptor(service);
  2195. }
  2196. }
  2197. }
  2198. /** True if the list of available router descriptors might have changed so
  2199. * that we should have a look whether we can republish previously failed
  2200. * rendezvous service descriptors. */
  2201. static int consider_republishing_rend_descriptors = 1;
  2202. /** Called when our internal view of the directory has changed, so that we
  2203. * might have router descriptors of hidden service directories available that
  2204. * we did not have before. */
  2205. void
  2206. rend_hsdir_routers_changed(void)
  2207. {
  2208. consider_republishing_rend_descriptors = 1;
  2209. }
  2210. /** Consider republication of v2 rendezvous service descriptors that failed
  2211. * previously, but without regenerating descriptor contents.
  2212. */
  2213. void
  2214. rend_consider_descriptor_republication(void)
  2215. {
  2216. int i;
  2217. rend_service_t *service;
  2218. if (!consider_republishing_rend_descriptors)
  2219. return;
  2220. consider_republishing_rend_descriptors = 0;
  2221. if (!get_options()->PublishHidServDescriptors)
  2222. return;
  2223. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  2224. service = smartlist_get(rend_service_list, i);
  2225. if (service->desc && !service->desc->all_uploads_performed) {
  2226. /* If we failed in uploading a descriptor last time, try again *without*
  2227. * updating the descriptor's contents. */
  2228. upload_service_descriptor(service);
  2229. }
  2230. }
  2231. }
  2232. /** Log the status of introduction points for all rendezvous services
  2233. * at log severity <b>severity</b>.
  2234. */
  2235. void
  2236. rend_service_dump_stats(int severity)
  2237. {
  2238. int i,j;
  2239. rend_service_t *service;
  2240. rend_intro_point_t *intro;
  2241. const char *safe_name;
  2242. origin_circuit_t *circ;
  2243. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  2244. service = smartlist_get(rend_service_list, i);
  2245. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  2246. service->directory);
  2247. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  2248. intro = smartlist_get(service->intro_nodes, j);
  2249. safe_name = safe_str_client(intro->extend_info->nickname);
  2250. circ = find_intro_circuit(intro, service->pk_digest);
  2251. if (!circ) {
  2252. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  2253. j, safe_name);
  2254. continue;
  2255. }
  2256. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  2257. j, safe_name, circuit_state_to_string(circ->_base.state));
  2258. }
  2259. }
  2260. }
  2261. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  2262. * 'circ', and look up the port and address based on conn-\>port.
  2263. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  2264. * or 0 for success.
  2265. */
  2266. int
  2267. rend_service_set_connection_addr_port(edge_connection_t *conn,
  2268. origin_circuit_t *circ)
  2269. {
  2270. rend_service_t *service;
  2271. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  2272. smartlist_t *matching_ports;
  2273. rend_service_port_config_t *chosen_port;
  2274. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  2275. tor_assert(circ->rend_data);
  2276. log_debug(LD_REND,"beginning to hunt for addr/port");
  2277. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  2278. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  2279. service = rend_service_get_by_pk_digest(
  2280. circ->rend_data->rend_pk_digest);
  2281. if (!service) {
  2282. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  2283. "rendezvous circuit %d; closing.",
  2284. serviceid, circ->_base.n_circ_id);
  2285. return -1;
  2286. }
  2287. matching_ports = smartlist_new();
  2288. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  2289. {
  2290. if (conn->_base.port == p->virtual_port) {
  2291. smartlist_add(matching_ports, p);
  2292. }
  2293. });
  2294. chosen_port = smartlist_choose(matching_ports);
  2295. smartlist_free(matching_ports);
  2296. if (chosen_port) {
  2297. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  2298. conn->_base.port = chosen_port->real_port;
  2299. return 0;
  2300. }
  2301. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  2302. conn->_base.port,serviceid);
  2303. return -1;
  2304. }