router.c 64 KB

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