router.c 69 KB

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