router.c 63 KB

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