router.c 69 KB

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