dirserv.c 33 KB

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