router.c 63 KB

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