router.c 68 KB

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