rendservice.c 74 KB

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