router.c 68 KB

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