rendservice.c 76 KB

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