router.c 25 KB

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