router.c 68 KB

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