router.c 64 KB

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