rendservice.c 74 KB

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