router.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. extern or_options_t options; /* command-line and config-file options */
  6. /************************************************************/
  7. /* private keys */
  8. static crypto_pk_env_t *onionkey=NULL;
  9. static crypto_pk_env_t *linkkey=NULL;
  10. static crypto_pk_env_t *identitykey=NULL;
  11. void set_onion_key(crypto_pk_env_t *k) {
  12. onionkey = k;
  13. }
  14. crypto_pk_env_t *get_onion_key(void) {
  15. assert(onionkey);
  16. return onionkey;
  17. }
  18. void set_link_key(crypto_pk_env_t *k)
  19. {
  20. linkkey = k;
  21. }
  22. crypto_pk_env_t *get_link_key(void)
  23. {
  24. assert(linkkey);
  25. return linkkey;
  26. }
  27. void set_identity_key(crypto_pk_env_t *k) {
  28. identitykey = k;
  29. }
  30. crypto_pk_env_t *get_identity_key(void) {
  31. assert(identitykey);
  32. return identitykey;
  33. }
  34. /************************************************************/
  35. /* Try to read an RSA key from 'fname'. If 'fname' doesn't exist, create a new
  36. * RSA key and save it in 'fname'. Return the read/created key, or NULL on
  37. * error.
  38. */
  39. crypto_pk_env_t *init_key_from_file(const char *fname)
  40. {
  41. crypto_pk_env_t *prkey = NULL;
  42. int fd = -1;
  43. FILE *file = NULL;
  44. if (!(prkey = crypto_new_pk_env())) {
  45. log(LOG_ERR, "Error creating crypto environment.");
  46. goto error;
  47. }
  48. switch(file_status(fname)) {
  49. case FN_DIR:
  50. case FN_ERROR:
  51. log(LOG_ERR, "Can't read key from %s", fname);
  52. goto error;
  53. case FN_NOENT:
  54. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  55. if (crypto_pk_generate_key(prkey)) {
  56. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  57. goto error;
  58. }
  59. if (crypto_pk_check_key(prkey) <= 0) {
  60. log(LOG_ERR, "Generated key seems invalid");
  61. goto error;
  62. }
  63. log(LOG_INFO, "Generated key seems valid");
  64. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  65. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  66. goto error;
  67. }
  68. return prkey;
  69. case FN_FILE:
  70. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  71. log(LOG_ERR, "Error loading private key.");
  72. goto error;
  73. }
  74. return prkey;
  75. default:
  76. assert(0);
  77. }
  78. error:
  79. if (prkey)
  80. crypto_free_pk_env(prkey);
  81. if (fd >= 0 && !file)
  82. close(fd);
  83. if (file)
  84. fclose(file);
  85. return NULL;
  86. }
  87. int init_keys(void) {
  88. char keydir[512];
  89. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  90. char *cp;
  91. const char *tmp, *mydesc;
  92. crypto_pk_env_t *prkey;
  93. /* OP's don't need keys. Just initialize the TLS context.*/
  94. if (!options.ORPort) {
  95. assert(!options.DirPort);
  96. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  97. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  98. return -1;
  99. }
  100. return 0;
  101. }
  102. assert(options.DataDirectory);
  103. if (strlen(options.DataDirectory) > (512-128)) {
  104. log_fn(LOG_ERR, "DataDirectory is too long.");
  105. return -1;
  106. }
  107. if (check_private_dir(options.DataDirectory, 1)) {
  108. return -1;
  109. }
  110. sprintf(keydir,"%s/keys",options.DataDirectory);
  111. if (check_private_dir(keydir, 1)) {
  112. return -1;
  113. }
  114. cp = keydir + strlen(keydir); /* End of string. */
  115. /* 1. Read identity key. Make it if none is found. */
  116. strcpy(cp, "/identity.key");
  117. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  118. prkey = init_key_from_file(keydir);
  119. if (!prkey) return -1;
  120. set_identity_key(prkey);
  121. /* 2. Read onion key. Make it if none is found. */
  122. strcpy(cp, "/onion.key");
  123. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  124. prkey = init_key_from_file(keydir);
  125. if (!prkey) return -1;
  126. set_onion_key(prkey);
  127. /* 3. Initialize link key and TLS context. */
  128. strcpy(cp, "/link.key");
  129. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  130. prkey = init_key_from_file(keydir);
  131. if (!prkey) return -1;
  132. set_link_key(prkey);
  133. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  134. log_fn(LOG_ERR, "Error initializing TLS context");
  135. return -1;
  136. }
  137. /* 4. Dump router descriptor to 'router.desc' */
  138. /* Must be called after keys are initialized. */
  139. if (!(router_get_my_descriptor())) {
  140. log_fn(LOG_ERR, "Error initializing descriptor.");
  141. return -1;
  142. }
  143. /* We need to add our own fingerprint so it gets recognized. */
  144. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  145. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  146. return -1;
  147. }
  148. tmp = mydesc = router_get_my_descriptor();
  149. if (dirserv_add_descriptor(&tmp) != 1) {
  150. log(LOG_ERR, "Unable to add own descriptor to directory.");
  151. return -1;
  152. }
  153. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  154. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  155. if (write_str_to_file(keydir, mydesc)) {
  156. return -1;
  157. }
  158. /* 5. Dump fingerprint to 'fingerprint' */
  159. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  160. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  161. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  162. strcpy(fingerprint, options.Nickname);
  163. strcat(fingerprint, " ");
  164. if (crypto_pk_get_fingerprint(get_identity_key(),
  165. fingerprint+strlen(fingerprint))<0) {
  166. log_fn(LOG_ERR, "Error computing fingerprint");
  167. return -1;
  168. }
  169. strcat(fingerprint, "\n");
  170. if (write_str_to_file(keydir, fingerprint))
  171. return -1;
  172. if(!options.DirPort)
  173. return 0;
  174. /* 6. [dirserver only] load approved-routers file */
  175. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  176. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  177. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  178. log_fn(LOG_ERR, "Error loading fingerprints");
  179. return -1;
  180. }
  181. /* 7. [dirserver only] load old directory, if it's there */
  182. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  183. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  184. cp = read_file_to_str(keydir);
  185. if(!cp) {
  186. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  187. } else {
  188. if(dirserv_init_from_directory_string(cp) < 0) {
  189. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  190. free(cp);
  191. return -1;
  192. }
  193. free(cp);
  194. }
  195. /* success */
  196. return 0;
  197. }
  198. /************************************************************/
  199. static routerinfo_t *desc_routerinfo = NULL; /* my descriptor */
  200. static char descriptor[8192]; /* string representation of my descriptor */
  201. void router_retry_connections(void) {
  202. int i;
  203. routerinfo_t *router;
  204. routerlist_t *rl;
  205. router_get_routerlist(&rl);
  206. for (i=0;i<rl->n_routers;i++) {
  207. router = rl->routers[i];
  208. if(!connection_exact_get_by_addr_port(router->addr,router->or_port)) {
  209. /* not in the list */
  210. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  211. connection_or_connect(router);
  212. }
  213. }
  214. }
  215. void router_upload_dir_desc_to_dirservers(void) {
  216. const char *s;
  217. s = router_get_my_descriptor();
  218. if (!s) {
  219. log_fn(LOG_WARN, "No descriptor; skipping upload");
  220. return;
  221. }
  222. router_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  223. }
  224. void router_post_to_dirservers(uint8_t purpose, const char *payload, int payload_len) {
  225. int i;
  226. routerinfo_t *router;
  227. routerlist_t *rl;
  228. router_get_routerlist(&rl);
  229. if(!rl)
  230. return;
  231. for(i=0;i<rl->n_routers;i++) {
  232. router = rl->routers[i];
  233. if(router->dir_port > 0)
  234. directory_initiate_command(router, purpose, payload, payload_len);
  235. }
  236. }
  237. static void router_add_exit_policy_from_config_helper(char *s, routerinfo_t *router) {
  238. char *e;
  239. int last=0;
  240. char line[1024];
  241. if(!s) {
  242. log_fn(LOG_INFO,"No exit policy configured. Ok.");
  243. return; /* nothing to see here */
  244. }
  245. if(!*s) {
  246. log_fn(LOG_INFO,"Exit policy is empty. Ok.");
  247. return; /* nothing to see here */
  248. }
  249. for(;;) {
  250. e = strchr(s,',');
  251. if(!e) {
  252. last = 1;
  253. strncpy(line,s,1023);
  254. } else {
  255. memcpy(line,s, ((e-s)<1023)?(e-s):1023);
  256. line[e-s] = 0;
  257. }
  258. line[1023]=0;
  259. log_fn(LOG_DEBUG,"Adding new entry '%s'",line);
  260. if(router_add_exit_policy_from_string(router,line) < 0)
  261. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", line);
  262. if(last)
  263. return;
  264. s = e+1;
  265. }
  266. }
  267. #define DefaultExitPolicy "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,accept *:20-22,accept *:53,accept *:79-80,accept *:110,accept *:143,accept *:443,accept *:873,accept *:993,accept *:995,accept *:1024-65535,reject *:*"
  268. static void router_add_exit_policy_from_config(routerinfo_t *router) {
  269. router_add_exit_policy_from_config_helper(options.ExitPolicy, router);
  270. if(strstr(options.ExitPolicy," *:*") == NULL) {
  271. /* if exitpolicy includes a *:* line, then we're done. Else, append
  272. * the default exitpolicy. */
  273. router_add_exit_policy_from_config_helper(DefaultExitPolicy, router);
  274. }
  275. }
  276. /* Return false if my exit policy says to allow connection to conn.
  277. * Else return true.
  278. */
  279. int router_compare_to_my_exit_policy(connection_t *conn) {
  280. assert(desc_routerinfo);
  281. assert(conn->addr); /* make sure it's resolved to something. this
  282. way we can't get a 'maybe' below. */
  283. return router_compare_addr_to_exit_policy(conn->addr, conn->port,
  284. desc_routerinfo->exit_policy);
  285. }
  286. const char *router_get_my_descriptor(void) {
  287. if (!desc_routerinfo) {
  288. if (router_rebuild_descriptor())
  289. return NULL;
  290. }
  291. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  292. return descriptor;
  293. }
  294. int router_rebuild_descriptor(void) {
  295. routerinfo_t *ri;
  296. ri = tor_malloc_zero(sizeof(routerinfo_t));
  297. ri->address = tor_strdup(options.Address);
  298. ri->nickname = tor_strdup(options.Nickname);
  299. /* No need to set addr. */
  300. ri->or_port = options.ORPort;
  301. ri->socks_port = options.SocksPort;
  302. ri->dir_port = options.DirPort;
  303. ri->published_on = time(NULL);
  304. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  305. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  306. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  307. ri->bandwidthrate = options.BandwidthRate;
  308. ri->bandwidthburst = options.BandwidthBurst;
  309. ri->exit_policy = NULL; /* zero it out first */
  310. router_add_exit_policy_from_config(ri);
  311. if (desc_routerinfo)
  312. routerinfo_free(desc_routerinfo);
  313. desc_routerinfo = ri;
  314. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  315. log_fn(LOG_WARN, "Couldn't dump router to string.");
  316. return -1;
  317. }
  318. return 0;
  319. }
  320. static void get_platform_str(char *platform, int len)
  321. {
  322. snprintf(platform, len-1, "Tor %s on %s", VERSION, get_uname());
  323. platform[len-1] = '\0';
  324. return;
  325. }
  326. /* XXX need to audit this thing and count fenceposts. maybe
  327. * refactor so we don't have to keep asking if we're
  328. * near the end of maxlen?
  329. */
  330. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  331. int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  332. crypto_pk_env_t *ident_key) {
  333. char *onion_pkey;
  334. char *link_pkey;
  335. char *identity_pkey;
  336. struct in_addr in;
  337. char platform[256];
  338. char digest[20];
  339. char signature[128];
  340. char published[32];
  341. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  342. int written;
  343. int result=0;
  344. struct exit_policy_t *tmpe;
  345. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  346. char *s_tmp, *s_dup;
  347. const char *cp;
  348. routerinfo_t *ri_tmp;
  349. #endif
  350. get_platform_str(platform, sizeof(platform));
  351. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  352. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  353. return -1;
  354. }
  355. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  356. &onion_pkey,&onion_pkeylen)<0) {
  357. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  358. return -1;
  359. }
  360. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  361. &identity_pkey,&identity_pkeylen)<0) {
  362. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  363. return -1;
  364. }
  365. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  366. &link_pkey,&link_pkeylen)<0) {
  367. log_fn(LOG_WARN,"write link_pkey to string failed!");
  368. return -1;
  369. }
  370. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  371. result = snprintf(s, maxlen,
  372. "router %s %s %d %d %d %d\n"
  373. "platform %s\n"
  374. "published %s\n"
  375. "onion-key\n%s"
  376. "link-key\n%s"
  377. "signing-key\n%s",
  378. router->nickname,
  379. router->address,
  380. router->or_port,
  381. router->socks_port,
  382. router->dir_port,
  383. (int) router->bandwidthrate,
  384. /* XXXBC also write bandwidthburst */
  385. platform,
  386. published,
  387. onion_pkey, link_pkey, identity_pkey);
  388. free(onion_pkey);
  389. free(link_pkey);
  390. free(identity_pkey);
  391. if(result < 0 || result >= maxlen) {
  392. /* apparently different glibcs do different things on snprintf error.. so check both */
  393. return -1;
  394. }
  395. written = result;
  396. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  397. in.s_addr = htonl(tmpe->addr);
  398. result = snprintf(s+written, maxlen-written, "%s %s",
  399. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  400. tmpe->msk == 0 ? "*" : inet_ntoa(in));
  401. if(result < 0 || result+written > maxlen) {
  402. /* apparently different glibcs do different things on snprintf error.. so check both */
  403. return -1;
  404. }
  405. written += result;
  406. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  407. in.s_addr = htonl(tmpe->msk);
  408. result = snprintf(s+written, maxlen-written, "/%s", inet_ntoa(in));
  409. if (result<0 || result+written > maxlen)
  410. return -1;
  411. written += result;
  412. }
  413. if (tmpe->prt_min == 0 && tmpe->prt_max == 65535) {
  414. if (written > maxlen-4)
  415. return -1;
  416. strcat(s+written, ":*\n");
  417. written += 3;
  418. } else if (tmpe->prt_min == tmpe->prt_max) {
  419. result = snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  420. if (result<0 || result+written > maxlen)
  421. return -1;
  422. written += result;
  423. } else {
  424. result = snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  425. tmpe->prt_max);
  426. if (result<0 || result+written > maxlen)
  427. return -1;
  428. written += result;
  429. }
  430. } /* end for */
  431. if (written > maxlen-256) /* Not enough room for signature. */
  432. return -1;
  433. strcat(s+written, "router-signature\n");
  434. written += strlen(s+written);
  435. s[written] = '\0';
  436. if (router_get_router_hash(s, digest) < 0)
  437. return -1;
  438. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  439. log_fn(LOG_WARN, "Error signing digest");
  440. return -1;
  441. }
  442. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  443. written += strlen(s+written);
  444. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  445. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  446. return -1;
  447. }
  448. written += strlen(s+written);
  449. strcat(s+written, "-----END SIGNATURE-----\n");
  450. written += strlen(s+written);
  451. if (written > maxlen-2)
  452. return -1;
  453. /* include a last '\n' */
  454. s[written] = '\n';
  455. s[written+1] = 0;
  456. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  457. cp = s_tmp = s_dup = tor_strdup(s);
  458. ri_tmp = router_get_entry_from_string(cp, NULL);
  459. if (!ri_tmp) {
  460. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  461. s);
  462. return -1;
  463. }
  464. free(s_dup);
  465. routerinfo_free(ri_tmp);
  466. #endif
  467. return written+1;
  468. }
  469. /*
  470. Local Variables:
  471. mode:c
  472. indent-tabs-mode:nil
  473. c-basic-offset:2
  474. End:
  475. */