router.c 25 KB

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