dirserv.c 33 KB

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