rendservice.c 73 KB

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