router.c 68 KB

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