rendservice.c 92 KB

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