rendservice.c 94 KB

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