router.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] =
  7. "$Id$";
  8. #define ROUTER_PRIVATE
  9. #include "or.h"
  10. /**
  11. * \file router.c
  12. * \brief OR functionality, including key maintenance, generating
  13. * and uploading server descriptors, retrying OR connections.
  14. **/
  15. extern long stats_n_seconds_working;
  16. /************************************************************/
  17. /*****
  18. * Key management: ORs only.
  19. *****/
  20. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  21. */
  22. static tor_mutex_t *key_lock=NULL;
  23. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  24. /** Current private onionskin decryption key: used to decode CREATE cells. */
  25. static crypto_pk_env_t *onionkey=NULL;
  26. /** Previous private onionskin decription key: used to decode CREATE cells
  27. * generated by clients that have an older version of our descriptor. */
  28. static crypto_pk_env_t *lastonionkey=NULL;
  29. /** Private "identity key": used to sign directory info and TLS
  30. * certificates. Never changes. */
  31. static crypto_pk_env_t *identitykey=NULL;
  32. /** Digest of identitykey. */
  33. static char identitykey_digest[DIGEST_LEN];
  34. /** Signing key used for v3 directory material; only set for authorities. */
  35. static crypto_pk_env_t *authority_signing_key = NULL;
  36. /** Key certificate to authenticate v3 directory material; only set for
  37. * authorities. */
  38. static authority_cert_t *authority_key_certificate = NULL;
  39. /* (Note that v3 authorities also have a separate "authority identity key",
  40. * but this key is never actually loaded by the Tor process. Instead, it's
  41. * used by tor-gencert to sign new signing keys and make new key
  42. * certificates. */
  43. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  44. * to update onionkey correctly, call rotate_onion_key().
  45. */
  46. static void
  47. set_onion_key(crypto_pk_env_t *k)
  48. {
  49. tor_mutex_acquire(key_lock);
  50. onionkey = k;
  51. onionkey_set_at = time(NULL);
  52. tor_mutex_release(key_lock);
  53. mark_my_descriptor_dirty();
  54. }
  55. /** Return the current onion key. Requires that the onion key has been
  56. * loaded or generated. */
  57. crypto_pk_env_t *
  58. get_onion_key(void)
  59. {
  60. tor_assert(onionkey);
  61. return onionkey;
  62. }
  63. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  64. * of the most recent onion key into *<b>last</b>.
  65. */
  66. void
  67. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  68. {
  69. tor_assert(key);
  70. tor_assert(last);
  71. tor_mutex_acquire(key_lock);
  72. tor_assert(onionkey);
  73. *key = crypto_pk_dup_key(onionkey);
  74. if (lastonionkey)
  75. *last = crypto_pk_dup_key(lastonionkey);
  76. else
  77. *last = NULL;
  78. tor_mutex_release(key_lock);
  79. }
  80. /** Return the time when the onion key was last set. This is either the time
  81. * when the process launched, or the time of the most recent key rotation since
  82. * the process launched.
  83. */
  84. time_t
  85. get_onion_key_set_at(void)
  86. {
  87. return onionkey_set_at;
  88. }
  89. /** Set the current identity key to k.
  90. */
  91. void
  92. set_identity_key(crypto_pk_env_t *k)
  93. {
  94. if (identitykey)
  95. crypto_free_pk_env(identitykey);
  96. identitykey = k;
  97. crypto_pk_get_digest(identitykey, identitykey_digest);
  98. }
  99. /** Returns the current identity key; requires that the identity key has been
  100. * set.
  101. */
  102. crypto_pk_env_t *
  103. get_identity_key(void)
  104. {
  105. tor_assert(identitykey);
  106. return identitykey;
  107. }
  108. /** Return true iff the identity key has been set. */
  109. int
  110. identity_key_is_set(void)
  111. {
  112. return identitykey != NULL;
  113. }
  114. /** Return the key certificate for this v3 (voting) authority, or NULL
  115. * if we have no such certificate. */
  116. authority_cert_t *
  117. get_my_v3_authority_cert(void)
  118. {
  119. return authority_key_certificate;
  120. }
  121. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  122. * if we have no such key. */
  123. crypto_pk_env_t *
  124. get_my_v3_authority_signing_key(void)
  125. {
  126. return authority_signing_key;
  127. }
  128. /** Replace the previous onion key with the current onion key, and generate
  129. * a new previous onion key. Immediately after calling this function,
  130. * the OR should:
  131. * - schedule all previous cpuworkers to shut down _after_ processing
  132. * pending work. (This will cause fresh cpuworkers to be generated.)
  133. * - generate and upload a fresh routerinfo.
  134. */
  135. void
  136. rotate_onion_key(void)
  137. {
  138. char fname[512];
  139. char fname_prev[512];
  140. crypto_pk_env_t *prkey;
  141. or_state_t *state = get_or_state();
  142. time_t now;
  143. tor_snprintf(fname,sizeof(fname),
  144. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",
  145. get_options()->DataDirectory);
  146. tor_snprintf(fname_prev,sizeof(fname_prev),
  147. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key.old",
  148. get_options()->DataDirectory);
  149. if (!(prkey = crypto_new_pk_env())) {
  150. log_err(LD_GENERAL,"Error constructing rotated onion key");
  151. goto error;
  152. }
  153. if (crypto_pk_generate_key(prkey)) {
  154. log_err(LD_BUG,"Error generating onion key");
  155. goto error;
  156. }
  157. if (file_status(fname) == FN_FILE) {
  158. if (replace_file(fname, fname_prev))
  159. goto error;
  160. }
  161. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  162. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  163. goto error;
  164. }
  165. log_info(LD_GENERAL, "Rotating onion key");
  166. tor_mutex_acquire(key_lock);
  167. if (lastonionkey)
  168. crypto_free_pk_env(lastonionkey);
  169. lastonionkey = onionkey;
  170. onionkey = prkey;
  171. now = time(NULL);
  172. state->LastRotatedOnionKey = onionkey_set_at = now;
  173. tor_mutex_release(key_lock);
  174. mark_my_descriptor_dirty();
  175. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  176. return;
  177. error:
  178. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  179. }
  180. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  181. * and <b>generate</b> is true, create a new RSA key and save it in
  182. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  183. * errors at level <b>severity</b>.
  184. */
  185. crypto_pk_env_t *
  186. init_key_from_file(const char *fname, int generate, int severity)
  187. {
  188. crypto_pk_env_t *prkey = NULL;
  189. FILE *file = NULL;
  190. if (!(prkey = crypto_new_pk_env())) {
  191. log(severity, LD_GENERAL,"Error constructing key");
  192. goto error;
  193. }
  194. switch (file_status(fname)) {
  195. case FN_DIR:
  196. case FN_ERROR:
  197. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  198. goto error;
  199. case FN_NOENT:
  200. if (generate) {
  201. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  202. fname);
  203. if (crypto_pk_generate_key(prkey)) {
  204. log(severity, LD_GENERAL,"Error generating onion key");
  205. goto error;
  206. }
  207. if (crypto_pk_check_key(prkey) <= 0) {
  208. log(severity, LD_GENERAL,"Generated key seems invalid");
  209. goto error;
  210. }
  211. log_info(LD_GENERAL, "Generated key seems valid");
  212. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  213. log(severity, LD_FS,
  214. "Couldn't write generated key to \"%s\".", fname);
  215. goto error;
  216. }
  217. } else {
  218. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  219. }
  220. return prkey;
  221. case FN_FILE:
  222. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  223. log(severity, LD_GENERAL,"Error loading private key.");
  224. goto error;
  225. }
  226. return prkey;
  227. default:
  228. tor_assert(0);
  229. }
  230. error:
  231. if (prkey)
  232. crypto_free_pk_env(prkey);
  233. if (file)
  234. fclose(file);
  235. return NULL;
  236. }
  237. /** Load the v3 (voting) authority signing key and certificate from
  238. * <b>keydir</b>, if they are present. */
  239. /* XXXX020 maybe move to dirserv.c */
  240. static void
  241. init_v3_authority_keys(const char *keydir)
  242. {
  243. char *fname = NULL, *cert = NULL;
  244. const char *eos = NULL;
  245. size_t fname_len = strlen(keydir) + 64;
  246. crypto_pk_env_t *signing_key = NULL;
  247. authority_cert_t *parsed = NULL;
  248. fname = tor_malloc(fname_len);
  249. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"authority_signing_key",
  250. keydir);
  251. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  252. if (!signing_key) {
  253. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  254. goto done;
  255. }
  256. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"authority_certificate",
  257. keydir);
  258. cert = read_file_to_str(fname, 0, NULL);
  259. if (!cert) {
  260. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  261. fname);
  262. goto done;
  263. }
  264. parsed = authority_cert_parse_from_string(cert, &eos);
  265. if (!parsed) {
  266. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  267. goto done;
  268. }
  269. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  270. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  271. "certificate");
  272. goto done;
  273. }
  274. parsed->cache_info.signed_descriptor_body = cert;
  275. parsed->cache_info.signed_descriptor_len = eos-cert;
  276. cert = NULL;
  277. authority_key_certificate = parsed;
  278. authority_signing_key = signing_key;
  279. parsed = NULL;
  280. signing_key = NULL;
  281. done:
  282. tor_free(fname);
  283. tor_free(cert);
  284. if (signing_key)
  285. crypto_free_pk_env(signing_key);
  286. if (parsed)
  287. authority_cert_free(parsed);
  288. }
  289. /** Initialize all OR private keys, and the TLS context, as necessary.
  290. * On OPs, this only initializes the tls context. Return 0 on success,
  291. * or -1 if Tor should die.
  292. */
  293. int
  294. init_keys(void)
  295. {
  296. char keydir[512];
  297. char fingerprint[FINGERPRINT_LEN+1];
  298. /*nickname<space>fp\n\0 */
  299. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  300. const char *mydesc, *datadir;
  301. crypto_pk_env_t *prkey;
  302. char digest[20];
  303. char v3_digest[20];
  304. char *cp;
  305. or_options_t *options = get_options();
  306. or_state_t *state = get_or_state();
  307. authority_type_t type;
  308. if (!key_lock)
  309. key_lock = tor_mutex_new();
  310. /* OP's don't need persistent keys; just make up an identity and
  311. * initialize the TLS context. */
  312. if (!server_mode(options)) {
  313. if (!(prkey = crypto_new_pk_env()))
  314. return -1;
  315. if (crypto_pk_generate_key(prkey))
  316. return -1;
  317. set_identity_key(prkey);
  318. /* Create a TLS context; default the client nickname to "client". */
  319. if (tor_tls_context_new(get_identity_key(),
  320. options->Nickname ? options->Nickname : "client",
  321. MAX_SSL_KEY_LIFETIME) < 0) {
  322. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  323. return -1;
  324. }
  325. return 0;
  326. }
  327. /* Make sure DataDirectory exists, and is private. */
  328. datadir = options->DataDirectory;
  329. if (check_private_dir(datadir, CPD_CREATE)) {
  330. return -1;
  331. }
  332. /* Check the key directory. */
  333. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"keys", datadir);
  334. if (check_private_dir(keydir, CPD_CREATE)) {
  335. return -1;
  336. }
  337. /* 1a. Read v3 directory authority key/cert information. */
  338. memset(v3_digest, 0, sizeof(v3_digest));
  339. if (authdir_mode(options) && options->V3AuthoritativeDir) {
  340. init_v3_authority_keys(keydir);
  341. if (get_my_v3_authority_cert()) {
  342. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  343. v3_digest);
  344. }
  345. }
  346. /* 1. Read identity key. Make it if none is found. */
  347. tor_snprintf(keydir,sizeof(keydir),
  348. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_id_key",datadir);
  349. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  350. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  351. if (!prkey) return -1;
  352. set_identity_key(prkey);
  353. /* 2. Read onion key. Make it if none is found. */
  354. tor_snprintf(keydir,sizeof(keydir),
  355. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",datadir);
  356. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  357. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  358. if (!prkey) return -1;
  359. set_onion_key(prkey);
  360. if (state->LastRotatedOnionKey > 100) { /* allow for some parsing slop. */
  361. onionkey_set_at = state->LastRotatedOnionKey;
  362. } else {
  363. /* We have no LastRotatedOnionKey set; either we just created the key
  364. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  365. * start the clock ticking now so that we will eventually rotate it even
  366. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  367. state->LastRotatedOnionKey = onionkey_set_at = time(NULL);
  368. or_state_mark_dirty(state, options->AvoidDiskWrites ? time(NULL)+3600 : 0);
  369. }
  370. tor_snprintf(keydir,sizeof(keydir),
  371. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key.old",datadir);
  372. if (file_status(keydir) == FN_FILE) {
  373. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  374. if (prkey)
  375. lastonionkey = prkey;
  376. }
  377. /* 3. Initialize link key and TLS context. */
  378. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  379. MAX_SSL_KEY_LIFETIME) < 0) {
  380. log_err(LD_GENERAL,"Error initializing TLS context");
  381. return -1;
  382. }
  383. /* 4. Build our router descriptor. */
  384. /* Must be called after keys are initialized. */
  385. mydesc = router_get_my_descriptor();
  386. if (authdir_mode(options)) {
  387. const char *m;
  388. routerinfo_t *ri;
  389. /* We need to add our own fingerprint so it gets recognized. */
  390. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  391. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  392. return -1;
  393. }
  394. if (!mydesc) {
  395. log_err(LD_GENERAL,"Error initializing descriptor.");
  396. return -1;
  397. }
  398. ri = router_parse_entry_from_string(mydesc, NULL, 1);
  399. if (!ri) {
  400. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  401. return -1;
  402. }
  403. if (dirserv_add_descriptor(ri, &m) < 0) {
  404. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  405. m?m:"<unknown error>");
  406. return -1;
  407. }
  408. }
  409. /* 5. Dump fingerprint to 'fingerprint' */
  410. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"fingerprint", datadir);
  411. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  412. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  413. log_err(LD_GENERAL,"Error computing fingerprint");
  414. return -1;
  415. }
  416. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  417. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  418. "%s %s\n",options->Nickname, fingerprint) < 0) {
  419. log_err(LD_GENERAL,"Error writing fingerprint line");
  420. return -1;
  421. }
  422. /* Check whether we need to write the fingerprint file. */
  423. cp = NULL;
  424. if (file_status(keydir) == FN_FILE)
  425. cp = read_file_to_str(keydir, 0, NULL);
  426. if (!cp || strcmp(cp, fingerprint_line)) {
  427. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  428. log_err(LD_FS, "Error writing fingerprint line to file");
  429. return -1;
  430. }
  431. }
  432. tor_free(cp);
  433. log(LOG_NOTICE, LD_GENERAL,
  434. "Your Tor server's identity key fingerprint is '%s %s'",
  435. options->Nickname, fingerprint);
  436. if (!authdir_mode(options))
  437. return 0;
  438. /* 6. [authdirserver only] load approved-routers file */
  439. if (dirserv_load_fingerprint_file() < 0) {
  440. log_err(LD_GENERAL,"Error loading fingerprints");
  441. return -1;
  442. }
  443. /* 6b. [authdirserver only] add own key to approved directories. */
  444. crypto_pk_get_digest(get_identity_key(), digest);
  445. type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : 0) |
  446. (options->V2AuthoritativeDir ? V2_AUTHORITY : 0) |
  447. (options->V3AuthoritativeDir ? V3_AUTHORITY : 0) |
  448. (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : 0) |
  449. (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : 0));
  450. if (!router_digest_is_trusted_dir(digest)) {
  451. add_trusted_dir_server(options->Nickname, NULL,
  452. (uint16_t)options->DirPort,
  453. (uint16_t)options->ORPort,
  454. digest,
  455. v3_digest,
  456. type);
  457. }
  458. return 0; /* success */
  459. }
  460. /* Keep track of whether we should upload our server descriptor,
  461. * and what type of server we are.
  462. */
  463. /** Whether we can reach our ORPort from the outside. */
  464. static int can_reach_or_port = 0;
  465. /** Whether we can reach our DirPort from the outside. */
  466. static int can_reach_dir_port = 0;
  467. /** Forget what we have learned about our reachability status. */
  468. void
  469. router_reset_reachability(void)
  470. {
  471. can_reach_or_port = can_reach_dir_port = 0;
  472. }
  473. /** Return 1 if ORPort is known reachable; else return 0. */
  474. int
  475. check_whether_orport_reachable(void)
  476. {
  477. or_options_t *options = get_options();
  478. return options->AssumeReachable ||
  479. can_reach_or_port;
  480. }
  481. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  482. int
  483. check_whether_dirport_reachable(void)
  484. {
  485. or_options_t *options = get_options();
  486. return !options->DirPort ||
  487. options->AssumeReachable ||
  488. we_are_hibernating() ||
  489. can_reach_dir_port;
  490. }
  491. /** Look at a variety of factors, and return 0 if we don't want to
  492. * advertise the fact that we have a DirPort open. Else return the
  493. * DirPort we want to advertise.
  494. *
  495. * Log a helpful message if we change our mind about whether to publish
  496. * a DirPort.
  497. */
  498. static int
  499. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  500. {
  501. static int advertising=1; /* start out assuming we will advertise */
  502. int new_choice=1;
  503. const char *reason = NULL;
  504. /* Section one: reasons to publish or not publish that aren't
  505. * worth mentioning to the user, either because they're obvious
  506. * or because they're normal behavior. */
  507. if (!router->dir_port) /* short circuit the rest of the function */
  508. return 0;
  509. if (authdir_mode(options)) /* always publish */
  510. return router->dir_port;
  511. if (we_are_hibernating())
  512. return 0;
  513. if (!check_whether_dirport_reachable())
  514. return 0;
  515. /* Section two: reasons to publish or not publish that the user
  516. * might find surprising. These are generally config options that
  517. * make us choose not to publish. */
  518. if (accounting_is_enabled(options)) {
  519. /* if we might potentially hibernate */
  520. new_choice = 0;
  521. reason = "AccountingMax enabled";
  522. } else if (router->bandwidthrate < 51200) {
  523. /* if we're advertising a small amount */
  524. new_choice = 0;
  525. reason = "BandwidthRate under 50KB";
  526. }
  527. if (advertising != new_choice) {
  528. if (new_choice == 1) {
  529. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", router->dir_port);
  530. } else {
  531. tor_assert(reason);
  532. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  533. }
  534. advertising = new_choice;
  535. }
  536. return advertising ? router->dir_port : 0;
  537. }
  538. /** Some time has passed, or we just got new directory information.
  539. * See if we currently believe our ORPort or DirPort to be
  540. * unreachable. If so, launch a new test for it.
  541. *
  542. * For ORPort, we simply try making a circuit that ends at ourselves.
  543. * Success is noticed in onionskin_answer().
  544. *
  545. * For DirPort, we make a connection via Tor to our DirPort and ask
  546. * for our own server descriptor.
  547. * Success is noticed in connection_dir_client_reached_eof().
  548. */
  549. void
  550. consider_testing_reachability(int test_or, int test_dir)
  551. {
  552. routerinfo_t *me = router_get_my_routerinfo();
  553. int orport_reachable = check_whether_orport_reachable();
  554. if (!me)
  555. return;
  556. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  557. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  558. !orport_reachable ? "reachability" : "bandwidth",
  559. me->address, me->or_port);
  560. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, 0, me, 0, 1, 1);
  561. control_event_server_status(LOG_NOTICE,
  562. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  563. me->address, me->or_port);
  564. }
  565. if (test_dir && !check_whether_dirport_reachable() &&
  566. !connection_get_by_type_addr_port_purpose(
  567. CONN_TYPE_DIR, me->addr, me->dir_port,
  568. DIR_PURPOSE_FETCH_SERVERDESC)) {
  569. /* ask myself, via tor, for my server descriptor. */
  570. directory_initiate_command(me->address, me->addr,
  571. me->or_port, me->dir_port,
  572. 0, me->cache_info.identity_digest,
  573. DIR_PURPOSE_FETCH_SERVERDESC,
  574. ROUTER_PURPOSE_GENERAL,
  575. 1, "authority.z", NULL, 0);
  576. control_event_server_status(LOG_NOTICE,
  577. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  578. me->address, me->dir_port);
  579. }
  580. }
  581. /** Annotate that we found our ORPort reachable. */
  582. void
  583. router_orport_found_reachable(void)
  584. {
  585. if (!can_reach_or_port) {
  586. routerinfo_t *me = router_get_my_routerinfo();
  587. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  588. "the outside. Excellent.%s",
  589. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  590. " Publishing server descriptor." : "");
  591. can_reach_or_port = 1;
  592. mark_my_descriptor_dirty();
  593. if (!me)
  594. return;
  595. control_event_server_status(LOG_NOTICE,
  596. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  597. me->address, me->dir_port);
  598. }
  599. }
  600. /** Annotate that we found our DirPort reachable. */
  601. void
  602. router_dirport_found_reachable(void)
  603. {
  604. if (!can_reach_dir_port) {
  605. routerinfo_t *me = router_get_my_routerinfo();
  606. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  607. "from the outside. Excellent.");
  608. can_reach_dir_port = 1;
  609. mark_my_descriptor_dirty();
  610. if (!me)
  611. return;
  612. control_event_server_status(LOG_NOTICE,
  613. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  614. me->address, me->dir_port);
  615. }
  616. }
  617. /** We have enough testing circuits open. Send a bunch of "drop"
  618. * cells down each of them, to exercise our bandwidth. */
  619. void
  620. router_perform_bandwidth_test(int num_circs, time_t now)
  621. {
  622. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  623. int max_cells = num_cells < CIRCWINDOW_START ?
  624. num_cells : CIRCWINDOW_START;
  625. int cells_per_circuit = max_cells / num_circs;
  626. origin_circuit_t *circ = NULL;
  627. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  628. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  629. CIRCUIT_PURPOSE_TESTING))) {
  630. /* dump cells_per_circuit drop cells onto this circ */
  631. int i = cells_per_circuit;
  632. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  633. continue;
  634. circ->_base.timestamp_dirty = now;
  635. while (i-- > 0) {
  636. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  637. RELAY_COMMAND_DROP,
  638. NULL, 0, circ->cpath->prev)<0) {
  639. return; /* stop if error */
  640. }
  641. }
  642. }
  643. }
  644. /** Return true iff we believe ourselves to be an authoritative
  645. * directory server.
  646. */
  647. int
  648. authdir_mode(or_options_t *options)
  649. {
  650. return options->AuthoritativeDir != 0;
  651. }
  652. /** Return true iff we believe ourselves to be a v1 authoritative
  653. * directory server.
  654. */
  655. int
  656. authdir_mode_v1(or_options_t *options)
  657. {
  658. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  659. }
  660. /** Return true iff we believe ourselves to be a v2 authoritative
  661. * directory server.
  662. */
  663. int
  664. authdir_mode_v2(or_options_t *options)
  665. {
  666. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  667. }
  668. /** Return true iff we believe ourselves to be a v3 authoritative
  669. * directory server.
  670. */
  671. int
  672. authdir_mode_v3(or_options_t *options)
  673. {
  674. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  675. }
  676. /** Return true iff we are an authoritative directory server that
  677. * is willing to receive or serve descriptors on its dirport.
  678. */
  679. int
  680. authdir_mode_handles_descs(or_options_t *options)
  681. {
  682. return authdir_mode_v1(options) || authdir_mode_v2(options) ||
  683. authdir_mode_bridge(options);
  684. }
  685. /** Return true iff we are an authoritative directory server that
  686. * publishes its own network statuses.
  687. */
  688. int
  689. authdir_mode_publishes_statuses(or_options_t *options)
  690. {
  691. if (authdir_mode_bridge(options))
  692. return 0;
  693. return authdir_mode_v1(options) || authdir_mode_v2(options);
  694. }
  695. /** Return true iff we are an authoritative directory server that
  696. * tests reachability of the descriptors it learns about.
  697. */
  698. int
  699. authdir_mode_tests_reachability(or_options_t *options)
  700. {
  701. return authdir_mode_v1(options) || authdir_mode_v2(options);
  702. }
  703. /** Return true iff we believe ourselves to be a bridge authoritative
  704. * directory server.
  705. */
  706. int
  707. authdir_mode_bridge(or_options_t *options)
  708. {
  709. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  710. }
  711. /** Return true iff we try to stay connected to all ORs at once.
  712. */
  713. int
  714. clique_mode(or_options_t *options)
  715. {
  716. return authdir_mode_tests_reachability(options);
  717. }
  718. /** Return true iff we are trying to be a server.
  719. */
  720. int
  721. server_mode(or_options_t *options)
  722. {
  723. if (options->ClientOnly) return 0;
  724. return (options->ORPort != 0 || options->ORListenAddress);
  725. }
  726. /** Remember if we've advertised ourselves to the dirservers. */
  727. static int server_is_advertised=0;
  728. /** Return true iff we have published our descriptor lately.
  729. */
  730. int
  731. advertised_server_mode(void)
  732. {
  733. return server_is_advertised;
  734. }
  735. /**
  736. * Called with a boolean: set whether we have recently published our
  737. * descriptor.
  738. */
  739. static void
  740. set_server_advertised(int s)
  741. {
  742. server_is_advertised = s;
  743. }
  744. /** Return true iff we are trying to be a socks proxy. */
  745. int
  746. proxy_mode(or_options_t *options)
  747. {
  748. return (options->SocksPort != 0 || options->SocksListenAddress);
  749. }
  750. /** Decide if we're a publishable server. We are a publishable server if:
  751. * - We don't have the ClientOnly option set
  752. * and
  753. * - We have the PublishServerDescriptor option set to non-empty
  754. * and
  755. * - We have ORPort set
  756. * and
  757. * - We believe we are reachable from the outside; or
  758. * - We are an authoritative directory server.
  759. */
  760. static int
  761. decide_if_publishable_server(void)
  762. {
  763. or_options_t *options = get_options();
  764. if (options->ClientOnly)
  765. return 0;
  766. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  767. return 0;
  768. if (!server_mode(options))
  769. return 0;
  770. if (authdir_mode(options))
  771. return 1;
  772. return check_whether_orport_reachable();
  773. }
  774. /** Initiate server descriptor upload as reasonable (if server is publishable,
  775. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  776. *
  777. * We need to rebuild the descriptor if it's dirty even if we're not
  778. * uploading, because our reachability testing *uses* our descriptor to
  779. * determine what IP address and ports to test.
  780. */
  781. void
  782. consider_publishable_server(int force)
  783. {
  784. int rebuilt;
  785. if (!server_mode(get_options()))
  786. return;
  787. rebuilt = router_rebuild_descriptor(0);
  788. if (decide_if_publishable_server()) {
  789. set_server_advertised(1);
  790. if (rebuilt == 0)
  791. router_upload_dir_desc_to_dirservers(force);
  792. } else {
  793. set_server_advertised(0);
  794. }
  795. }
  796. /*
  797. * Clique maintenance -- to be phased out.
  798. */
  799. /** Return true iff we believe this OR tries to keep connections open
  800. * to all other ORs. */
  801. int
  802. router_is_clique_mode(routerinfo_t *router)
  803. {
  804. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  805. return 1;
  806. return 0;
  807. }
  808. /*
  809. * OR descriptor generation.
  810. */
  811. /** My routerinfo. */
  812. static routerinfo_t *desc_routerinfo = NULL;
  813. /** My extrainfo */
  814. static extrainfo_t *desc_extrainfo = NULL;
  815. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  816. * now. */
  817. static time_t desc_clean_since = 0;
  818. /** Boolean: do we need to regenerate the above? */
  819. static int desc_needs_upload = 0;
  820. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  821. * descriptor successfully yet, try to upload our signed descriptor to
  822. * all the directory servers we know about.
  823. */
  824. void
  825. router_upload_dir_desc_to_dirservers(int force)
  826. {
  827. routerinfo_t *ri;
  828. extrainfo_t *ei;
  829. char *msg;
  830. size_t desc_len, extra_len = 0, total_len;
  831. authority_type_t auth = get_options()->_PublishServerDescriptor;
  832. ri = router_get_my_routerinfo();
  833. if (!ri) {
  834. log_info(LD_GENERAL, "No descriptor; skipping upload");
  835. return;
  836. }
  837. ei = router_get_my_extrainfo();
  838. if (auth == NO_AUTHORITY)
  839. return;
  840. if (!force && !desc_needs_upload)
  841. return;
  842. desc_needs_upload = 0;
  843. desc_len = ri->cache_info.signed_descriptor_len;
  844. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  845. total_len = desc_len + extra_len + 1;
  846. msg = tor_malloc(total_len);
  847. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  848. if (ei) {
  849. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  850. }
  851. msg[desc_len+extra_len] = 0;
  852. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  853. (auth & BRIDGE_AUTHORITY) ?
  854. ROUTER_PURPOSE_BRIDGE :
  855. ROUTER_PURPOSE_GENERAL,
  856. auth, msg, desc_len, extra_len);
  857. tor_free(msg);
  858. }
  859. /** OR only: Check whether my exit policy says to allow connection to
  860. * conn. Return 0 if we accept; non-0 if we reject.
  861. */
  862. int
  863. router_compare_to_my_exit_policy(edge_connection_t *conn)
  864. {
  865. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  866. return -1;
  867. /* make sure it's resolved to something. this way we can't get a
  868. 'maybe' below. */
  869. if (!conn->_base.addr)
  870. return -1;
  871. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  872. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  873. }
  874. /** Return true iff I'm a server and <b>digest</b> is equal to
  875. * my identity digest. */
  876. int
  877. router_digest_is_me(const char *digest)
  878. {
  879. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  880. }
  881. /** A wrapper around router_digest_is_me(). */
  882. int
  883. router_is_me(routerinfo_t *router)
  884. {
  885. return router_digest_is_me(router->cache_info.identity_digest);
  886. }
  887. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  888. int
  889. router_fingerprint_is_me(const char *fp)
  890. {
  891. char digest[DIGEST_LEN];
  892. if (strlen(fp) == HEX_DIGEST_LEN &&
  893. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  894. return router_digest_is_me(digest);
  895. return 0;
  896. }
  897. /** Return a routerinfo for this OR, rebuilding a fresh one if
  898. * necessary. Return NULL on error, or if called on an OP. */
  899. routerinfo_t *
  900. router_get_my_routerinfo(void)
  901. {
  902. if (!server_mode(get_options()))
  903. return NULL;
  904. if (router_rebuild_descriptor(0))
  905. return NULL;
  906. return desc_routerinfo;
  907. }
  908. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  909. * one if necessary. Return NULL on error.
  910. */
  911. const char *
  912. router_get_my_descriptor(void)
  913. {
  914. const char *body;
  915. if (!router_get_my_routerinfo())
  916. return NULL;
  917. /* Make sure this is nul-terminated. */
  918. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  919. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  920. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  921. log_debug(LD_GENERAL,"my desc is '%s'", body);
  922. return body;
  923. }
  924. /* Return the extrainfo document for this OR, or NULL if we have none.
  925. * Rebuilt it (and the server descriptor) if necessary. */
  926. extrainfo_t *
  927. router_get_my_extrainfo(void)
  928. {
  929. if (!server_mode(get_options()))
  930. return NULL;
  931. if (router_rebuild_descriptor(0))
  932. return NULL;
  933. return desc_extrainfo;
  934. }
  935. /** A list of nicknames that we've warned about including in our family
  936. * declaration verbatim rather than as digests. */
  937. static smartlist_t *warned_nonexistent_family = NULL;
  938. static int router_guess_address_from_dir_headers(uint32_t *guess);
  939. /** Return our current best guess at our address, either because
  940. * it's configured in torrc, or because we've learned it from
  941. * dirserver headers. */
  942. int
  943. router_pick_published_address(or_options_t *options, uint32_t *addr)
  944. {
  945. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  946. log_info(LD_CONFIG, "Could not determine our address locally. "
  947. "Checking if directory headers provide any hints.");
  948. if (router_guess_address_from_dir_headers(addr) < 0) {
  949. log_info(LD_CONFIG, "No hints from directory headers either. "
  950. "Will try again later.");
  951. return -1;
  952. }
  953. }
  954. return 0;
  955. }
  956. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  957. * routerinfo, signed server descriptor, and extra-info document for this OR.
  958. * Return 0 on success, -1 on temporary error.
  959. */
  960. int
  961. router_rebuild_descriptor(int force)
  962. {
  963. routerinfo_t *ri;
  964. extrainfo_t *ei;
  965. uint32_t addr;
  966. char platform[256];
  967. int hibernating = we_are_hibernating();
  968. or_options_t *options = get_options();
  969. if (desc_clean_since && !force)
  970. return 0;
  971. if (router_pick_published_address(options, &addr) < 0) {
  972. /* Stop trying to rebuild our descriptor every second. We'll
  973. * learn that it's time to try again when server_has_changed_ip()
  974. * marks it dirty. */
  975. desc_clean_since = time(NULL);
  976. return -1;
  977. }
  978. ri = tor_malloc_zero(sizeof(routerinfo_t));
  979. ri->routerlist_index = -1;
  980. ri->address = tor_dup_addr(addr);
  981. ri->nickname = tor_strdup(options->Nickname);
  982. ri->addr = addr;
  983. ri->or_port = options->ORPort;
  984. ri->dir_port = options->DirPort;
  985. ri->cache_info.published_on = time(NULL);
  986. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  987. * main thread */
  988. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  989. if (crypto_pk_get_digest(ri->identity_pkey,
  990. ri->cache_info.identity_digest)<0) {
  991. routerinfo_free(ri);
  992. return -1;
  993. }
  994. get_platform_str(platform, sizeof(platform));
  995. ri->platform = tor_strdup(platform);
  996. /* compute ri->bandwidthrate as the min of various options */
  997. ri->bandwidthrate = (int)options->BandwidthRate;
  998. if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
  999. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  1000. if (options->RelayBandwidthRate > 0 &&
  1001. ri->bandwidthrate > options->RelayBandwidthRate)
  1002. ri->bandwidthrate = (int)options->RelayBandwidthRate;
  1003. /* and compute ri->bandwidthburst similarly */
  1004. ri->bandwidthburst = (int)options->BandwidthBurst;
  1005. if (options->RelayBandwidthBurst > 0 &&
  1006. ri->bandwidthburst > options->RelayBandwidthBurst)
  1007. ri->bandwidthburst = (int)options->RelayBandwidthBurst;
  1008. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1009. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1010. options->ExitPolicyRejectPrivate);
  1011. if (desc_routerinfo) { /* inherit values */
  1012. ri->is_valid = desc_routerinfo->is_valid;
  1013. ri->is_running = desc_routerinfo->is_running;
  1014. ri->is_named = desc_routerinfo->is_named;
  1015. }
  1016. if (authdir_mode(options))
  1017. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1018. if (options->MyFamily) {
  1019. smartlist_t *family;
  1020. if (!warned_nonexistent_family)
  1021. warned_nonexistent_family = smartlist_create();
  1022. family = smartlist_create();
  1023. ri->declared_family = smartlist_create();
  1024. smartlist_split_string(family, options->MyFamily, ",",
  1025. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1026. SMARTLIST_FOREACH(family, char *, name,
  1027. {
  1028. routerinfo_t *member;
  1029. if (!strcasecmp(name, options->Nickname))
  1030. member = ri;
  1031. else
  1032. member = router_get_by_nickname(name, 1);
  1033. if (!member) {
  1034. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1035. !is_legal_hexdigest(name)) {
  1036. log_warn(LD_CONFIG,
  1037. "I have no descriptor for the router named \"%s\" "
  1038. "in my declared family; I'll use the nickname as is, but "
  1039. "this may confuse clients.", name);
  1040. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1041. }
  1042. smartlist_add(ri->declared_family, name);
  1043. name = NULL;
  1044. } else if (router_is_me(member)) {
  1045. /* Don't list ourself in our own family; that's redundant */
  1046. } else {
  1047. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1048. fp[0] = '$';
  1049. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1050. member->cache_info.identity_digest, DIGEST_LEN);
  1051. smartlist_add(ri->declared_family, fp);
  1052. if (smartlist_string_isin(warned_nonexistent_family, name))
  1053. smartlist_string_remove(warned_nonexistent_family, name);
  1054. }
  1055. tor_free(name);
  1056. });
  1057. /* remove duplicates from the list */
  1058. smartlist_sort_strings(ri->declared_family);
  1059. smartlist_uniq_strings(ri->declared_family);
  1060. smartlist_free(family);
  1061. }
  1062. /* Now generate the extrainfo. */
  1063. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1064. ei->cache_info.is_extrainfo = 1;
  1065. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1066. ei->cache_info.published_on = ri->cache_info.published_on;
  1067. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1068. DIGEST_LEN);
  1069. ei->cache_info.signed_descriptor_body = tor_malloc(8192);
  1070. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
  1071. ei, get_identity_key()) < 0) {
  1072. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1073. return -1;
  1074. }
  1075. ei->cache_info.signed_descriptor_len =
  1076. strlen(ei->cache_info.signed_descriptor_body);
  1077. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1078. ei->cache_info.signed_descriptor_digest);
  1079. /* Now finish the router descriptor. */
  1080. memcpy(ri->cache_info.extra_info_digest,
  1081. ei->cache_info.signed_descriptor_digest,
  1082. DIGEST_LEN);
  1083. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1084. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1085. ri, get_identity_key())<0) {
  1086. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1087. return -1;
  1088. }
  1089. ri->cache_info.signed_descriptor_len =
  1090. strlen(ri->cache_info.signed_descriptor_body);
  1091. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1092. ri->cache_info.signed_descriptor_digest);
  1093. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL));
  1094. if (desc_routerinfo)
  1095. routerinfo_free(desc_routerinfo);
  1096. desc_routerinfo = ri;
  1097. if (desc_extrainfo)
  1098. extrainfo_free(desc_extrainfo);
  1099. desc_extrainfo = ei;
  1100. desc_clean_since = time(NULL);
  1101. desc_needs_upload = 1;
  1102. control_event_my_descriptor_changed();
  1103. return 0;
  1104. }
  1105. /** Mark descriptor out of date if it's older than <b>when</b> */
  1106. void
  1107. mark_my_descriptor_dirty_if_older_than(time_t when)
  1108. {
  1109. if (desc_clean_since < when)
  1110. mark_my_descriptor_dirty();
  1111. }
  1112. /** Call when the current descriptor is out of date. */
  1113. void
  1114. mark_my_descriptor_dirty(void)
  1115. {
  1116. desc_clean_since = 0;
  1117. }
  1118. /** How frequently will we republish our descriptor because of large (factor
  1119. * of 2) shifts in estimated bandwidth? */
  1120. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1121. /** Check whether bandwidth has changed a lot since the last time we announced
  1122. * bandwidth. If so, mark our descriptor dirty. */
  1123. void
  1124. check_descriptor_bandwidth_changed(time_t now)
  1125. {
  1126. static time_t last_changed = 0;
  1127. uint64_t prev, cur;
  1128. if (!desc_routerinfo)
  1129. return;
  1130. prev = desc_routerinfo->bandwidthcapacity;
  1131. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1132. if ((prev != cur && (!prev || !cur)) ||
  1133. cur > prev*2 ||
  1134. cur < prev/2) {
  1135. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1136. log_info(LD_GENERAL,
  1137. "Measured bandwidth has changed; rebuilding descriptor.");
  1138. mark_my_descriptor_dirty();
  1139. last_changed = now;
  1140. }
  1141. }
  1142. }
  1143. /** Note at log level severity that our best guess of address has changed from
  1144. * <b>prev</b> to <b>cur</b>. */
  1145. static void
  1146. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  1147. {
  1148. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1149. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1150. struct in_addr in_prev;
  1151. struct in_addr in_cur;
  1152. in_prev.s_addr = htonl(prev);
  1153. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1154. in_cur.s_addr = htonl(cur);
  1155. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1156. if (prev)
  1157. log_fn(severity, LD_GENERAL,
  1158. "Our IP Address has changed from %s to %s; "
  1159. "rebuilding descriptor.",
  1160. addrbuf_prev, addrbuf_cur);
  1161. else
  1162. log_notice(LD_GENERAL,
  1163. "Guessed our IP address as %s.",
  1164. addrbuf_cur);
  1165. }
  1166. /** Check whether our own address as defined by the Address configuration
  1167. * has changed. This is for routers that get their address from a service
  1168. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1169. void
  1170. check_descriptor_ipaddress_changed(time_t now)
  1171. {
  1172. uint32_t prev, cur;
  1173. or_options_t *options = get_options();
  1174. (void) now;
  1175. if (!desc_routerinfo)
  1176. return;
  1177. prev = desc_routerinfo->addr;
  1178. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1179. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1180. return;
  1181. }
  1182. if (prev != cur) {
  1183. log_addr_has_changed(LOG_INFO, prev, cur);
  1184. ip_address_changed(0);
  1185. }
  1186. }
  1187. /** The most recently guessed value of our IP address, based on directory
  1188. * headers. */
  1189. static uint32_t last_guessed_ip = 0;
  1190. /** A directory server told us our IP address is <b>suggestion</b>.
  1191. * If this address is different from the one we think we are now, and
  1192. * if our computer doesn't actually know its IP address, then switch. */
  1193. void
  1194. router_new_address_suggestion(const char *suggestion)
  1195. {
  1196. uint32_t addr, cur = 0;
  1197. struct in_addr in;
  1198. or_options_t *options = get_options();
  1199. /* first, learn what the IP address actually is */
  1200. if (!tor_inet_aton(suggestion, &in)) {
  1201. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1202. escaped(suggestion));
  1203. return;
  1204. }
  1205. addr = ntohl(in.s_addr);
  1206. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1207. if (!server_mode(options)) {
  1208. last_guessed_ip = addr; /* store it in case we need it later */
  1209. return;
  1210. }
  1211. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1212. /* We're all set -- we already know our address. Great. */
  1213. last_guessed_ip = cur; /* store it in case we need it later */
  1214. return;
  1215. }
  1216. if (is_internal_IP(addr, 0)) {
  1217. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1218. return;
  1219. }
  1220. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1221. * us an answer different from what we had the last time we managed to
  1222. * resolve it. */
  1223. if (last_guessed_ip != addr) {
  1224. control_event_server_status(LOG_NOTICE,
  1225. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1226. suggestion);
  1227. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  1228. ip_address_changed(0);
  1229. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1230. }
  1231. }
  1232. /** We failed to resolve our address locally, but we'd like to build
  1233. * a descriptor and publish / test reachability. If we have a guess
  1234. * about our address based on directory headers, answer it and return
  1235. * 0; else return -1. */
  1236. static int
  1237. router_guess_address_from_dir_headers(uint32_t *guess)
  1238. {
  1239. if (last_guessed_ip) {
  1240. *guess = last_guessed_ip;
  1241. return 0;
  1242. }
  1243. return -1;
  1244. }
  1245. extern const char tor_svn_revision[]; /* from main.c */
  1246. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1247. * string describing the version of Tor and the operating system we're
  1248. * currently running on.
  1249. */
  1250. void
  1251. get_platform_str(char *platform, size_t len)
  1252. {
  1253. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1254. }
  1255. /* XXX need to audit this thing and count fenceposts. maybe
  1256. * refactor so we don't have to keep asking if we're
  1257. * near the end of maxlen?
  1258. */
  1259. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1260. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1261. * with, encode the routerinfo as a signed server descriptor and write the
  1262. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1263. * failure, and the number of bytes used on success.
  1264. */
  1265. int
  1266. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1267. crypto_pk_env_t *ident_key)
  1268. {
  1269. char *onion_pkey; /* Onion key, PEM-encoded. */
  1270. char *identity_pkey; /* Identity key, PEM-encoded. */
  1271. char digest[DIGEST_LEN];
  1272. char published[ISO_TIME_LEN+1];
  1273. char fingerprint[FINGERPRINT_LEN+1];
  1274. char extra_info_digest[HEX_DIGEST_LEN+1];
  1275. size_t onion_pkeylen, identity_pkeylen;
  1276. size_t written;
  1277. int result=0;
  1278. addr_policy_t *tmpe;
  1279. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1280. char *bandwidth_usage;
  1281. #endif
  1282. char *family_line;
  1283. or_options_t *options = get_options();
  1284. /* Make sure the identity key matches the one in the routerinfo. */
  1285. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1286. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1287. "match router's public key!");
  1288. return -1;
  1289. }
  1290. /* record our fingerprint, so we can include it in the descriptor */
  1291. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1292. log_err(LD_BUG,"Error computing fingerprint");
  1293. return -1;
  1294. }
  1295. /* PEM-encode the onion key */
  1296. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1297. &onion_pkey,&onion_pkeylen)<0) {
  1298. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1299. return -1;
  1300. }
  1301. /* PEM-encode the identity key key */
  1302. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1303. &identity_pkey,&identity_pkeylen)<0) {
  1304. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1305. tor_free(onion_pkey);
  1306. return -1;
  1307. }
  1308. /* Encode the publication time. */
  1309. format_iso_time(published, router->cache_info.published_on);
  1310. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1311. /* How busy have we been? */
  1312. bandwidth_usage = rep_hist_get_bandwidth_lines(0);
  1313. #endif
  1314. if (router->declared_family && smartlist_len(router->declared_family)) {
  1315. size_t n;
  1316. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1317. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1318. family_line = tor_malloc(n);
  1319. tor_snprintf(family_line, n, "family %s\n", family);
  1320. tor_free(family);
  1321. } else {
  1322. family_line = tor_strdup("");
  1323. }
  1324. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1325. router->cache_info.extra_info_digest, DIGEST_LEN);
  1326. /* Generate the easy portion of the router descriptor. */
  1327. result = tor_snprintf(s, maxlen,
  1328. "router %s %s %d 0 %d\n"
  1329. "platform %s\n"
  1330. "published %s\n"
  1331. "opt fingerprint %s\n"
  1332. "uptime %ld\n"
  1333. "bandwidth %d %d %d\n"
  1334. "opt extra-info-digest %s\n%s"
  1335. "onion-key\n%s"
  1336. "signing-key\n%s"
  1337. "%s%s%s",
  1338. router->nickname,
  1339. router->address,
  1340. router->or_port,
  1341. decide_to_advertise_dirport(options, router),
  1342. router->platform,
  1343. published,
  1344. fingerprint,
  1345. stats_n_seconds_working,
  1346. (int) router->bandwidthrate,
  1347. (int) router->bandwidthburst,
  1348. (int) router->bandwidthcapacity,
  1349. extra_info_digest,
  1350. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1351. onion_pkey, identity_pkey,
  1352. family_line,
  1353. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1354. bandwidth_usage,
  1355. #else
  1356. "",
  1357. #endif
  1358. we_are_hibernating() ? "opt hibernating 1\n" : "");
  1359. tor_free(family_line);
  1360. tor_free(onion_pkey);
  1361. tor_free(identity_pkey);
  1362. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1363. tor_free(bandwidth_usage);
  1364. #endif
  1365. if (result < 0) {
  1366. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1367. return -1;
  1368. }
  1369. /* From now on, we use 'written' to remember the current length of 's'. */
  1370. written = result;
  1371. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1372. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1373. options->ContactInfo);
  1374. if (result<0) {
  1375. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1376. return -1;
  1377. }
  1378. written += result;
  1379. }
  1380. /* Write the exit policy to the end of 's'. */
  1381. tmpe = router->exit_policy;
  1382. if (dns_seems_to_be_broken()) {
  1383. /* DNS is screwed up; don't claim to be an exit. */
  1384. strlcat(s+written, "reject *:*\n", maxlen-written);
  1385. written += strlen("reject *:*\n");
  1386. tmpe = NULL;
  1387. }
  1388. for ( ; tmpe; tmpe=tmpe->next) {
  1389. result = policy_write_item(s+written, maxlen-written, tmpe);
  1390. if (result < 0) {
  1391. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1392. return -1;
  1393. }
  1394. tor_assert(result == (int)strlen(s+written));
  1395. written += result;
  1396. if (written+2 > maxlen) {
  1397. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1398. return -1;
  1399. }
  1400. s[written++] = '\n';
  1401. }
  1402. if (written+256 > maxlen) { /* Not enough room for signature. */
  1403. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1404. return -1;
  1405. }
  1406. /* Sign the directory */
  1407. strlcpy(s+written, "router-signature\n", maxlen-written);
  1408. written += strlen(s+written);
  1409. s[written] = '\0';
  1410. if (router_get_router_hash(s, digest) < 0) {
  1411. return -1;
  1412. }
  1413. note_crypto_pk_op(SIGN_RTR);
  1414. if (router_append_dirobj_signature(s+written,maxlen-written,
  1415. digest,ident_key)<0) {
  1416. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1417. return -1;
  1418. }
  1419. written += strlen(s+written);
  1420. if (written+2 > maxlen) {
  1421. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1422. return -1;
  1423. }
  1424. /* include a last '\n' */
  1425. s[written] = '\n';
  1426. s[written+1] = 0;
  1427. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1428. {
  1429. char *s_dup;
  1430. const char *cp;
  1431. routerinfo_t *ri_tmp;
  1432. cp = s_dup = tor_strdup(s);
  1433. ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
  1434. if (!ri_tmp) {
  1435. log_err(LD_BUG,
  1436. "We just generated a router descriptor we can't parse.");
  1437. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1438. return -1;
  1439. }
  1440. tor_free(s_dup);
  1441. routerinfo_free(ri_tmp);
  1442. }
  1443. #endif
  1444. return written+1;
  1445. }
  1446. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1447. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1448. * negative on failure. */
  1449. int
  1450. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1451. crypto_pk_env_t *ident_key)
  1452. {
  1453. char identity[HEX_DIGEST_LEN+1];
  1454. char published[ISO_TIME_LEN+1];
  1455. char digest[DIGEST_LEN];
  1456. char *bandwidth_usage;
  1457. int result;
  1458. size_t len;
  1459. base16_encode(identity, sizeof(identity),
  1460. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1461. format_iso_time(published, extrainfo->cache_info.published_on);
  1462. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1463. result = tor_snprintf(s, maxlen,
  1464. "extra-info %s %s\n"
  1465. "published %s\n%s"
  1466. "router-signature\n",
  1467. extrainfo->nickname, identity,
  1468. published, bandwidth_usage);
  1469. tor_free(bandwidth_usage);
  1470. if (result<0)
  1471. return -1;
  1472. len = strlen(s);
  1473. if (router_get_extrainfo_hash(s, digest)<0)
  1474. return -1;
  1475. if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
  1476. return -1;
  1477. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1478. {
  1479. char *cp, *s_dup;
  1480. extrainfo_t *ei_tmp;
  1481. cp = s_dup = tor_strdup(s);
  1482. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1483. if (!ei_tmp) {
  1484. log_err(LD_BUG,
  1485. "We just generated an extrainfo descriptor we can't parse.");
  1486. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1487. return -1;
  1488. }
  1489. tor_free(s_dup);
  1490. extrainfo_free(ei_tmp);
  1491. }
  1492. #endif
  1493. return strlen(s)+1;
  1494. }
  1495. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1496. int
  1497. is_legal_nickname(const char *s)
  1498. {
  1499. size_t len;
  1500. tor_assert(s);
  1501. len = strlen(s);
  1502. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1503. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1504. }
  1505. /** Return true iff <b>s</b> is a legally valid server nickname or
  1506. * hex-encoded identity-key digest. */
  1507. int
  1508. is_legal_nickname_or_hexdigest(const char *s)
  1509. {
  1510. if (*s!='$')
  1511. return is_legal_nickname(s);
  1512. else
  1513. return is_legal_hexdigest(s);
  1514. }
  1515. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1516. * digest. */
  1517. int
  1518. is_legal_hexdigest(const char *s)
  1519. {
  1520. size_t len;
  1521. tor_assert(s);
  1522. if (s[0] == '$') s++;
  1523. len = strlen(s);
  1524. if (len > HEX_DIGEST_LEN) {
  1525. if (s[HEX_DIGEST_LEN] == '=' ||
  1526. s[HEX_DIGEST_LEN] == '~') {
  1527. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1528. return 0;
  1529. } else {
  1530. return 0;
  1531. }
  1532. }
  1533. return (len >= HEX_DIGEST_LEN &&
  1534. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1535. }
  1536. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1537. * verbose representation of the identity of <b>router</b>. The format is:
  1538. * A dollar sign.
  1539. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1540. * A "=" if the router is named; a "~" if it is not.
  1541. * The router's nickname.
  1542. **/
  1543. void
  1544. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1545. {
  1546. buf[0] = '$';
  1547. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1548. DIGEST_LEN);
  1549. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1550. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1551. }
  1552. /** Forget that we have issued any router-related warnings, so that we'll
  1553. * warn again if we see the same errors. */
  1554. void
  1555. router_reset_warnings(void)
  1556. {
  1557. if (warned_nonexistent_family) {
  1558. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1559. smartlist_clear(warned_nonexistent_family);
  1560. }
  1561. }
  1562. /** Release all static resources held in router.c */
  1563. void
  1564. router_free_all(void)
  1565. {
  1566. if (onionkey)
  1567. crypto_free_pk_env(onionkey);
  1568. if (lastonionkey)
  1569. crypto_free_pk_env(lastonionkey);
  1570. if (identitykey)
  1571. crypto_free_pk_env(identitykey);
  1572. if (key_lock)
  1573. tor_mutex_free(key_lock);
  1574. if (desc_routerinfo)
  1575. routerinfo_free(desc_routerinfo);
  1576. if (desc_extrainfo)
  1577. extrainfo_free(desc_extrainfo);
  1578. if (authority_signing_key)
  1579. crypto_free_pk_env(authority_signing_key);
  1580. if (authority_key_certificate)
  1581. authority_cert_free(authority_key_certificate);
  1582. if (warned_nonexistent_family) {
  1583. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1584. smartlist_free(warned_nonexistent_family);
  1585. }
  1586. }