router.c 25 KB

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