router.c 68 KB

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