router.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. #include "or.h"
  7. /**
  8. * \file router.c
  9. * \brief OR functionality, including key maintenance, generating
  10. * and uploading server descriptors, retrying OR connections.
  11. **/
  12. extern long stats_n_seconds_uptime;
  13. /** Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  14. /************************************************************/
  15. /*****
  16. * Key management: ORs only.
  17. *****/
  18. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  19. */
  20. static tor_mutex_t *key_lock=NULL;
  21. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  22. static crypto_pk_env_t *onionkey=NULL;
  23. static crypto_pk_env_t *lastonionkey=NULL;
  24. static crypto_pk_env_t *identitykey=NULL;
  25. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  26. * to update onionkey correctly, call rotate_onion_key().
  27. */
  28. void set_onion_key(crypto_pk_env_t *k) {
  29. tor_mutex_acquire(key_lock);
  30. onionkey = k;
  31. onionkey_set_at = time(NULL);
  32. tor_mutex_release(key_lock);
  33. mark_my_descriptor_dirty();
  34. }
  35. /** Return the current onion key. Requires that the onion key has been
  36. * loaded or generated. */
  37. crypto_pk_env_t *get_onion_key(void) {
  38. tor_assert(onionkey);
  39. return onionkey;
  40. }
  41. /** Return the onion key that was current before the most recent onion
  42. * key rotation. If no rotation has been performed since this process
  43. * started, return NULL.
  44. */
  45. crypto_pk_env_t *get_previous_onion_key(void) {
  46. return lastonionkey;
  47. }
  48. void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  49. {
  50. tor_assert(key);
  51. tor_assert(last);
  52. tor_mutex_acquire(key_lock);
  53. *key = crypto_pk_dup_key(onionkey);
  54. if (lastonionkey)
  55. *last = crypto_pk_dup_key(lastonionkey);
  56. else
  57. *last = NULL;
  58. tor_mutex_release(key_lock);
  59. }
  60. /** Return the time when the onion key was last set. This is either the time
  61. * when the process launched, or the time of the most recent key rotation since
  62. * the process launched.
  63. */
  64. time_t get_onion_key_set_at(void) {
  65. return onionkey_set_at;
  66. }
  67. /** Set the current identity key to k.
  68. */
  69. void set_identity_key(crypto_pk_env_t *k) {
  70. identitykey = k;
  71. }
  72. /** Returns the current identity key; requires that the identity key has been
  73. * set.
  74. */
  75. crypto_pk_env_t *get_identity_key(void) {
  76. tor_assert(identitykey);
  77. return identitykey;
  78. }
  79. /** Return true iff the identity key has been set. */
  80. int identity_key_is_set(void) {
  81. return identitykey != NULL;
  82. }
  83. /** Replace the previous onion key with the current onion key, and generate
  84. * a new previous onion key. Immediately after calling this function,
  85. * the OR should:
  86. * - schedule all previous cpuworkers to shut down _after_ processing
  87. * pending work. (This will cause fresh cpuworkers to be generated.)
  88. * - generate and upload a fresh routerinfo.
  89. */
  90. void rotate_onion_key(void)
  91. {
  92. char fname[512];
  93. char fname_prev[512];
  94. crypto_pk_env_t *prkey;
  95. tor_snprintf(fname,sizeof(fname),
  96. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  97. tor_snprintf(fname_prev,sizeof(fname_prev),
  98. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  99. if (!(prkey = crypto_new_pk_env())) {
  100. log(LOG_ERR, "Error creating crypto environment.");
  101. goto error;
  102. }
  103. if (crypto_pk_generate_key(prkey)) {
  104. log(LOG_ERR, "Error generating onion key");
  105. goto error;
  106. }
  107. if (file_status(fname) == FN_FILE) {
  108. if (replace_file(fname, fname_prev))
  109. goto error;
  110. }
  111. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  112. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  113. goto error;
  114. }
  115. tor_mutex_acquire(key_lock);
  116. if (lastonionkey)
  117. crypto_free_pk_env(lastonionkey);
  118. log_fn(LOG_INFO, "Rotating onion key");
  119. lastonionkey = onionkey;
  120. set_onion_key(prkey);
  121. tor_mutex_release(key_lock);
  122. return;
  123. error:
  124. log_fn(LOG_WARN, "Couldn't rotate onion key.");
  125. }
  126. /** The latest calculated bandwidth usage for our node. */
  127. static int bw_capacity = 0;
  128. /** Tuck <b>bw</b> away so we can produce it when somebody
  129. * calls router_get_bandwidth_capacity() below.
  130. */
  131. void router_set_bandwidth_capacity(int bw) {
  132. bw_capacity = bw;
  133. }
  134. /** Return the value we tucked away above, or zero by default. */
  135. int router_get_bandwidth_capacity(void) {
  136. if (we_are_hibernating())
  137. return 0;
  138. return bw_capacity;
  139. }
  140. /* Read an RSA secret key key from a file that was once named fname_old,
  141. * but is now named fname_new. Rename the file from old to new as needed.
  142. */
  143. static crypto_pk_env_t *
  144. init_key_from_file_name_changed(const char *fname_old,
  145. const char *fname_new)
  146. {
  147. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  148. /* The new filename is there, or both are, or neither is. */
  149. return init_key_from_file(fname_new);
  150. /* The old filename exists, and the new one doesn't. Rename and load. */
  151. if (rename(fname_old, fname_new) < 0) {
  152. log_fn(LOG_ERR, "Couldn't rename %s to %s: %s", fname_old, fname_new,
  153. strerror(errno));
  154. return NULL;
  155. }
  156. return init_key_from_file(fname_new);
  157. }
  158. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  159. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  160. * key, or NULL on error.
  161. */
  162. crypto_pk_env_t *init_key_from_file(const char *fname)
  163. {
  164. crypto_pk_env_t *prkey = NULL;
  165. FILE *file = NULL;
  166. if (!(prkey = crypto_new_pk_env())) {
  167. log(LOG_ERR, "Error creating crypto environment.");
  168. goto error;
  169. }
  170. switch(file_status(fname)) {
  171. case FN_DIR:
  172. case FN_ERROR:
  173. log(LOG_ERR, "Can't read key from %s", fname);
  174. goto error;
  175. case FN_NOENT:
  176. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  177. if (crypto_pk_generate_key(prkey)) {
  178. log(LOG_ERR, "Error generating onion key");
  179. goto error;
  180. }
  181. if (crypto_pk_check_key(prkey) <= 0) {
  182. log(LOG_ERR, "Generated key seems invalid");
  183. goto error;
  184. }
  185. log(LOG_INFO, "Generated key seems valid");
  186. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  187. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  188. goto error;
  189. }
  190. return prkey;
  191. case FN_FILE:
  192. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  193. log(LOG_ERR, "Error loading private key.");
  194. goto error;
  195. }
  196. return prkey;
  197. default:
  198. tor_assert(0);
  199. }
  200. error:
  201. if (prkey)
  202. crypto_free_pk_env(prkey);
  203. if (file)
  204. fclose(file);
  205. return NULL;
  206. }
  207. /** Initialize all OR private keys, and the TLS context, as necessary.
  208. * On OPs, this only initializes the tls context.
  209. */
  210. int init_keys(void) {
  211. /* XXX009 Two problems with how this is called:
  212. * 1. It should be idempotent for servers, so we can call init_keys
  213. * as much as we need to.
  214. * 2. Clients should rotate their identity keys at least whenever
  215. * their IPs change.
  216. */
  217. char keydir[512];
  218. char keydir2[512];
  219. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  220. char *cp;
  221. const char *tmp, *mydesc, *datadir;
  222. crypto_pk_env_t *prkey;
  223. char digest[20];
  224. or_options_t *options = get_options();
  225. if (!key_lock)
  226. key_lock = tor_mutex_new();
  227. /* OP's don't need persistent keys; just make up an identity and
  228. * initialize the TLS context. */
  229. if (!server_mode(options)) {
  230. if (!(prkey = crypto_new_pk_env()))
  231. return -1;
  232. if (crypto_pk_generate_key(prkey))
  233. return -1;
  234. set_identity_key(prkey);
  235. /* Create a TLS context; default the client nickname to "client". */
  236. if (tor_tls_context_new(get_identity_key(), 1,
  237. options->Nickname ? options->Nickname : "client",
  238. MAX_SSL_KEY_LIFETIME) < 0) {
  239. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  240. return -1;
  241. }
  242. return 0;
  243. }
  244. /* Make sure DataDirectory exists, and is private. */
  245. datadir = options->DataDirectory;
  246. if (check_private_dir(datadir, CPD_CREATE)) {
  247. return -1;
  248. }
  249. /* Check the key directory. */
  250. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  251. if (check_private_dir(keydir, CPD_CREATE)) {
  252. return -1;
  253. }
  254. cp = keydir + strlen(keydir); /* End of string. */
  255. /* 1. Read identity key. Make it if none is found. */
  256. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  257. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  258. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir2);
  259. prkey = init_key_from_file_name_changed(keydir,keydir2);
  260. if (!prkey) return -1;
  261. set_identity_key(prkey);
  262. /* 2. Read onion key. Make it if none is found. */
  263. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  264. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  265. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir2);
  266. prkey = init_key_from_file_name_changed(keydir,keydir2);
  267. if (!prkey) return -1;
  268. set_onion_key(prkey);
  269. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  270. if (file_status(keydir) == FN_FILE) {
  271. prkey = init_key_from_file(keydir);
  272. if (prkey)
  273. lastonionkey = prkey;
  274. }
  275. /* 3. Initialize link key and TLS context. */
  276. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  277. MAX_SSL_KEY_LIFETIME) < 0) {
  278. log_fn(LOG_ERR, "Error initializing TLS context");
  279. return -1;
  280. }
  281. /* 4. Dump router descriptor to 'router.desc' */
  282. /* Must be called after keys are initialized. */
  283. tmp = mydesc = router_get_my_descriptor();
  284. if (!mydesc) {
  285. log_fn(LOG_ERR, "Error initializing descriptor.");
  286. return -1;
  287. }
  288. if(authdir_mode(options)) {
  289. /* We need to add our own fingerprint so it gets recognized. */
  290. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  291. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  292. return -1;
  293. }
  294. if (dirserv_add_descriptor(&tmp) != 1) {
  295. log(LOG_ERR, "Unable to add own descriptor to directory.");
  296. return -1;
  297. }
  298. }
  299. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  300. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  301. if (write_str_to_file(keydir, mydesc,0)) {
  302. return -1;
  303. }
  304. /* 5. Dump fingerprint to 'fingerprint' */
  305. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  306. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  307. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  308. strlcpy(fingerprint, options->Nickname, sizeof(fingerprint));
  309. strlcat(fingerprint, " ", sizeof(fingerprint));
  310. if (crypto_pk_get_fingerprint(get_identity_key(),
  311. fingerprint+strlen(fingerprint), 1)<0) {
  312. log_fn(LOG_ERR, "Error computing fingerprint");
  313. return -1;
  314. }
  315. strlcat(fingerprint, "\n", sizeof(fingerprint));
  316. if (write_str_to_file(keydir, fingerprint, 0))
  317. return -1;
  318. if(!authdir_mode(options))
  319. return 0;
  320. /* 6. [authdirserver only] load approved-routers file */
  321. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  322. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  323. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  324. log_fn(LOG_ERR, "Error loading fingerprints");
  325. return -1;
  326. }
  327. /* 6b. [authdirserver only] add own key to approved directories. */
  328. crypto_pk_get_digest(get_identity_key(), digest);
  329. if (!router_digest_is_trusted_dir(digest)) {
  330. add_trusted_dir_server(options->Address, (uint16_t)options->DirPort, digest);
  331. }
  332. /* 7. [authdirserver only] load old directory, if it's there */
  333. tor_snprintf(keydir,sizeof(keydir),"%s/cached-directory", datadir);
  334. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  335. cp = read_file_to_str(keydir,0);
  336. if(!cp) {
  337. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  338. } else {
  339. if(dirserv_load_from_directory_string(cp) < 0) {
  340. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  341. tor_free(cp);
  342. return -1;
  343. }
  344. tor_free(cp);
  345. }
  346. /* success */
  347. return 0;
  348. }
  349. /*
  350. * Clique maintenance
  351. */
  352. /** OR only: if in clique mode, try to open connections to all of the
  353. * other ORs we know about. Otherwise, open connections to those we
  354. * think are in clique mode.
  355. */
  356. void router_retry_connections(void) {
  357. int i;
  358. routerinfo_t *router;
  359. routerlist_t *rl;
  360. or_options_t *options = get_options();
  361. tor_assert(server_mode(options));
  362. router_get_routerlist(&rl);
  363. if (!rl) return;
  364. for (i=0;i < smartlist_len(rl->routers);i++) {
  365. router = smartlist_get(rl->routers, i);
  366. if(router_is_me(router))
  367. continue;
  368. if(!clique_mode(options) && !router_is_clique_mode(router))
  369. continue;
  370. if(!connection_get_by_identity_digest(router->identity_digest,
  371. CONN_TYPE_OR)) {
  372. /* not in the list */
  373. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  374. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  375. }
  376. }
  377. }
  378. int router_is_clique_mode(routerinfo_t *router) {
  379. if(router_digest_is_trusted_dir(router->identity_digest))
  380. return 1;
  381. return 0;
  382. }
  383. /*
  384. * OR descriptor generation.
  385. */
  386. /** My routerinfo. */
  387. static routerinfo_t *desc_routerinfo = NULL;
  388. /** String representation of my descriptor, signed by me. */
  389. static char descriptor[8192];
  390. /** Boolean: do we need to regenerate the above? */
  391. static int desc_is_dirty = 1;
  392. /** Boolean: do we need to regenerate the above? */
  393. static int desc_needs_upload = 0;
  394. /** OR only: try to upload our signed descriptor to all the directory servers
  395. * we know about. DOCDOC force
  396. */
  397. void router_upload_dir_desc_to_dirservers(int force) {
  398. const char *s;
  399. s = router_get_my_descriptor();
  400. if (!s) {
  401. log_fn(LOG_WARN, "No descriptor; skipping upload");
  402. return;
  403. }
  404. if (!force || !desc_needs_upload)
  405. return;
  406. desc_needs_upload = 0;
  407. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  408. }
  409. #define DEFAULT_EXIT_POLICY "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-81,accept *:110,accept *:143,accept *:443,accept *:873,accept *:993,accept *:995,reject *:4661-4662,reject *:1214,reject *:6346,accept *:1024-65535,reject *:*"
  410. /** Set the exit policy on <b>router</b> to match the exit policy in the
  411. * current configuration file. If the exit policy doesn't have a catch-all
  412. * rule, then append the default exit policy as well.
  413. */
  414. static void router_add_exit_policy_from_config(routerinfo_t *router) {
  415. struct addr_policy_t *ep;
  416. struct config_line_t default_policy;
  417. config_parse_addr_policy(get_options()->ExitPolicy, &router->exit_policy);
  418. for (ep = router->exit_policy; ep; ep = ep->next) {
  419. if (ep->msk == 0 && ep->prt_min <= 1 && ep->prt_max >= 65535) {
  420. /* if exitpolicy includes a *:* line, then we're done. */
  421. return;
  422. }
  423. }
  424. /* Else, append the default exitpolicy. */
  425. default_policy.key = NULL;
  426. default_policy.value = (char*)DEFAULT_EXIT_POLICY;
  427. default_policy.next = NULL;
  428. config_parse_addr_policy(&default_policy, &router->exit_policy);
  429. }
  430. /** OR only: Return false if my exit policy says to allow connection to
  431. * conn. Else return true.
  432. */
  433. int router_compare_to_my_exit_policy(connection_t *conn)
  434. {
  435. tor_assert(desc_routerinfo);
  436. /* make sure it's resolved to something. this way we can't get a
  437. 'maybe' below. */
  438. if (!conn->addr)
  439. return -1;
  440. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  441. desc_routerinfo->exit_policy);
  442. }
  443. /** Return true iff <b>router</b> has the same nickname as this OR. (For an
  444. * OP, always returns false.)
  445. */
  446. int router_is_me(routerinfo_t *router)
  447. {
  448. routerinfo_t *me = router_get_my_routerinfo();
  449. tor_assert(router);
  450. if(!me || memcmp(me->identity_digest, router->identity_digest, DIGEST_LEN))
  451. return 0;
  452. return 1;
  453. }
  454. /** Return a routerinfo for this OR, rebuilding a fresh one if
  455. * necessary. Return NULL on error, or if called on an OP. */
  456. routerinfo_t *router_get_my_routerinfo(void)
  457. {
  458. if (!server_mode(get_options()))
  459. return NULL;
  460. if (!desc_routerinfo) {
  461. if (router_rebuild_descriptor(1))
  462. return NULL;
  463. }
  464. return desc_routerinfo;
  465. }
  466. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  467. * one if necessary. Return NULL on error.
  468. */
  469. const char *router_get_my_descriptor(void) {
  470. if (!desc_routerinfo) {
  471. if (router_rebuild_descriptor(1))
  472. return NULL;
  473. }
  474. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  475. return descriptor;
  476. }
  477. /** Rebuild a fresh routerinfo and signed server descriptor for this
  478. * OR. Return 0 on success, -1 on error. DOCDOC force
  479. */
  480. int router_rebuild_descriptor(int force) {
  481. routerinfo_t *ri;
  482. uint32_t addr;
  483. char platform[256];
  484. struct in_addr in;
  485. or_options_t *options = get_options();
  486. if (!desc_is_dirty && !force)
  487. return 0;
  488. if(resolve_my_address(options->Address, &addr) < 0) {
  489. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  490. return -1;
  491. }
  492. ri = tor_malloc_zero(sizeof(routerinfo_t));
  493. in.s_addr = htonl(addr);
  494. ri->address = tor_strdup(inet_ntoa(in));
  495. ri->nickname = tor_strdup(options->Nickname);
  496. ri->addr = addr;
  497. ri->or_port = options->ORPort;
  498. ri->socks_port = options->SocksPort;
  499. ri->dir_port = options->DirPort;
  500. ri->published_on = time(NULL);
  501. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  502. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  503. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  504. routerinfo_free(ri);
  505. return -1;
  506. }
  507. get_platform_str(platform, sizeof(platform));
  508. ri->platform = tor_strdup(platform);
  509. ri->bandwidthrate = (int)options->BandwidthRate;
  510. ri->bandwidthburst = (int)options->BandwidthBurst;
  511. ri->bandwidthcapacity = router_get_bandwidth_capacity();
  512. router_add_exit_policy_from_config(ri);
  513. if(desc_routerinfo) /* inherit values */
  514. ri->is_verified = desc_routerinfo->is_verified;
  515. if (options->MyFamily) {
  516. ri->declared_family = smartlist_create();
  517. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  518. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  519. }
  520. if (desc_routerinfo)
  521. routerinfo_free(desc_routerinfo);
  522. desc_routerinfo = ri;
  523. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  524. log_fn(LOG_WARN, "Couldn't dump router to string.");
  525. return -1;
  526. }
  527. desc_is_dirty = 0;
  528. desc_needs_upload = 1;
  529. return 0;
  530. }
  531. /** DOCDOC */
  532. void
  533. mark_my_descriptor_dirty(void)
  534. {
  535. desc_is_dirty = 1;
  536. }
  537. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  538. * string describing the version of Tor and the operating system we're
  539. * currently running on.
  540. */
  541. void get_platform_str(char *platform, size_t len)
  542. {
  543. tor_snprintf(platform, len-1, "Tor %s on %s",
  544. VERSION, get_uname());
  545. platform[len-1] = '\0';
  546. return;
  547. }
  548. /* XXX need to audit this thing and count fenceposts. maybe
  549. * refactor so we don't have to keep asking if we're
  550. * near the end of maxlen?
  551. */
  552. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  553. /** OR only: Given a routerinfo for this router, and an identity key to sign
  554. * with, encode the routerinfo as a signed server descriptor and write the
  555. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  556. * failure, and the number of bytes used on success.
  557. */
  558. int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  559. crypto_pk_env_t *ident_key) {
  560. char *onion_pkey; /* Onion key, PEM-encoded. */
  561. char *identity_pkey; /* Identity key, PEM-encoded. */
  562. char digest[20];
  563. char signature[128];
  564. char published[32];
  565. char fingerprint[FINGERPRINT_LEN+1];
  566. struct in_addr in;
  567. size_t onion_pkeylen, identity_pkeylen;
  568. size_t written;
  569. int result=0;
  570. struct addr_policy_t *tmpe;
  571. char *bandwidth_usage;
  572. char *family_line;
  573. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  574. char *s_tmp, *s_dup;
  575. const char *cp;
  576. routerinfo_t *ri_tmp;
  577. #endif
  578. /* Make sure the identity key matches the one in the routerinfo. */
  579. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  580. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  581. return -1;
  582. }
  583. /* record our fingerprint, so we can include it in the descriptor */
  584. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  585. log_fn(LOG_ERR, "Error computing fingerprint");
  586. return -1;
  587. }
  588. /* PEM-encode the onion key */
  589. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  590. &onion_pkey,&onion_pkeylen)<0) {
  591. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  592. return -1;
  593. }
  594. /* PEM-encode the identity key key */
  595. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  596. &identity_pkey,&identity_pkeylen)<0) {
  597. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  598. tor_free(onion_pkey);
  599. return -1;
  600. }
  601. /* Encode the publication time. */
  602. format_iso_time(published, router->published_on);
  603. /* How busy have we been? */
  604. bandwidth_usage = rep_hist_get_bandwidth_lines();
  605. if (router->declared_family && smartlist_len(router->declared_family)) {
  606. size_t n;
  607. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  608. n += strlen("opt family ") + 2; /* 1 for \n, 1 for \0. */
  609. family_line = tor_malloc(n);
  610. tor_snprintf(family_line, n, "opt family %s\n", s);
  611. tor_free(s);
  612. } else {
  613. family_line = tor_strdup("");
  614. }
  615. /* Generate the easy portion of the router descriptor. */
  616. result = tor_snprintf(s, maxlen,
  617. "router %s %s %d %d %d\n"
  618. "platform %s\n"
  619. "published %s\n"
  620. "opt fingerprint %s\n"
  621. "opt uptime %ld\n"
  622. "bandwidth %d %d %d\n"
  623. "onion-key\n%s"
  624. "signing-key\n%s%s%s",
  625. router->nickname,
  626. router->address,
  627. router->or_port,
  628. router->socks_port,
  629. router->dir_port,
  630. router->platform,
  631. published,
  632. fingerprint,
  633. stats_n_seconds_uptime,
  634. (int) router->bandwidthrate,
  635. (int) router->bandwidthburst,
  636. (int) router->bandwidthcapacity,
  637. onion_pkey, identity_pkey,
  638. family_line, bandwidth_usage);
  639. tor_free(family_line);
  640. tor_free(onion_pkey);
  641. tor_free(identity_pkey);
  642. tor_free(bandwidth_usage);
  643. if(result < 0 || (size_t)result >= maxlen) {
  644. /* apparently different glibcs do different things on tor_snprintf error.. so check both */
  645. return -1;
  646. }
  647. /* From now on, we use 'written' to remember the current length of 's'. */
  648. written = result;
  649. if (get_options()->ContactInfo && strlen(get_options()->ContactInfo)) {
  650. result = tor_snprintf(s+written,maxlen-written, "opt contact %s\n",
  651. get_options()->ContactInfo);
  652. if (result<0 || result+written > maxlen)
  653. return -1;
  654. written += result;
  655. }
  656. /* Write the exit policy to the end of 's'. */
  657. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  658. in.s_addr = htonl(tmpe->addr);
  659. /* Write: "accept 1.2.3.4" */
  660. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  661. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  662. tmpe->msk == 0 ? "*" : inet_ntoa(in));
  663. if(result < 0 || result+written > maxlen) {
  664. /* apparently different glibcs do different things on tor_snprintf error.. so check both */
  665. return -1;
  666. }
  667. written += result;
  668. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  669. /* Write "/255.255.0.0" */
  670. in.s_addr = htonl(tmpe->msk);
  671. result = tor_snprintf(s+written, maxlen-written, "/%s", inet_ntoa(in));
  672. if (result<0 || result+written > maxlen)
  673. return -1;
  674. written += result;
  675. }
  676. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  677. /* There is no port set; write ":*" */
  678. if (written > maxlen-4)
  679. return -1;
  680. strlcat(s+written, ":*\n", maxlen-written);
  681. written += 3;
  682. } else if (tmpe->prt_min == tmpe->prt_max) {
  683. /* There is only one port; write ":80". */
  684. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  685. if (result<0 || result+written > maxlen)
  686. return -1;
  687. written += result;
  688. } else {
  689. /* There is a range of ports; write ":79-80". */
  690. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  691. tmpe->prt_max);
  692. if (result<0 || result+written > maxlen)
  693. return -1;
  694. written += result;
  695. }
  696. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  697. /* This was a catch-all rule, so future rules are irrelevant. */
  698. break;
  699. } /* end for */
  700. if (written > maxlen-256) /* Not enough room for signature. */
  701. return -1;
  702. /* Sign the directory */
  703. strlcat(s+written, "router-signature\n", maxlen-written);
  704. written += strlen(s+written);
  705. s[written] = '\0';
  706. if (router_get_router_hash(s, digest) < 0)
  707. return -1;
  708. if (crypto_pk_private_sign(ident_key, signature, digest, 20) < 0) {
  709. log_fn(LOG_WARN, "Error signing digest");
  710. return -1;
  711. }
  712. strlcat(s+written, "-----BEGIN SIGNATURE-----\n", maxlen-written);
  713. written += strlen(s+written);
  714. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  715. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  716. return -1;
  717. }
  718. written += strlen(s+written);
  719. strlcat(s+written, "-----END SIGNATURE-----\n", maxlen-written);
  720. written += strlen(s+written);
  721. if (written > maxlen-2)
  722. return -1;
  723. /* include a last '\n' */
  724. s[written] = '\n';
  725. s[written+1] = 0;
  726. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  727. cp = s_tmp = s_dup = tor_strdup(s);
  728. ri_tmp = router_parse_entry_from_string(cp, NULL);
  729. if (!ri_tmp) {
  730. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  731. s);
  732. return -1;
  733. }
  734. tor_free(s_dup);
  735. routerinfo_free(ri_tmp);
  736. #endif
  737. return written+1;
  738. }
  739. int is_legal_nickname(const char *s)
  740. {
  741. size_t len;
  742. tor_assert(s);
  743. len = strlen(s);
  744. return len > 0 && len <= MAX_NICKNAME_LEN &&
  745. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  746. }
  747. int is_legal_nickname_or_hexdigest(const char *s)
  748. {
  749. size_t len;
  750. tor_assert(s);
  751. if (*s!='$')
  752. return is_legal_nickname(s);
  753. len = strlen(s);
  754. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  755. }
  756. /*
  757. Local Variables:
  758. mode:c
  759. indent-tabs-mode:nil
  760. c-basic-offset:2
  761. End:
  762. */