rendservice.c 74 KB

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