rendservice.c 86 KB

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