dirserv.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dirserv_c_id[] = "$Id$";
  6. #include "or.h"
  7. /**
  8. * \file dirserv.c
  9. * \brief Directory server core implementation. Manages directory
  10. * contents and generates directories.
  11. **/
  12. /** How far in the future do we allow a router to get? (seconds) */
  13. #define ROUTER_ALLOW_SKEW (60*60*12) /* 12 hours */
  14. /** How many seconds do we wait before regenerating the directory? */
  15. #define DIR_REGEN_SLACK_TIME 5
  16. /** Do we need to regenerate the directory when someone asks for it? */
  17. static int the_directory_is_dirty = 1;
  18. static int runningrouters_is_dirty = 1;
  19. static void directory_remove_invalid(void);
  20. static int dirserv_regenerate_directory(void);
  21. /* Should be static; exposed for testing */
  22. int add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list);
  23. /************** Fingerprint handling code ************/
  24. typedef struct fingerprint_entry_t {
  25. char *nickname;
  26. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a NUL */
  27. } fingerprint_entry_t;
  28. /** List of nickname-\>identity fingerprint mappings for all the routers
  29. * that we recognize. Used to prevent Sybil attacks. */
  30. static smartlist_t *fingerprint_list = NULL;
  31. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  32. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  33. * new, or 1 if we replaced the old value.
  34. */
  35. int /* Should be static; exposed for testing */
  36. add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list)
  37. {
  38. int i;
  39. fingerprint_entry_t *ent;
  40. tor_assert(nickname);
  41. tor_assert(fp);
  42. tor_assert(list);
  43. for (i = 0; i < smartlist_len(list); ++i) {
  44. ent = smartlist_get(list, i);
  45. if (!strcasecmp(ent->nickname,nickname)) {
  46. tor_free(ent->fingerprint);
  47. ent->fingerprint = tor_strdup(fp);
  48. return 1;
  49. }
  50. }
  51. ent = tor_malloc(sizeof(fingerprint_entry_t));
  52. ent->nickname = tor_strdup(nickname);
  53. ent->fingerprint = tor_strdup(fp);
  54. tor_strstrip(ent->fingerprint, " ");
  55. smartlist_add(list, ent);
  56. return 0;
  57. }
  58. /** Add the nickname and fingerprint for this OR to the
  59. * global list of recognized identity key fingerprints. */
  60. int
  61. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  62. {
  63. char fp[FINGERPRINT_LEN+1];
  64. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  65. log_fn(LOG_ERR, "Error computing fingerprint");
  66. return -1;
  67. }
  68. if (!fingerprint_list)
  69. fingerprint_list = smartlist_create();
  70. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  71. return 0;
  72. }
  73. /** Parse the nickname-\>fingerprint mappings stored in the file named
  74. * <b>fname</b>. The file format is line-based, with each non-blank
  75. * holding one nickname, some space, and a fingerprint for that
  76. * nickname. On success, replace the current fingerprint list with
  77. * the contents of <b>fname</b> and return 0. On failure, leave the
  78. * current fingerprint list untouched, and return -1. */
  79. int
  80. dirserv_parse_fingerprint_file(const char *fname)
  81. {
  82. char *cf;
  83. char *nickname, *fingerprint;
  84. smartlist_t *fingerprint_list_new;
  85. int result;
  86. struct config_line_t *front=NULL, *list;
  87. cf = read_file_to_str(fname, 0);
  88. if (!cf) {
  89. log_fn(LOG_WARN, "Cannot open fingerprint file %s", fname);
  90. return -1;
  91. }
  92. result = config_get_lines(cf, &front);
  93. tor_free(cf);
  94. if (result < 0) {
  95. log_fn(LOG_WARN, "Error reading from fingerprint file");
  96. return -1;
  97. }
  98. fingerprint_list_new = smartlist_create();
  99. for (list=front; list; list=list->next) {
  100. nickname = list->key; fingerprint = list->value;
  101. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  102. log(LOG_NOTICE, "Nickname '%s' too long in fingerprint file. Skipping.", nickname);
  103. continue;
  104. }
  105. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  106. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  107. log_fn(LOG_NOTICE, "Invalid fingerprint (nickname '%s', fingerprint %s). Skipping.",
  108. nickname, fingerprint);
  109. continue;
  110. }
  111. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  112. /* If you approved an OR called "client", then clients who use
  113. * the default nickname could all be rejected. That's no good. */
  114. log(LOG_NOTICE,
  115. "Authorizing a nickname '%s' would break many clients; skipping.",
  116. DEFAULT_CLIENT_NICKNAME);
  117. continue;
  118. }
  119. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new) != 0)
  120. log(LOG_NOTICE, "Duplicate nickname '%s'.", nickname);
  121. }
  122. config_free_lines(front);
  123. dirserv_free_fingerprint_list();
  124. fingerprint_list = fingerprint_list_new;
  125. /* Delete any routers whose fingerprints we no longer recognize */
  126. directory_remove_invalid();
  127. return 0;
  128. }
  129. /** Check whether <b>router</b> has a nickname/identity key combination that
  130. * we recognize from the fingerprint list. Return 1 if router's
  131. * identity and nickname match, -1 if we recognize the nickname but
  132. * the identity key is wrong, and 0 if the nickname is not known. */
  133. int
  134. dirserv_router_fingerprint_is_known(const routerinfo_t *router)
  135. {
  136. int i, found=0;
  137. fingerprint_entry_t *ent =NULL;
  138. char fp[FINGERPRINT_LEN+1];
  139. if (!fingerprint_list)
  140. fingerprint_list = smartlist_create();
  141. log_fn(LOG_DEBUG, "%d fingerprints known.", smartlist_len(fingerprint_list));
  142. for (i=0;i<smartlist_len(fingerprint_list);++i) {
  143. ent = smartlist_get(fingerprint_list, i);
  144. log_fn(LOG_DEBUG,"%s vs %s", router->nickname, ent->nickname);
  145. if (!strcasecmp(router->nickname,ent->nickname)) {
  146. found = 1;
  147. break;
  148. }
  149. }
  150. if (!found) { /* No such server known */
  151. log_fn(LOG_INFO,"no fingerprint found for '%s'",router->nickname);
  152. return 0;
  153. }
  154. if (crypto_pk_get_fingerprint(router->identity_pkey, fp, 0)) {
  155. log_fn(LOG_WARN,"error computing fingerprint");
  156. return -1;
  157. }
  158. if (0==strcasecmp(ent->fingerprint, fp)) {
  159. log_fn(LOG_DEBUG,"good fingerprint for '%s'",router->nickname);
  160. return 1; /* Right fingerprint. */
  161. } else {
  162. log_fn(LOG_WARN,"mismatched fingerprint for '%s': expected '%s' got '%s'",
  163. router->nickname, ent->fingerprint, fp);
  164. return -1; /* Wrong fingerprint. */
  165. }
  166. }
  167. /** If we are an authoritative dirserver, and the list of approved
  168. * servers contains one whose identity key digest is <b>digest</b>,
  169. * return that router's nickname. Otherwise return NULL. */
  170. const char *
  171. dirserv_get_nickname_by_digest(const char *digest)
  172. {
  173. char hexdigest[HEX_DIGEST_LEN+1];
  174. if (!fingerprint_list)
  175. return NULL;
  176. tor_assert(digest);
  177. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  178. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  179. { if (!strcasecmp(hexdigest, ent->fingerprint))
  180. return ent->nickname; } );
  181. return NULL;
  182. }
  183. /** Clear the current fingerprint list. */
  184. void
  185. dirserv_free_fingerprint_list()
  186. {
  187. int i;
  188. fingerprint_entry_t *ent;
  189. if (!fingerprint_list)
  190. return;
  191. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  192. ent = smartlist_get(fingerprint_list, i);
  193. tor_free(ent->nickname);
  194. tor_free(ent->fingerprint);
  195. tor_free(ent);
  196. }
  197. smartlist_free(fingerprint_list);
  198. fingerprint_list = NULL;
  199. }
  200. /*
  201. * Descriptor list
  202. */
  203. /** List of routerinfo_t for all server descriptors that this dirserv
  204. * is holding.
  205. * XXXX This should eventually get coalesced into routerlist.c
  206. */
  207. static smartlist_t *descriptor_list = NULL;
  208. /** Release all storage that the dirserv is holding for server
  209. * descriptors. */
  210. void
  211. dirserv_free_descriptors()
  212. {
  213. if (!descriptor_list)
  214. return;
  215. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  216. routerinfo_free(ri));
  217. smartlist_clear(descriptor_list);
  218. }
  219. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  220. * unless we're configured to not care. Return 0 if all ok. */
  221. static int
  222. dirserv_router_has_valid_address(routerinfo_t *ri)
  223. {
  224. struct in_addr iaddr;
  225. if (get_options()->DirAllowPrivateAddresses)
  226. return 0; /* whatever it is, we're fine with it */
  227. if (!tor_inet_aton(ri->address, &iaddr)) {
  228. log_fn(LOG_INFO,"Router '%s' published non-IP address '%s'. Refusing.",
  229. ri->nickname, ri->address);
  230. return -1;
  231. }
  232. if (is_internal_IP(ntohl(iaddr.s_addr))) {
  233. log_fn(LOG_INFO,"Router '%s' published internal IP address '%s'. Refusing.",
  234. ri->nickname, ri->address);
  235. return -1; /* it's a private IP, we should reject it */
  236. }
  237. return 0;
  238. }
  239. /** Parse the server descriptor at *desc and maybe insert it into the
  240. * list of server descriptors, and (if the descriptor is well-formed)
  241. * advance *desc immediately past the descriptor's end. Set msg to a
  242. * message that should be passed back to the origin of this descriptor, or
  243. * to NULL.
  244. *
  245. * Return 1 if descriptor is well-formed and accepted;
  246. * 0 if well-formed and server is unapproved but accepted;
  247. * -1 if it looks vaguely like a router descriptor but rejected;
  248. * -2 if we can't find a router descriptor in *desc.
  249. */
  250. int
  251. dirserv_add_descriptor(const char **desc, const char **msg)
  252. {
  253. routerinfo_t *ri = NULL, *ri_old=NULL;
  254. int i, r, found=-1;
  255. char *start, *end;
  256. char *desc_tmp = NULL;
  257. size_t desc_len;
  258. time_t now;
  259. int verified=1; /* whether we knew its fingerprint already */
  260. tor_assert(msg);
  261. *msg = NULL;
  262. if (!descriptor_list)
  263. descriptor_list = smartlist_create();
  264. start = strstr(*desc, "router ");
  265. if (!start) {
  266. log_fn(LOG_WARN, "no 'router' line found. This is not a descriptor.");
  267. return -2;
  268. }
  269. if ((end = strstr(start+6, "\nrouter "))) {
  270. ++end; /* Include NL. */
  271. } else if ((end = strstr(start+6, "\ndirectory-signature"))) {
  272. ++end;
  273. } else {
  274. end = start+strlen(start);
  275. }
  276. desc_len = end-start;
  277. desc_tmp = tor_strndup(start, desc_len); /* Is this strndup still needed???*/
  278. /* Check: is the descriptor syntactically valid? */
  279. ri = router_parse_entry_from_string(desc_tmp, NULL);
  280. tor_free(desc_tmp);
  281. if (!ri) {
  282. log(LOG_WARN, "Couldn't parse descriptor");
  283. *msg = "Rejected: Couldn't parse server descriptor.";
  284. return -1;
  285. }
  286. /* Okay. Now check whether the fingerprint is recognized. */
  287. r = dirserv_router_fingerprint_is_known(ri);
  288. if (r==-1) {
  289. log_fn(LOG_WARN, "Known nickname '%s', wrong fingerprint. Not adding (ContactInfo '%s', platform '%s').",
  290. ri->nickname, ri->contact_info ? ri->contact_info : "",
  291. ri->platform ? ri->platform : "");
  292. *msg = "Rejected: There is already a verified server with this nickname and a different fingerprint.";
  293. routerinfo_free(ri);
  294. *desc = end;
  295. return -1;
  296. } else if (r==0) {
  297. char fp[FINGERPRINT_LEN+1];
  298. log_fn(LOG_INFO, "Unknown nickname '%s' (%s:%d). Will try to add.",
  299. ri->nickname, ri->address, ri->or_port);
  300. if (crypto_pk_get_fingerprint(ri->identity_pkey, fp, 1) < 0) {
  301. log_fn(LOG_WARN, "Error computing fingerprint for '%s'", ri->nickname);
  302. } else {
  303. log_fn(LOG_INFO, "Fingerprint line: %s %s", ri->nickname, fp);
  304. }
  305. verified = 0;
  306. }
  307. /* Is there too much clock skew? */
  308. now = time(NULL);
  309. if (ri->published_on > now+ROUTER_ALLOW_SKEW) {
  310. log_fn(LOG_NOTICE, "Publication time for nickname '%s' is too far (%d minutes) in the future; possible clock skew. Not adding (ContactInfo '%s', platform '%s').",
  311. ri->nickname, (int)((ri->published_on-now)/60),
  312. ri->contact_info ? ri->contact_info : "",
  313. ri->platform ? ri->platform : "");
  314. *msg = "Rejected: Your clock is set too far in the future, or your timezone is not correct.";
  315. routerinfo_free(ri);
  316. *desc = end;
  317. return -1;
  318. }
  319. if (ri->published_on < now-ROUTER_MAX_AGE) {
  320. log_fn(LOG_NOTICE, "Publication time for router with nickname '%s' is too far (%d minutes) in the past. Not adding (ContactInfo '%s', platform '%s').",
  321. ri->nickname, (int)((now-ri->published_on)/60),
  322. ri->contact_info ? ri->contact_info : "",
  323. ri->platform ? ri->platform : "");
  324. *msg = "Rejected: Server is expired, or your clock is too far in the past, or your timezone is not correct.";
  325. routerinfo_free(ri);
  326. *desc = end;
  327. return -1;
  328. }
  329. if (dirserv_router_has_valid_address(ri) < 0) {
  330. log_fn(LOG_NOTICE, "Router with nickname '%s' has invalid address '%s'. Not adding (ContactInfo '%s', platform '%s').",
  331. ri->nickname, ri->address,
  332. ri->contact_info ? ri->contact_info : "",
  333. ri->platform ? ri->platform : "");
  334. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  335. routerinfo_free(ri);
  336. *desc = end;
  337. return -1;
  338. }
  339. /* Do we already have an entry for this router? */
  340. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  341. ri_old = smartlist_get(descriptor_list, i);
  342. if (!memcmp(ri->identity_digest, ri_old->identity_digest, DIGEST_LEN)) {
  343. found = i;
  344. break;
  345. }
  346. }
  347. if (found >= 0) {
  348. char hex_digest[HEX_DIGEST_LEN+1];
  349. base16_encode(hex_digest, HEX_DIGEST_LEN+1, ri->identity_digest,DIGEST_LEN);
  350. /* if so, decide whether to update it. */
  351. if (ri_old->published_on >= ri->published_on) {
  352. /* We already have a newer or equal-time descriptor */
  353. log_fn(LOG_INFO,"We already have a new enough desc for server %s (nickname '%s'). Not adding.",hex_digest,ri->nickname);
  354. *msg = "We already have a newer descriptor.";
  355. /* This isn't really an error; return success. */
  356. routerinfo_free(ri);
  357. *desc = end;
  358. return verified;
  359. }
  360. /* We don't alrady have a newer one; we'll update this one. */
  361. log_fn(LOG_INFO,"Dirserv updating desc for server %s (nickname '%s')",hex_digest,ri->nickname);
  362. *msg = verified?"Verified server updated":"Unverified server updated. (Have you sent us your key fingerprint?)";
  363. routerinfo_free(ri_old);
  364. smartlist_del_keeporder(descriptor_list, found);
  365. } else {
  366. /* Add at the end. */
  367. log_fn(LOG_INFO,"Dirserv adding desc for nickname '%s'",ri->nickname);
  368. *msg = verified?"Verified server added":"Unverified server added. (Have you sent us your key fingerprint?)";
  369. }
  370. ri->is_verified = verified ||
  371. tor_version_as_new_as(ri->platform,"0.1.0.2-rc");
  372. smartlist_add(descriptor_list, ri);
  373. *desc = end;
  374. directory_set_dirty();
  375. return verified;
  376. }
  377. /** Remove all descriptors whose nicknames or fingerprints no longer
  378. * are allowed by our fingerprint list. (Descriptors that used to be
  379. * good can become bad when we reload the fingerprint list.)
  380. */
  381. static void
  382. directory_remove_invalid(void)
  383. {
  384. int i;
  385. int r;
  386. routerinfo_t *ent;
  387. if (!descriptor_list)
  388. descriptor_list = smartlist_create();
  389. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  390. ent = smartlist_get(descriptor_list, i);
  391. r = dirserv_router_fingerprint_is_known(ent);
  392. if (r<0) {
  393. log(LOG_INFO, "Router '%s' is now verified with a key; removing old router with same name and different key.",
  394. ent->nickname);
  395. routerinfo_free(ent);
  396. smartlist_del(descriptor_list, i--);
  397. } else if (r>0 && !ent->is_verified) {
  398. log(LOG_INFO, "Router '%s' is now approved.", ent->nickname);
  399. ent->is_verified = 1;
  400. } else if (r==0 && ent->is_verified) {
  401. log(LOG_INFO, "Router '%s' is no longer approved.", ent->nickname);
  402. ent->is_verified = 0;
  403. }
  404. }
  405. }
  406. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  407. * directory, we will rebuild it instead of reusing the most recently
  408. * generated one.
  409. */
  410. void
  411. directory_set_dirty()
  412. {
  413. time_t now = time(NULL);
  414. if (!the_directory_is_dirty)
  415. the_directory_is_dirty = now;
  416. if (!runningrouters_is_dirty)
  417. runningrouters_is_dirty = now;
  418. }
  419. /** Load all descriptors from a directory stored in the string
  420. * <b>dir</b>.
  421. */
  422. int
  423. dirserv_load_from_directory_string(const char *dir)
  424. {
  425. const char *cp = dir, *m;
  426. while (1) {
  427. cp = strstr(cp, "\nrouter ");
  428. if (!cp) break;
  429. ++cp;
  430. if (dirserv_add_descriptor(&cp,&m) < -1) {
  431. /* only fail if parsing failed; keep going if simply rejected */
  432. return -1;
  433. }
  434. --cp; /*Back up to newline.*/
  435. }
  436. return 0;
  437. }
  438. /**
  439. * Allocate and return a description of the status of the server <b>desc</b>,
  440. * for use in a router-status line. The server is listed
  441. * as running iff <b>is_live</b> is true.
  442. */
  443. static char *
  444. list_single_server_status(routerinfo_t *desc, int is_live)
  445. {
  446. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  447. char *cp;
  448. tor_assert(desc);
  449. cp = buf;
  450. if (!is_live) {
  451. *cp++ = '!';
  452. }
  453. if (desc->is_verified) {
  454. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  455. cp += strlen(cp);
  456. *cp++ = '=';
  457. }
  458. *cp++ = '$';
  459. base16_encode(cp, HEX_DIGEST_LEN+1, desc->identity_digest,
  460. DIGEST_LEN);
  461. return tor_strdup(buf);
  462. }
  463. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  464. * contents of a router-status line, and store it in
  465. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  466. */
  467. int
  468. list_server_status(smartlist_t *routers, char **router_status_out)
  469. {
  470. /* List of entries in a router-status style: An optional !, then an optional
  471. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  472. smartlist_t *rs_entries;
  473. int authdir_mode = get_options()->AuthoritativeDir;
  474. tor_assert(router_status_out);
  475. rs_entries = smartlist_create();
  476. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  477. {
  478. int is_live;
  479. connection_t *conn;
  480. conn = connection_get_by_identity_digest(
  481. ri->identity_digest, CONN_TYPE_OR);
  482. if (authdir_mode) {
  483. /* Treat a router as alive if
  484. * - It's me, and I'm not hibernating.
  485. * or - we're connected to it. */
  486. is_live = (router_is_me(ri) && !we_are_hibernating()) ||
  487. (conn && conn->state == OR_CONN_STATE_OPEN);
  488. } else {
  489. is_live = ri->is_running;
  490. }
  491. smartlist_add(rs_entries, list_single_server_status(ri, is_live));
  492. });
  493. *router_status_out = smartlist_join_strings(rs_entries, " ", 0,NULL);
  494. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  495. smartlist_free(rs_entries);
  496. return 0;
  497. }
  498. /** Remove any descriptors from the directory that are more than <b>age</b>
  499. * seconds old.
  500. */
  501. void
  502. dirserv_remove_old_servers(int age)
  503. {
  504. int i;
  505. time_t cutoff;
  506. routerinfo_t *ent;
  507. if (!descriptor_list)
  508. descriptor_list = smartlist_create();
  509. cutoff = time(NULL) - age;
  510. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  511. ent = smartlist_get(descriptor_list, i);
  512. if (ent->published_on <= cutoff) {
  513. /* descriptor_list[i] is too old. Remove it. */
  514. routerinfo_free(ent);
  515. smartlist_del(descriptor_list, i--);
  516. directory_set_dirty();
  517. }
  518. }
  519. }
  520. /** Generate a new directory and write it into a newly allocated string.
  521. * Point *<b>dir_out</b> to the allocated string. Sign the
  522. * directory with <b>private_key</b>. Return 0 on success, -1 on
  523. * failure.
  524. */
  525. int
  526. dirserv_dump_directory_to_string(char **dir_out,
  527. crypto_pk_env_t *private_key)
  528. {
  529. char *cp;
  530. char *router_status;
  531. char *identity_pkey; /* Identity key, DER64-encoded. */
  532. char *recommended_versions;
  533. char digest[20];
  534. char signature[128];
  535. char published[33];
  536. time_t published_on;
  537. char *buf = NULL;
  538. size_t buf_len;
  539. int i;
  540. size_t identity_pkey_len;
  541. tor_assert(dir_out);
  542. *dir_out = NULL;
  543. if (!descriptor_list)
  544. descriptor_list = smartlist_create();
  545. if (list_server_status(descriptor_list, &router_status))
  546. return -1;
  547. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  548. &identity_pkey_len)<0) {
  549. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  550. return -1;
  551. }
  552. {
  553. smartlist_t *versions;
  554. struct config_line_t *ln;
  555. versions = smartlist_create();
  556. for (ln = get_options()->RecommendedVersions; ln; ln = ln->next) {
  557. smartlist_split_string(versions, ln->value, ",",
  558. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  559. }
  560. recommended_versions = smartlist_join_strings(versions,",",0,NULL);
  561. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  562. smartlist_free(versions);
  563. }
  564. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  565. published_on = time(NULL);
  566. format_iso_time(published, published_on);
  567. buf_len = 2048+strlen(recommended_versions)+
  568. strlen(router_status);
  569. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  570. buf_len += strlen(ri->signed_descriptor));
  571. buf = tor_malloc(buf_len);
  572. /* We'll be comparing against buf_len throughout the rest of the
  573. function, though strictly speaking we shouldn't be able to exceed
  574. it. This is C, after all, so we may as well check for buffer
  575. overruns.*/
  576. tor_snprintf(buf, buf_len,
  577. "signed-directory\n"
  578. "published %s\n"
  579. "recommended-software %s\n"
  580. "router-status %s\n"
  581. "dir-signing-key\n%s\n",
  582. published, recommended_versions, router_status,
  583. identity_pkey);
  584. tor_free(recommended_versions);
  585. tor_free(router_status);
  586. tor_free(identity_pkey);
  587. i = strlen(buf);
  588. cp = buf+i;
  589. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  590. if (strlcat(buf, ri->signed_descriptor, buf_len) >= buf_len)
  591. goto truncated);
  592. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  593. signature.
  594. */
  595. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  596. goto truncated;
  597. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  598. goto truncated;
  599. if (strlcat(buf, "\n", buf_len) >= buf_len)
  600. goto truncated;
  601. if (router_get_dir_hash(buf,digest)) {
  602. log_fn(LOG_WARN,"couldn't compute digest");
  603. tor_free(buf);
  604. return -1;
  605. }
  606. if (crypto_pk_private_sign(private_key, signature, digest, 20) < 0) {
  607. log_fn(LOG_WARN,"couldn't sign digest");
  608. tor_free(buf);
  609. return -1;
  610. }
  611. log(LOG_DEBUG,"generated directory digest begins with %s",hex_str(digest,4));
  612. if (strlcat(cp, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  613. goto truncated;
  614. i = strlen(buf);
  615. cp = buf+i;
  616. if (base64_encode(cp, buf_len-i, signature, 128) < 0) {
  617. log_fn(LOG_WARN,"couldn't base64-encode signature");
  618. tor_free(buf);
  619. return -1;
  620. }
  621. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  622. goto truncated;
  623. *dir_out = buf;
  624. return 0;
  625. truncated:
  626. log_fn(LOG_WARN,"tried to exceed string length.");
  627. tor_free(buf);
  628. return -1;
  629. }
  630. /** Most recently generated encoded signed directory. */
  631. static char *the_directory = NULL;
  632. static size_t the_directory_len = 0;
  633. static char *the_directory_z = NULL;
  634. static size_t the_directory_z_len = 0;
  635. /** DOCDOC */
  636. typedef struct cached_dir_t {
  637. char *dir;
  638. char *dir_z;
  639. size_t dir_len;
  640. size_t dir_z_len;
  641. time_t published;
  642. } cached_dir_t;
  643. /* used only by non-auth dirservers */
  644. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  645. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  646. /** If we have no cached directory, or it is older than <b>when</b>, then
  647. * replace it with <b>directory</b>, published at <b>when</b>.
  648. */
  649. void
  650. dirserv_set_cached_directory(const char *directory, time_t when,
  651. int is_running_routers)
  652. {
  653. time_t now;
  654. cached_dir_t *d;
  655. now = time(NULL);
  656. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  657. if (when<=d->published) {
  658. log_fn(LOG_INFO, "Ignoring old directory; not caching.");
  659. } else if (when>=now+ROUTER_MAX_AGE) {
  660. log_fn(LOG_INFO, "Ignoring future directory; not caching.");
  661. } else {
  662. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  663. log_fn(LOG_DEBUG, "Caching directory.");
  664. tor_free(d->dir);
  665. d->dir = tor_strdup(directory);
  666. d->dir_len = strlen(directory);
  667. tor_free(d->dir_z);
  668. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  669. ZLIB_METHOD)) {
  670. log_fn(LOG_WARN,"Error compressing cached directory");
  671. }
  672. d->published = when;
  673. if (!is_running_routers) {
  674. char filename[512];
  675. tor_snprintf(filename,sizeof(filename),"%s/cached-directory", get_options()->DataDirectory);
  676. if (write_str_to_file(filename,cached_directory.dir,0) < 0) {
  677. log_fn(LOG_NOTICE, "Couldn't write cached directory to disk. Ignoring.");
  678. }
  679. }
  680. }
  681. }
  682. /** Set *<b>directory</b> to the most recently generated encoded signed
  683. * directory, generating a new one as necessary. If not an authoritative
  684. * directory may return 0 if no directory is yet cached.*/
  685. size_t
  686. dirserv_get_directory(const char **directory, int compress)
  687. {
  688. if (!get_options()->AuthoritativeDir) {
  689. cached_dir_t *d = &cached_directory;
  690. *directory = compress ? d->dir_z : d->dir;
  691. if (*directory) {
  692. return compress ? d->dir_z_len : d->dir_len;
  693. } else {
  694. /* no directory yet retrieved */
  695. return 0;
  696. }
  697. }
  698. if (the_directory_is_dirty &&
  699. the_directory_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  700. if (dirserv_regenerate_directory())
  701. return 0;
  702. } else {
  703. log(LOG_INFO,"Directory still clean, reusing.");
  704. }
  705. *directory = compress ? the_directory_z : the_directory;
  706. return compress ? the_directory_z_len : the_directory_len;
  707. }
  708. /**
  709. * Generate a fresh directory (authdirservers only.)
  710. */
  711. static int
  712. dirserv_regenerate_directory(void)
  713. {
  714. char *new_directory=NULL;
  715. if (dirserv_dump_directory_to_string(&new_directory,
  716. get_identity_key())) {
  717. log(LOG_WARN, "Error creating directory.");
  718. tor_free(new_directory);
  719. return -1;
  720. }
  721. tor_free(the_directory);
  722. the_directory = new_directory;
  723. the_directory_len = strlen(the_directory);
  724. log_fn(LOG_INFO,"New directory (size %d):\n%s",(int)the_directory_len,
  725. the_directory);
  726. tor_free(the_directory_z);
  727. if (tor_gzip_compress(&the_directory_z, &the_directory_z_len,
  728. the_directory, the_directory_len,
  729. ZLIB_METHOD)) {
  730. log_fn(LOG_WARN, "Error gzipping directory.");
  731. return -1;
  732. }
  733. the_directory_is_dirty = 0;
  734. /* Save the directory to disk so we re-load it quickly on startup.
  735. */
  736. dirserv_set_cached_directory(the_directory, time(NULL), 0);
  737. return 0;
  738. }
  739. static char *the_runningrouters=NULL;
  740. static size_t the_runningrouters_len=0;
  741. static char *the_runningrouters_z=NULL;
  742. static size_t the_runningrouters_z_len=0;
  743. /** Replace the current running-routers list with a newly generated one. */
  744. static int
  745. generate_runningrouters(crypto_pk_env_t *private_key)
  746. {
  747. char *s=NULL, *cp;
  748. char *router_status=NULL;
  749. char digest[DIGEST_LEN];
  750. char signature[PK_BYTES];
  751. int i;
  752. char published[33];
  753. size_t len;
  754. time_t published_on;
  755. char *identity_pkey; /* Identity key, DER64-encoded. */
  756. size_t identity_pkey_len;
  757. if (!descriptor_list)
  758. descriptor_list = smartlist_create();
  759. if (list_server_status(descriptor_list, &router_status)) {
  760. goto err;
  761. }
  762. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  763. &identity_pkey_len)<0) {
  764. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  765. goto err;
  766. }
  767. published_on = time(NULL);
  768. format_iso_time(published, published_on);
  769. len = 2048+strlen(router_status);
  770. s = tor_malloc_zero(len);
  771. tor_snprintf(s, len, "network-status\n"
  772. "published %s\n"
  773. "router-status %s\n"
  774. "dir-signing-key\n%s"
  775. "directory-signature %s\n"
  776. "-----BEGIN SIGNATURE-----\n",
  777. published, router_status, identity_pkey, get_options()->Nickname);
  778. tor_free(router_status);
  779. tor_free(identity_pkey);
  780. if (router_get_runningrouters_hash(s,digest)) {
  781. log_fn(LOG_WARN,"couldn't compute digest");
  782. goto err;
  783. }
  784. if (crypto_pk_private_sign(private_key, signature, digest, 20) < 0) {
  785. log_fn(LOG_WARN,"couldn't sign digest");
  786. goto err;
  787. }
  788. i = strlen(s);
  789. cp = s+i;
  790. if (base64_encode(cp, len-i, signature, 128) < 0) {
  791. log_fn(LOG_WARN,"couldn't base64-encode signature");
  792. goto err;
  793. }
  794. if (strlcat(s, "-----END SIGNATURE-----\n", len) >= len) {
  795. goto err;
  796. }
  797. tor_free(the_runningrouters);
  798. the_runningrouters = s;
  799. the_runningrouters_len = strlen(s);
  800. tor_free(the_runningrouters_z);
  801. if (tor_gzip_compress(&the_runningrouters_z, &the_runningrouters_z_len,
  802. the_runningrouters, the_runningrouters_len,
  803. ZLIB_METHOD)) {
  804. log_fn(LOG_WARN, "Error gzipping runningrouters");
  805. return -1;
  806. }
  807. runningrouters_is_dirty = 0;
  808. /* We don't cache running-routers to disk, so there's no point in
  809. * authdirservers caching it. */
  810. /* dirserv_set_cached_directory(the_runningrouters, time(NULL), 1); */
  811. return 0;
  812. err:
  813. tor_free(s);
  814. tor_free(router_status);
  815. return -1;
  816. }
  817. /** Set *<b>rr</b> to the most recently generated encoded signed
  818. * running-routers list, generating a new one as necessary. Return the
  819. * size of the directory on success, and 0 on failure. */
  820. size_t
  821. dirserv_get_runningrouters(const char **rr, int compress)
  822. {
  823. if (!get_options()->AuthoritativeDir) {
  824. cached_dir_t *d = &cached_runningrouters;
  825. *rr = compress ? d->dir_z : d->dir;
  826. if (*rr) {
  827. return compress ? d->dir_z_len : d->dir_len;
  828. } else {
  829. /* no directory yet retrieved */
  830. return 0;
  831. }
  832. }
  833. if (runningrouters_is_dirty &&
  834. runningrouters_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  835. if (generate_runningrouters(get_identity_key())) {
  836. log_fn(LOG_ERR, "Couldn't generate running-routers list?");
  837. return 0;
  838. }
  839. }
  840. *rr = compress ? the_runningrouters_z : the_runningrouters;
  841. return compress ? the_runningrouters_z_len : the_runningrouters_len;
  842. }
  843. /** Called when a TLS handshake has completed successfully with a
  844. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  845. * a certificate with digest <b>digest_rcvd</b> and nickname
  846. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  847. * descriptors for that address/port combination must be unusable:
  848. * delete them if they are not verified.
  849. *
  850. * Also, if as_advertised is 1, then inform the reachability checker
  851. * that we could get to this guy.
  852. */
  853. void
  854. dirserv_orconn_tls_done(const char *address,
  855. uint16_t or_port,
  856. const char *digest_rcvd,
  857. const char *nickname_rcvd,
  858. int as_advertised) //XXXRD
  859. {
  860. int i;
  861. tor_assert(address);
  862. tor_assert(digest_rcvd);
  863. tor_assert(nickname_rcvd);
  864. if (!descriptor_list)
  865. return;
  866. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  867. routerinfo_t *ri = smartlist_get(descriptor_list, i);
  868. int drop = 0;
  869. if (ri->is_verified)
  870. continue;
  871. if (!strcasecmp(address, ri->address) &&
  872. or_port == ri->or_port) {
  873. /* We have a router at the same address! */
  874. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  875. log_fn(LOG_NOTICE, "Dropping descriptor: nickname '%s' does not match nickname '%s' in cert from %s:%d",
  876. ri->nickname, nickname_rcvd, address, or_port);
  877. drop = 1;
  878. } else if (memcmp(ri->identity_digest, digest_rcvd, DIGEST_LEN)) {
  879. log_fn(LOG_NOTICE, "Dropping descriptor: identity key does not match key in cert from %s:%d",
  880. address, or_port);
  881. drop = 1;
  882. }
  883. if (drop) {
  884. routerinfo_free(ri);
  885. smartlist_del(descriptor_list, i--);
  886. directory_set_dirty();
  887. }
  888. }
  889. }
  890. }
  891. /** Release all storage used by the directory server. */
  892. void
  893. dirserv_free_all(void)
  894. {
  895. if (fingerprint_list) {
  896. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  897. { tor_free(fp->nickname);
  898. tor_free(fp->fingerprint);
  899. tor_free(fp); });
  900. smartlist_free(fingerprint_list);
  901. fingerprint_list = NULL;
  902. }
  903. if (descriptor_list) {
  904. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  905. routerinfo_free(ri));
  906. smartlist_free(descriptor_list);
  907. descriptor_list = NULL;
  908. }
  909. tor_free(the_directory);
  910. tor_free(the_directory_z);
  911. the_directory_len = 0;
  912. the_directory_z_len = 0;
  913. tor_free(the_runningrouters);
  914. tor_free(the_runningrouters_z);
  915. the_runningrouters_len = 0;
  916. the_runningrouters_z_len = 0;
  917. tor_free(cached_directory.dir);
  918. tor_free(cached_directory.dir_z);
  919. tor_free(cached_runningrouters.dir);
  920. tor_free(cached_runningrouters.dir_z);
  921. memset(&cached_directory, 0, sizeof(cached_directory));
  922. memset(&cached_runningrouters, 0, sizeof(cached_runningrouters));
  923. }