router.c 64 KB

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