router.c 68 KB

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