router.c 72 KB

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