router.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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-2009, 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. get_options()->AccelName,
  408. get_options()->AccelDir)) {
  409. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  410. return -1;
  411. }
  412. /* OP's don't need persistent keys; just make up an identity and
  413. * initialize the TLS context. */
  414. if (!server_mode(options)) {
  415. if (!(prkey = crypto_new_pk_env()))
  416. return -1;
  417. if (crypto_pk_generate_key(prkey)) {
  418. crypto_free_pk_env(prkey);
  419. return -1;
  420. }
  421. set_identity_key(prkey);
  422. /* Create a TLS context; default the client nickname to "client". */
  423. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
  424. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  425. return -1;
  426. }
  427. return 0;
  428. }
  429. /* Make sure DataDirectory exists, and is private. */
  430. if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
  431. return -1;
  432. }
  433. /* Check the key directory. */
  434. keydir = get_datadir_fname("keys");
  435. if (check_private_dir(keydir, CPD_CREATE)) {
  436. tor_free(keydir);
  437. return -1;
  438. }
  439. tor_free(keydir);
  440. /* 1a. Read v3 directory authority key/cert information. */
  441. memset(v3_digest, 0, sizeof(v3_digest));
  442. if (authdir_mode_v3(options)) {
  443. if (init_v3_authority_keys()<0) {
  444. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  445. "were unable to load our v3 authority keys and certificate! "
  446. "Use tor-gencert to generate them. Dying.");
  447. return -1;
  448. }
  449. cert = get_my_v3_authority_cert();
  450. if (cert) {
  451. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  452. v3_digest);
  453. v3_digest_set = 1;
  454. }
  455. }
  456. /* 1. Read identity key. Make it if none is found. */
  457. keydir = get_datadir_fname2("keys", "secret_id_key");
  458. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  459. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  460. tor_free(keydir);
  461. if (!prkey) return -1;
  462. set_identity_key(prkey);
  463. /* 2. Read onion key. Make it if none is found. */
  464. keydir = get_datadir_fname2("keys", "secret_onion_key");
  465. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  466. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  467. tor_free(keydir);
  468. if (!prkey) return -1;
  469. set_onion_key(prkey);
  470. if (options->command == CMD_RUN_TOR) {
  471. /* only mess with the state file if we're actually running Tor */
  472. or_state_t *state = get_or_state();
  473. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  474. /* We allow for some parsing slop, but we don't want to risk accepting
  475. * values in the distant future. If we did, we might never rotate the
  476. * onion key. */
  477. onionkey_set_at = state->LastRotatedOnionKey;
  478. } else {
  479. /* We have no LastRotatedOnionKey set; either we just created the key
  480. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  481. * start the clock ticking now so that we will eventually rotate it even
  482. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  483. state->LastRotatedOnionKey = onionkey_set_at = now;
  484. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  485. time(NULL)+3600 : 0);
  486. }
  487. }
  488. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  489. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  490. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  491. if (prkey)
  492. lastonionkey = prkey;
  493. }
  494. tor_free(keydir);
  495. /* 3. Initialize link key and TLS context. */
  496. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 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. memcmp(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. if (!can_reach_or_port) {
  733. routerinfo_t *me = router_get_my_routerinfo();
  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. if (!me) { /* should never happen */
  741. log_warn(LD_BUG, "ORPort found reachable, but I have no routerinfo "
  742. "yet. Failing to inform controller of success.");
  743. return;
  744. }
  745. control_event_server_status(LOG_NOTICE,
  746. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  747. me->address, me->or_port);
  748. }
  749. }
  750. /** Annotate that we found our DirPort reachable. */
  751. void
  752. router_dirport_found_reachable(void)
  753. {
  754. if (!can_reach_dir_port) {
  755. routerinfo_t *me = router_get_my_routerinfo();
  756. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  757. "from the outside. Excellent.");
  758. can_reach_dir_port = 1;
  759. if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
  760. mark_my_descriptor_dirty();
  761. if (!me) { /* should never happen */
  762. log_warn(LD_BUG, "DirPort found reachable, but I have no routerinfo "
  763. "yet. Failing to inform controller of success.");
  764. return;
  765. }
  766. control_event_server_status(LOG_NOTICE,
  767. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  768. me->address, me->dir_port);
  769. }
  770. }
  771. /** We have enough testing circuits open. Send a bunch of "drop"
  772. * cells down each of them, to exercise our bandwidth. */
  773. void
  774. router_perform_bandwidth_test(int num_circs, time_t now)
  775. {
  776. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  777. int max_cells = num_cells < CIRCWINDOW_START ?
  778. num_cells : CIRCWINDOW_START;
  779. int cells_per_circuit = max_cells / num_circs;
  780. origin_circuit_t *circ = NULL;
  781. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  782. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  783. CIRCUIT_PURPOSE_TESTING))) {
  784. /* dump cells_per_circuit drop cells onto this circ */
  785. int i = cells_per_circuit;
  786. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  787. continue;
  788. circ->_base.timestamp_dirty = now;
  789. while (i-- > 0) {
  790. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  791. RELAY_COMMAND_DROP,
  792. NULL, 0, circ->cpath->prev)<0) {
  793. return; /* stop if error */
  794. }
  795. }
  796. }
  797. }
  798. /** Return true iff we believe ourselves to be an authoritative
  799. * directory server.
  800. */
  801. int
  802. authdir_mode(or_options_t *options)
  803. {
  804. return options->AuthoritativeDir != 0;
  805. }
  806. /** Return true iff we believe ourselves to be a v1 authoritative
  807. * directory server.
  808. */
  809. int
  810. authdir_mode_v1(or_options_t *options)
  811. {
  812. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  813. }
  814. /** Return true iff we believe ourselves to be a v2 authoritative
  815. * directory server.
  816. */
  817. int
  818. authdir_mode_v2(or_options_t *options)
  819. {
  820. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  821. }
  822. /** Return true iff we believe ourselves to be a v3 authoritative
  823. * directory server.
  824. */
  825. int
  826. authdir_mode_v3(or_options_t *options)
  827. {
  828. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  829. }
  830. /** Return true iff we are a v1, v2, or v3 directory authority. */
  831. int
  832. authdir_mode_any_main(or_options_t *options)
  833. {
  834. return options->V1AuthoritativeDir ||
  835. options->V2AuthoritativeDir ||
  836. options->V3AuthoritativeDir;
  837. }
  838. /** Return true if we believe ourselves to be any kind of
  839. * authoritative directory beyond just a hidserv authority. */
  840. int
  841. authdir_mode_any_nonhidserv(or_options_t *options)
  842. {
  843. return options->BridgeAuthoritativeDir ||
  844. authdir_mode_any_main(options);
  845. }
  846. /** Return true iff we are an authoritative directory server that is
  847. * authoritative about receiving and serving descriptors of type
  848. * <b>purpose</b> its dirport. Use -1 for "any purpose". */
  849. int
  850. authdir_mode_handles_descs(or_options_t *options, int purpose)
  851. {
  852. if (purpose < 0)
  853. return authdir_mode_any_nonhidserv(options);
  854. else if (purpose == ROUTER_PURPOSE_GENERAL)
  855. return authdir_mode_any_main(options);
  856. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  857. return (options->BridgeAuthoritativeDir);
  858. else
  859. return 0;
  860. }
  861. /** Return true iff we are an authoritative directory server that
  862. * publishes its own network statuses.
  863. */
  864. int
  865. authdir_mode_publishes_statuses(or_options_t *options)
  866. {
  867. if (authdir_mode_bridge(options))
  868. return 0;
  869. return authdir_mode_any_nonhidserv(options);
  870. }
  871. /** Return true iff we are an authoritative directory server that
  872. * tests reachability of the descriptors it learns about.
  873. */
  874. int
  875. authdir_mode_tests_reachability(or_options_t *options)
  876. {
  877. return authdir_mode_handles_descs(options, -1);
  878. }
  879. /** Return true iff we believe ourselves to be a bridge authoritative
  880. * directory server.
  881. */
  882. int
  883. authdir_mode_bridge(or_options_t *options)
  884. {
  885. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  886. }
  887. /** Return true iff we once tried to stay connected to all ORs at once.
  888. * FFFF this function, and the notion of staying connected to ORs, is
  889. * nearly obsolete. One day there will be a proposal for getting rid of
  890. * it.
  891. */
  892. int
  893. clique_mode(or_options_t *options)
  894. {
  895. return authdir_mode_tests_reachability(options);
  896. }
  897. /** Return true iff we are trying to be a server.
  898. */
  899. int
  900. server_mode(or_options_t *options)
  901. {
  902. if (options->ClientOnly) return 0;
  903. return (options->ORPort != 0 || options->ORListenAddress);
  904. }
  905. /** Remember if we've advertised ourselves to the dirservers. */
  906. static int server_is_advertised=0;
  907. /** Return true iff we have published our descriptor lately.
  908. */
  909. int
  910. advertised_server_mode(void)
  911. {
  912. return server_is_advertised;
  913. }
  914. /**
  915. * Called with a boolean: set whether we have recently published our
  916. * descriptor.
  917. */
  918. static void
  919. set_server_advertised(int s)
  920. {
  921. server_is_advertised = s;
  922. }
  923. /** Return true iff we are trying to be a socks proxy. */
  924. int
  925. proxy_mode(or_options_t *options)
  926. {
  927. return (options->SocksPort != 0 || options->SocksListenAddress ||
  928. options->TransPort != 0 || options->TransListenAddress ||
  929. options->NatdPort != 0 || options->NatdListenAddress ||
  930. options->DNSPort != 0 || options->DNSListenAddress);
  931. }
  932. /** Decide if we're a publishable server. We are a publishable server if:
  933. * - We don't have the ClientOnly option set
  934. * and
  935. * - We have the PublishServerDescriptor option set to non-empty
  936. * and
  937. * - We have ORPort set
  938. * and
  939. * - We believe we are reachable from the outside; or
  940. * - We are an authoritative directory server.
  941. */
  942. static int
  943. decide_if_publishable_server(void)
  944. {
  945. or_options_t *options = get_options();
  946. if (options->ClientOnly)
  947. return 0;
  948. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  949. return 0;
  950. if (!server_mode(options))
  951. return 0;
  952. if (authdir_mode(options))
  953. return 1;
  954. return check_whether_orport_reachable();
  955. }
  956. /** Initiate server descriptor upload as reasonable (if server is publishable,
  957. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  958. *
  959. * We need to rebuild the descriptor if it's dirty even if we're not
  960. * uploading, because our reachability testing *uses* our descriptor to
  961. * determine what IP address and ports to test.
  962. */
  963. void
  964. consider_publishable_server(int force)
  965. {
  966. int rebuilt;
  967. if (!server_mode(get_options()))
  968. return;
  969. rebuilt = router_rebuild_descriptor(0);
  970. if (decide_if_publishable_server()) {
  971. set_server_advertised(1);
  972. if (rebuilt == 0)
  973. router_upload_dir_desc_to_dirservers(force);
  974. } else {
  975. set_server_advertised(0);
  976. }
  977. }
  978. /*
  979. * Clique maintenance -- to be phased out.
  980. */
  981. /** Return true iff we believe this OR tries to keep connections open
  982. * to all other ORs. */
  983. int
  984. router_is_clique_mode(routerinfo_t *router)
  985. {
  986. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  987. return 1;
  988. return 0;
  989. }
  990. /*
  991. * OR descriptor generation.
  992. */
  993. /** My routerinfo. */
  994. static routerinfo_t *desc_routerinfo = NULL;
  995. /** My extrainfo */
  996. static extrainfo_t *desc_extrainfo = NULL;
  997. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  998. * now. */
  999. static time_t desc_clean_since = 0;
  1000. /** Boolean: do we need to regenerate the above? */
  1001. static int desc_needs_upload = 0;
  1002. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1003. * descriptor successfully yet, try to upload our signed descriptor to
  1004. * all the directory servers we know about.
  1005. */
  1006. void
  1007. router_upload_dir_desc_to_dirservers(int force)
  1008. {
  1009. routerinfo_t *ri;
  1010. extrainfo_t *ei;
  1011. char *msg;
  1012. size_t desc_len, extra_len = 0, total_len;
  1013. authority_type_t auth = get_options()->_PublishServerDescriptor;
  1014. ri = router_get_my_routerinfo();
  1015. if (!ri) {
  1016. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1017. return;
  1018. }
  1019. ei = router_get_my_extrainfo();
  1020. if (auth == NO_AUTHORITY)
  1021. return;
  1022. if (!force && !desc_needs_upload)
  1023. return;
  1024. desc_needs_upload = 0;
  1025. desc_len = ri->cache_info.signed_descriptor_len;
  1026. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1027. total_len = desc_len + extra_len + 1;
  1028. msg = tor_malloc(total_len);
  1029. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1030. if (ei) {
  1031. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1032. }
  1033. msg[desc_len+extra_len] = 0;
  1034. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1035. (auth & BRIDGE_AUTHORITY) ?
  1036. ROUTER_PURPOSE_BRIDGE :
  1037. ROUTER_PURPOSE_GENERAL,
  1038. auth, msg, desc_len, extra_len);
  1039. tor_free(msg);
  1040. }
  1041. /** OR only: Check whether my exit policy says to allow connection to
  1042. * conn. Return 0 if we accept; non-0 if we reject.
  1043. */
  1044. int
  1045. router_compare_to_my_exit_policy(edge_connection_t *conn)
  1046. {
  1047. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1048. return -1;
  1049. /* make sure it's resolved to something. this way we can't get a
  1050. 'maybe' below. */
  1051. if (tor_addr_is_null(&conn->_base.addr))
  1052. return -1;
  1053. /* XXXX IPv6 */
  1054. if (tor_addr_family(&conn->_base.addr) != AF_INET)
  1055. return -1;
  1056. return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
  1057. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  1058. }
  1059. /** Return true iff I'm a server and <b>digest</b> is equal to
  1060. * my identity digest. */
  1061. int
  1062. router_digest_is_me(const char *digest)
  1063. {
  1064. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  1065. }
  1066. /** Return true iff I'm a server and <b>digest</b> is equal to
  1067. * my identity digest. */
  1068. int
  1069. router_extrainfo_digest_is_me(const char *digest)
  1070. {
  1071. extrainfo_t *ei = router_get_my_extrainfo();
  1072. if (!ei)
  1073. return 0;
  1074. return !memcmp(digest,
  1075. ei->cache_info.signed_descriptor_digest,
  1076. DIGEST_LEN);
  1077. }
  1078. /** A wrapper around router_digest_is_me(). */
  1079. int
  1080. router_is_me(routerinfo_t *router)
  1081. {
  1082. return router_digest_is_me(router->cache_info.identity_digest);
  1083. }
  1084. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  1085. int
  1086. router_fingerprint_is_me(const char *fp)
  1087. {
  1088. char digest[DIGEST_LEN];
  1089. if (strlen(fp) == HEX_DIGEST_LEN &&
  1090. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  1091. return router_digest_is_me(digest);
  1092. return 0;
  1093. }
  1094. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1095. * necessary. Return NULL on error, or if called on an OP. */
  1096. routerinfo_t *
  1097. router_get_my_routerinfo(void)
  1098. {
  1099. if (!server_mode(get_options()))
  1100. return NULL;
  1101. if (router_rebuild_descriptor(0))
  1102. return NULL;
  1103. return desc_routerinfo;
  1104. }
  1105. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1106. * one if necessary. Return NULL on error.
  1107. */
  1108. const char *
  1109. router_get_my_descriptor(void)
  1110. {
  1111. const char *body;
  1112. if (!router_get_my_routerinfo())
  1113. return NULL;
  1114. /* Make sure this is nul-terminated. */
  1115. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1116. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1117. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1118. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1119. return body;
  1120. }
  1121. /** Return the extrainfo document for this OR, or NULL if we have none.
  1122. * Rebuilt it (and the server descriptor) if necessary. */
  1123. extrainfo_t *
  1124. router_get_my_extrainfo(void)
  1125. {
  1126. if (!server_mode(get_options()))
  1127. return NULL;
  1128. if (router_rebuild_descriptor(0))
  1129. return NULL;
  1130. return desc_extrainfo;
  1131. }
  1132. /** A list of nicknames that we've warned about including in our family
  1133. * declaration verbatim rather than as digests. */
  1134. static smartlist_t *warned_nonexistent_family = NULL;
  1135. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1136. /** Make a current best guess at our address, either because
  1137. * it's configured in torrc, or because we've learned it from
  1138. * dirserver headers. Place the answer in *<b>addr</b> and return
  1139. * 0 on success, else return -1 if we have no guess. */
  1140. int
  1141. router_pick_published_address(or_options_t *options, uint32_t *addr)
  1142. {
  1143. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1144. log_info(LD_CONFIG, "Could not determine our address locally. "
  1145. "Checking if directory headers provide any hints.");
  1146. if (router_guess_address_from_dir_headers(addr) < 0) {
  1147. log_info(LD_CONFIG, "No hints from directory headers either. "
  1148. "Will try again later.");
  1149. return -1;
  1150. }
  1151. }
  1152. return 0;
  1153. }
  1154. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1155. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1156. * Return 0 on success, -1 on temporary error.
  1157. */
  1158. int
  1159. router_rebuild_descriptor(int force)
  1160. {
  1161. routerinfo_t *ri;
  1162. extrainfo_t *ei;
  1163. uint32_t addr;
  1164. char platform[256];
  1165. int hibernating = we_are_hibernating();
  1166. size_t ei_size;
  1167. or_options_t *options = get_options();
  1168. if (desc_clean_since && !force)
  1169. return 0;
  1170. if (router_pick_published_address(options, &addr) < 0) {
  1171. /* Stop trying to rebuild our descriptor every second. We'll
  1172. * learn that it's time to try again when server_has_changed_ip()
  1173. * marks it dirty. */
  1174. desc_clean_since = time(NULL);
  1175. return -1;
  1176. }
  1177. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1178. ri->cache_info.routerlist_index = -1;
  1179. ri->address = tor_dup_ip(addr);
  1180. ri->nickname = tor_strdup(options->Nickname);
  1181. ri->addr = addr;
  1182. ri->or_port = options->ORPort;
  1183. ri->dir_port = options->DirPort;
  1184. ri->cache_info.published_on = time(NULL);
  1185. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1186. * main thread */
  1187. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  1188. if (crypto_pk_get_digest(ri->identity_pkey,
  1189. ri->cache_info.identity_digest)<0) {
  1190. routerinfo_free(ri);
  1191. return -1;
  1192. }
  1193. get_platform_str(platform, sizeof(platform));
  1194. ri->platform = tor_strdup(platform);
  1195. /* compute ri->bandwidthrate as the min of various options */
  1196. ri->bandwidthrate = get_effective_bwrate(options);
  1197. /* and compute ri->bandwidthburst similarly */
  1198. ri->bandwidthburst = get_effective_bwburst(options);
  1199. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1200. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1201. options->ExitPolicyRejectPrivate,
  1202. ri->address, !options->BridgeRelay);
  1203. if (desc_routerinfo) { /* inherit values */
  1204. ri->is_valid = desc_routerinfo->is_valid;
  1205. ri->is_running = desc_routerinfo->is_running;
  1206. ri->is_named = desc_routerinfo->is_named;
  1207. }
  1208. if (authdir_mode(options))
  1209. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1210. if (options->MyFamily) {
  1211. smartlist_t *family;
  1212. if (!warned_nonexistent_family)
  1213. warned_nonexistent_family = smartlist_create();
  1214. family = smartlist_create();
  1215. ri->declared_family = smartlist_create();
  1216. smartlist_split_string(family, options->MyFamily, ",",
  1217. SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1218. SMARTLIST_FOREACH(family, char *, name,
  1219. {
  1220. routerinfo_t *member;
  1221. if (!strcasecmp(name, options->Nickname))
  1222. member = ri;
  1223. else
  1224. member = router_get_by_nickname(name, 1);
  1225. if (!member) {
  1226. int is_legal = is_legal_nickname_or_hexdigest(name);
  1227. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1228. !is_legal_hexdigest(name)) {
  1229. if (is_legal)
  1230. log_warn(LD_CONFIG,
  1231. "I have no descriptor for the router named \"%s\" in my "
  1232. "declared family; I'll use the nickname as is, but "
  1233. "this may confuse clients.", name);
  1234. else
  1235. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1236. "declared family, but that isn't a legal nickname. "
  1237. "Skipping it.", escaped(name));
  1238. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1239. }
  1240. if (is_legal) {
  1241. smartlist_add(ri->declared_family, name);
  1242. name = NULL;
  1243. }
  1244. } else if (router_is_me(member)) {
  1245. /* Don't list ourself in our own family; that's redundant */
  1246. } else {
  1247. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1248. fp[0] = '$';
  1249. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1250. member->cache_info.identity_digest, DIGEST_LEN);
  1251. smartlist_add(ri->declared_family, fp);
  1252. if (smartlist_string_isin(warned_nonexistent_family, name))
  1253. smartlist_string_remove(warned_nonexistent_family, name);
  1254. }
  1255. tor_free(name);
  1256. });
  1257. /* remove duplicates from the list */
  1258. smartlist_sort_strings(ri->declared_family);
  1259. smartlist_uniq_strings(ri->declared_family);
  1260. smartlist_free(family);
  1261. }
  1262. /* Now generate the extrainfo. */
  1263. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1264. ei->cache_info.is_extrainfo = 1;
  1265. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1266. ei->cache_info.published_on = ri->cache_info.published_on;
  1267. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1268. DIGEST_LEN);
  1269. ei_size = options->ExtraInfoStatistics ? MAX_EXTRAINFO_UPLOAD_SIZE : 8192;
  1270. ei->cache_info.signed_descriptor_body = tor_malloc(ei_size);
  1271. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body,
  1272. ei_size, ei, get_identity_key()) < 0) {
  1273. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1274. extrainfo_free(ei);
  1275. return -1;
  1276. }
  1277. ei->cache_info.signed_descriptor_len =
  1278. strlen(ei->cache_info.signed_descriptor_body);
  1279. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1280. ei->cache_info.signed_descriptor_digest);
  1281. /* Now finish the router descriptor. */
  1282. memcpy(ri->cache_info.extra_info_digest,
  1283. ei->cache_info.signed_descriptor_digest,
  1284. DIGEST_LEN);
  1285. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1286. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1287. ri, get_identity_key())<0) {
  1288. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1289. return -1;
  1290. }
  1291. ri->cache_info.signed_descriptor_len =
  1292. strlen(ri->cache_info.signed_descriptor_body);
  1293. ri->purpose =
  1294. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1295. ri->cache_info.send_unencrypted = 1;
  1296. /* Let bridges serve their own descriptors unencrypted, so they can
  1297. * pass reachability testing. (If they want to be harder to notice,
  1298. * they can always leave the DirPort off). */
  1299. if (!options->BridgeRelay)
  1300. ei->cache_info.send_unencrypted = 1;
  1301. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1302. ri->cache_info.signed_descriptor_digest);
  1303. routerinfo_set_country(ri);
  1304. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1305. if (desc_routerinfo)
  1306. routerinfo_free(desc_routerinfo);
  1307. desc_routerinfo = ri;
  1308. if (desc_extrainfo)
  1309. extrainfo_free(desc_extrainfo);
  1310. desc_extrainfo = ei;
  1311. desc_clean_since = time(NULL);
  1312. desc_needs_upload = 1;
  1313. control_event_my_descriptor_changed();
  1314. return 0;
  1315. }
  1316. /** Mark descriptor out of date if it's older than <b>when</b> */
  1317. void
  1318. mark_my_descriptor_dirty_if_older_than(time_t when)
  1319. {
  1320. if (desc_clean_since < when)
  1321. mark_my_descriptor_dirty();
  1322. }
  1323. /** Call when the current descriptor is out of date. */
  1324. void
  1325. mark_my_descriptor_dirty(void)
  1326. {
  1327. desc_clean_since = 0;
  1328. }
  1329. /** How frequently will we republish our descriptor because of large (factor
  1330. * of 2) shifts in estimated bandwidth? */
  1331. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1332. /** Check whether bandwidth has changed a lot since the last time we announced
  1333. * bandwidth. If so, mark our descriptor dirty. */
  1334. void
  1335. check_descriptor_bandwidth_changed(time_t now)
  1336. {
  1337. static time_t last_changed = 0;
  1338. uint64_t prev, cur;
  1339. if (!desc_routerinfo)
  1340. return;
  1341. prev = desc_routerinfo->bandwidthcapacity;
  1342. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1343. if ((prev != cur && (!prev || !cur)) ||
  1344. cur > prev*2 ||
  1345. cur < prev/2) {
  1346. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1347. log_info(LD_GENERAL,
  1348. "Measured bandwidth has changed; rebuilding descriptor.");
  1349. mark_my_descriptor_dirty();
  1350. last_changed = now;
  1351. }
  1352. }
  1353. }
  1354. /** Note at log level severity that our best guess of address has changed from
  1355. * <b>prev</b> to <b>cur</b>. */
  1356. static void
  1357. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
  1358. const char *source)
  1359. {
  1360. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1361. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1362. struct in_addr in_prev;
  1363. struct in_addr in_cur;
  1364. in_prev.s_addr = htonl(prev);
  1365. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1366. in_cur.s_addr = htonl(cur);
  1367. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1368. if (prev)
  1369. log_fn(severity, LD_GENERAL,
  1370. "Our IP Address has changed from %s to %s; "
  1371. "rebuilding descriptor (source: %s).",
  1372. addrbuf_prev, addrbuf_cur, source);
  1373. else
  1374. log_notice(LD_GENERAL,
  1375. "Guessed our IP address as %s (source: %s).",
  1376. addrbuf_cur, source);
  1377. }
  1378. /** Check whether our own address as defined by the Address configuration
  1379. * has changed. This is for routers that get their address from a service
  1380. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1381. void
  1382. check_descriptor_ipaddress_changed(time_t now)
  1383. {
  1384. uint32_t prev, cur;
  1385. or_options_t *options = get_options();
  1386. (void) now;
  1387. if (!desc_routerinfo)
  1388. return;
  1389. prev = desc_routerinfo->addr;
  1390. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1391. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1392. return;
  1393. }
  1394. if (prev != cur) {
  1395. log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
  1396. ip_address_changed(0);
  1397. }
  1398. }
  1399. /** The most recently guessed value of our IP address, based on directory
  1400. * headers. */
  1401. static uint32_t last_guessed_ip = 0;
  1402. /** A directory server <b>d_conn</b> told us our IP address is
  1403. * <b>suggestion</b>.
  1404. * If this address is different from the one we think we are now, and
  1405. * if our computer doesn't actually know its IP address, then switch. */
  1406. void
  1407. router_new_address_suggestion(const char *suggestion,
  1408. const dir_connection_t *d_conn)
  1409. {
  1410. uint32_t addr, cur = 0;
  1411. struct in_addr in;
  1412. or_options_t *options = get_options();
  1413. /* first, learn what the IP address actually is */
  1414. if (!tor_inet_aton(suggestion, &in)) {
  1415. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1416. escaped(suggestion));
  1417. return;
  1418. }
  1419. addr = ntohl(in.s_addr);
  1420. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1421. if (!server_mode(options)) {
  1422. last_guessed_ip = addr; /* store it in case we need it later */
  1423. return;
  1424. }
  1425. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1426. /* We're all set -- we already know our address. Great. */
  1427. last_guessed_ip = cur; /* store it in case we need it later */
  1428. return;
  1429. }
  1430. if (is_internal_IP(addr, 0)) {
  1431. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1432. return;
  1433. }
  1434. if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
  1435. /* Don't believe anybody who says our IP is their IP. */
  1436. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  1437. "but he's just reporting his own IP address. Ignoring.",
  1438. suggestion);
  1439. return;
  1440. }
  1441. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1442. * us an answer different from what we had the last time we managed to
  1443. * resolve it. */
  1444. if (last_guessed_ip != addr) {
  1445. control_event_server_status(LOG_NOTICE,
  1446. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1447. suggestion);
  1448. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
  1449. d_conn->_base.address);
  1450. ip_address_changed(0);
  1451. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1452. }
  1453. }
  1454. /** We failed to resolve our address locally, but we'd like to build
  1455. * a descriptor and publish / test reachability. If we have a guess
  1456. * about our address based on directory headers, answer it and return
  1457. * 0; else return -1. */
  1458. static int
  1459. router_guess_address_from_dir_headers(uint32_t *guess)
  1460. {
  1461. if (last_guessed_ip) {
  1462. *guess = last_guessed_ip;
  1463. return 0;
  1464. }
  1465. return -1;
  1466. }
  1467. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1468. * string describing the version of Tor and the operating system we're
  1469. * currently running on.
  1470. */
  1471. void
  1472. get_platform_str(char *platform, size_t len)
  1473. {
  1474. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1475. }
  1476. /* XXX need to audit this thing and count fenceposts. maybe
  1477. * refactor so we don't have to keep asking if we're
  1478. * near the end of maxlen?
  1479. */
  1480. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1481. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1482. * with, encode the routerinfo as a signed server descriptor and write the
  1483. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1484. * failure, and the number of bytes used on success.
  1485. */
  1486. int
  1487. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1488. crypto_pk_env_t *ident_key)
  1489. {
  1490. char *onion_pkey; /* Onion key, PEM-encoded. */
  1491. char *identity_pkey; /* Identity key, PEM-encoded. */
  1492. char digest[DIGEST_LEN];
  1493. char published[ISO_TIME_LEN+1];
  1494. char fingerprint[FINGERPRINT_LEN+1];
  1495. char extra_info_digest[HEX_DIGEST_LEN+1];
  1496. size_t onion_pkeylen, identity_pkeylen;
  1497. size_t written;
  1498. int result=0;
  1499. addr_policy_t *tmpe;
  1500. char *family_line;
  1501. or_options_t *options = get_options();
  1502. /* Make sure the identity key matches the one in the routerinfo. */
  1503. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1504. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1505. "match router's public key!");
  1506. return -1;
  1507. }
  1508. /* record our fingerprint, so we can include it in the descriptor */
  1509. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1510. log_err(LD_BUG,"Error computing fingerprint");
  1511. return -1;
  1512. }
  1513. /* PEM-encode the onion key */
  1514. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1515. &onion_pkey,&onion_pkeylen)<0) {
  1516. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1517. return -1;
  1518. }
  1519. /* PEM-encode the identity key key */
  1520. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1521. &identity_pkey,&identity_pkeylen)<0) {
  1522. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1523. tor_free(onion_pkey);
  1524. return -1;
  1525. }
  1526. /* Encode the publication time. */
  1527. format_iso_time(published, router->cache_info.published_on);
  1528. if (router->declared_family && smartlist_len(router->declared_family)) {
  1529. size_t n;
  1530. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1531. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1532. family_line = tor_malloc(n);
  1533. tor_snprintf(family_line, n, "family %s\n", family);
  1534. tor_free(family);
  1535. } else {
  1536. family_line = tor_strdup("");
  1537. }
  1538. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1539. router->cache_info.extra_info_digest, DIGEST_LEN);
  1540. /* Generate the easy portion of the router descriptor. */
  1541. result = tor_snprintf(s, maxlen,
  1542. "router %s %s %d 0 %d\n"
  1543. "platform %s\n"
  1544. "opt protocols Link 1 2 Circuit 1\n"
  1545. "published %s\n"
  1546. "opt fingerprint %s\n"
  1547. "uptime %ld\n"
  1548. "bandwidth %d %d %d\n"
  1549. "opt extra-info-digest %s\n%s"
  1550. "onion-key\n%s"
  1551. "signing-key\n%s"
  1552. "%s%s%s%s",
  1553. router->nickname,
  1554. router->address,
  1555. router->or_port,
  1556. decide_to_advertise_dirport(options, router->dir_port),
  1557. router->platform,
  1558. published,
  1559. fingerprint,
  1560. stats_n_seconds_working,
  1561. (int) router->bandwidthrate,
  1562. (int) router->bandwidthburst,
  1563. (int) router->bandwidthcapacity,
  1564. extra_info_digest,
  1565. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1566. onion_pkey, identity_pkey,
  1567. family_line,
  1568. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1569. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
  1570. options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
  1571. tor_free(family_line);
  1572. tor_free(onion_pkey);
  1573. tor_free(identity_pkey);
  1574. if (result < 0) {
  1575. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1576. return -1;
  1577. }
  1578. /* From now on, we use 'written' to remember the current length of 's'. */
  1579. written = result;
  1580. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1581. const char *ci = options->ContactInfo;
  1582. if (strchr(ci, '\n') || strchr(ci, '\r'))
  1583. ci = escaped(ci);
  1584. result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
  1585. if (result<0) {
  1586. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1587. return -1;
  1588. }
  1589. written += result;
  1590. }
  1591. /* Write the exit policy to the end of 's'. */
  1592. if (dns_seems_to_be_broken() || has_dns_init_failed() ||
  1593. !router->exit_policy || !smartlist_len(router->exit_policy)) {
  1594. /* DNS is screwed up; don't claim to be an exit. */
  1595. strlcat(s+written, "reject *:*\n", maxlen-written);
  1596. written += strlen("reject *:*\n");
  1597. tmpe = NULL;
  1598. } else if (router->exit_policy) {
  1599. int i;
  1600. for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
  1601. tmpe = smartlist_get(router->exit_policy, i);
  1602. result = policy_write_item(s+written, maxlen-written, tmpe, 1);
  1603. if (result < 0) {
  1604. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1605. return -1;
  1606. }
  1607. tor_assert(result == (int)strlen(s+written));
  1608. written += result;
  1609. if (written+2 > maxlen) {
  1610. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1611. return -1;
  1612. }
  1613. s[written++] = '\n';
  1614. }
  1615. }
  1616. if (written+256 > maxlen) { /* Not enough room for signature. */
  1617. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1618. return -1;
  1619. }
  1620. /* Sign the descriptor */
  1621. strlcpy(s+written, "router-signature\n", maxlen-written);
  1622. written += strlen(s+written);
  1623. s[written] = '\0';
  1624. if (router_get_router_hash(s, digest) < 0) {
  1625. return -1;
  1626. }
  1627. note_crypto_pk_op(SIGN_RTR);
  1628. if (router_append_dirobj_signature(s+written,maxlen-written,
  1629. digest,DIGEST_LEN,ident_key)<0) {
  1630. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1631. return -1;
  1632. }
  1633. written += strlen(s+written);
  1634. if (written+2 > maxlen) {
  1635. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1636. return -1;
  1637. }
  1638. /* include a last '\n' */
  1639. s[written] = '\n';
  1640. s[written+1] = 0;
  1641. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1642. {
  1643. char *s_dup;
  1644. const char *cp;
  1645. routerinfo_t *ri_tmp;
  1646. cp = s_dup = tor_strdup(s);
  1647. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1648. if (!ri_tmp) {
  1649. log_err(LD_BUG,
  1650. "We just generated a router descriptor we can't parse.");
  1651. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1652. return -1;
  1653. }
  1654. tor_free(s_dup);
  1655. routerinfo_free(ri_tmp);
  1656. }
  1657. #endif
  1658. return (int)written+1;
  1659. }
  1660. /** Load the contents of <b>filename</b>, find the last line starting with
  1661. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  1662. * the past or more than 1 hour in the future with respect to <b>now</b>,
  1663. * and write the file contents starting with that line to *<b>out</b>.
  1664. * Return 1 for success, 0 if the file does not exist, or -1 if the file
  1665. * does not contain a line matching these criteria or other failure. */
  1666. static int
  1667. load_stats_file(const char *filename, const char *end_line, time_t now,
  1668. char **out)
  1669. {
  1670. int r = -1;
  1671. char *fname = get_datadir_fname(filename);
  1672. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  1673. time_t written;
  1674. switch (file_status(fname)) {
  1675. case FN_FILE:
  1676. /* X022 Find an alternative to reading the whole file to memory. */
  1677. if ((contents = read_file_to_str(fname, 0, NULL))) {
  1678. tmp = strstr(contents, end_line);
  1679. /* Find last block starting with end_line */
  1680. while (tmp) {
  1681. start = tmp;
  1682. tmp = strstr(tmp + 1, end_line);
  1683. }
  1684. if (!start)
  1685. goto notfound;
  1686. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  1687. goto notfound;
  1688. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  1689. if (parse_iso_time(timestr, &written) < 0)
  1690. goto notfound;
  1691. if (written < now - (25*60*60) || written > now + (1*60*60))
  1692. goto notfound;
  1693. *out = tor_strdup(start);
  1694. r = 1;
  1695. }
  1696. notfound:
  1697. tor_free(contents);
  1698. break;
  1699. case FN_NOENT:
  1700. r = 0;
  1701. break;
  1702. case FN_ERROR:
  1703. case FN_DIR:
  1704. default:
  1705. break;
  1706. }
  1707. tor_free(fname);
  1708. return r;
  1709. }
  1710. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1711. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1712. * negative on failure. */
  1713. int
  1714. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1715. crypto_pk_env_t *ident_key)
  1716. {
  1717. or_options_t *options = get_options();
  1718. char identity[HEX_DIGEST_LEN+1];
  1719. char published[ISO_TIME_LEN+1];
  1720. char digest[DIGEST_LEN];
  1721. char *bandwidth_usage;
  1722. int result;
  1723. size_t len;
  1724. static int write_stats_to_extrainfo = 1;
  1725. base16_encode(identity, sizeof(identity),
  1726. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1727. format_iso_time(published, extrainfo->cache_info.published_on);
  1728. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1729. result = tor_snprintf(s, maxlen,
  1730. "extra-info %s %s\n"
  1731. "published %s\n%s",
  1732. extrainfo->nickname, identity,
  1733. published, bandwidth_usage);
  1734. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  1735. char *contents = NULL;
  1736. time_t now = time(NULL);
  1737. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  1738. if (options->DirReqStatistics &&
  1739. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  1740. "dirreq-stats-end", now, &contents) > 0) {
  1741. size_t pos = strlen(s);
  1742. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1743. strlen(contents)) {
  1744. log_warn(LD_DIR, "Could not write dirreq-stats to extra-info "
  1745. "descriptor.");
  1746. s[pos] = '\0';
  1747. }
  1748. tor_free(contents);
  1749. }
  1750. if (options->EntryStatistics &&
  1751. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  1752. "entry-stats-end", now, &contents) > 0) {
  1753. size_t pos = strlen(s);
  1754. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1755. strlen(contents)) {
  1756. log_warn(LD_DIR, "Could not write entry-stats to extra-info "
  1757. "descriptor.");
  1758. s[pos] = '\0';
  1759. }
  1760. tor_free(contents);
  1761. }
  1762. if (options->CellStatistics &&
  1763. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  1764. "cell-stats-end", now, &contents) > 0) {
  1765. size_t pos = strlen(s);
  1766. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1767. strlen(contents)) {
  1768. log_warn(LD_DIR, "Could not write buffer-stats to extra-info "
  1769. "descriptor.");
  1770. s[pos] = '\0';
  1771. }
  1772. tor_free(contents);
  1773. }
  1774. if (options->ExitPortStatistics &&
  1775. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  1776. "exit-stats-end", now, &contents) > 0) {
  1777. size_t pos = strlen(s);
  1778. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1779. strlen(contents)) {
  1780. log_warn(LD_DIR, "Could not write exit-stats to extra-info "
  1781. "descriptor.");
  1782. s[pos] = '\0';
  1783. }
  1784. tor_free(contents);
  1785. }
  1786. }
  1787. tor_free(bandwidth_usage);
  1788. if (result<0)
  1789. return -1;
  1790. if (should_record_bridge_info(options)) {
  1791. char *geoip_summary = extrainfo_get_client_geoip_summary(time(NULL));
  1792. if (geoip_summary) {
  1793. char geoip_start[ISO_TIME_LEN+1];
  1794. format_iso_time(geoip_start, geoip_get_history_start());
  1795. result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
  1796. "geoip-start-time %s\n"
  1797. "geoip-client-origins %s\n",
  1798. geoip_start, geoip_summary);
  1799. control_event_clients_seen(geoip_start, geoip_summary);
  1800. tor_free(geoip_summary);
  1801. if (result<0)
  1802. return -1;
  1803. }
  1804. }
  1805. len = strlen(s);
  1806. strlcat(s+len, "router-signature\n", maxlen-len);
  1807. len += strlen(s+len);
  1808. if (router_get_extrainfo_hash(s, digest)<0)
  1809. return -1;
  1810. if (router_append_dirobj_signature(s+len, maxlen-len, digest, DIGEST_LEN,
  1811. ident_key)<0)
  1812. return -1;
  1813. {
  1814. char *cp, *s_dup;
  1815. extrainfo_t *ei_tmp;
  1816. cp = s_dup = tor_strdup(s);
  1817. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1818. if (!ei_tmp) {
  1819. log_err(LD_BUG,
  1820. "We just generated an extrainfo descriptor we can't parse.");
  1821. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1822. return -1;
  1823. }
  1824. tor_free(s_dup);
  1825. extrainfo_free(ei_tmp);
  1826. }
  1827. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  1828. char *cp, *s_dup;
  1829. extrainfo_t *ei_tmp;
  1830. cp = s_dup = tor_strdup(s);
  1831. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1832. if (!ei_tmp) {
  1833. log_warn(LD_GENERAL,
  1834. "We just generated an extra-info descriptor with "
  1835. "statistics that we can't parse. Not adding statistics to "
  1836. "this or any future extra-info descriptors. Descriptor "
  1837. "was:\n%s", s);
  1838. write_stats_to_extrainfo = 0;
  1839. extrainfo_dump_to_string(s, maxlen, extrainfo, ident_key);
  1840. }
  1841. tor_free(s_dup);
  1842. extrainfo_free(ei_tmp);
  1843. }
  1844. return (int)strlen(s)+1;
  1845. }
  1846. /** Wrapper function for geoip_get_client_history(). It first discards
  1847. * any items in the client history that are too old -- it dumps anything
  1848. * more than 48 hours old, but it only considers whether to dump at most
  1849. * once per 48 hours, so we aren't too precise to an observer (see also
  1850. * r14780).
  1851. */
  1852. char *
  1853. extrainfo_get_client_geoip_summary(time_t now)
  1854. {
  1855. static time_t last_purged_at = 0;
  1856. int geoip_purge_interval =
  1857. (get_options()->DirReqStatistics || get_options()->EntryStatistics) ?
  1858. DIR_ENTRY_RECORD_USAGE_RETAIN_IPS : 48*60*60;
  1859. if (now > last_purged_at+geoip_purge_interval) {
  1860. /* (Note that this also discards items in the client history with
  1861. * action GEOIP_CLIENT_NETWORKSTATUS{_V2}, which doesn't matter
  1862. * because bridge and directory stats are independent. Keep in mind
  1863. * for future extensions, though.) */
  1864. geoip_remove_old_clients(now-geoip_purge_interval);
  1865. last_purged_at = now;
  1866. }
  1867. return geoip_get_client_history_bridge(now, GEOIP_CLIENT_CONNECT);
  1868. }
  1869. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1870. int
  1871. is_legal_nickname(const char *s)
  1872. {
  1873. size_t len;
  1874. tor_assert(s);
  1875. len = strlen(s);
  1876. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1877. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1878. }
  1879. /** Return true iff <b>s</b> is a legally valid server nickname or
  1880. * hex-encoded identity-key digest. */
  1881. int
  1882. is_legal_nickname_or_hexdigest(const char *s)
  1883. {
  1884. if (*s!='$')
  1885. return is_legal_nickname(s);
  1886. else
  1887. return is_legal_hexdigest(s);
  1888. }
  1889. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1890. * digest. */
  1891. int
  1892. is_legal_hexdigest(const char *s)
  1893. {
  1894. size_t len;
  1895. tor_assert(s);
  1896. if (s[0] == '$') s++;
  1897. len = strlen(s);
  1898. if (len > HEX_DIGEST_LEN) {
  1899. if (s[HEX_DIGEST_LEN] == '=' ||
  1900. s[HEX_DIGEST_LEN] == '~') {
  1901. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1902. return 0;
  1903. } else {
  1904. return 0;
  1905. }
  1906. }
  1907. return (len >= HEX_DIGEST_LEN &&
  1908. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1909. }
  1910. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1911. * verbose representation of the identity of <b>router</b>. The format is:
  1912. * A dollar sign.
  1913. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1914. * A "=" if the router is named; a "~" if it is not.
  1915. * The router's nickname.
  1916. **/
  1917. void
  1918. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  1919. {
  1920. buf[0] = '$';
  1921. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1922. DIGEST_LEN);
  1923. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1924. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1925. }
  1926. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1927. * verbose representation of the identity of <b>router</b>. The format is:
  1928. * A dollar sign.
  1929. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1930. * A "=" if the router is named; a "~" if it is not.
  1931. * The router's nickname.
  1932. **/
  1933. void
  1934. routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
  1935. {
  1936. buf[0] = '$';
  1937. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
  1938. DIGEST_LEN);
  1939. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1940. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1941. }
  1942. /** Forget that we have issued any router-related warnings, so that we'll
  1943. * warn again if we see the same errors. */
  1944. void
  1945. router_reset_warnings(void)
  1946. {
  1947. if (warned_nonexistent_family) {
  1948. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1949. smartlist_clear(warned_nonexistent_family);
  1950. }
  1951. }
  1952. /** Given a router purpose, convert it to a string. Don't call this on
  1953. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  1954. * know its string representation. */
  1955. const char *
  1956. router_purpose_to_string(uint8_t p)
  1957. {
  1958. switch (p)
  1959. {
  1960. case ROUTER_PURPOSE_GENERAL: return "general";
  1961. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  1962. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  1963. default:
  1964. tor_assert(0);
  1965. }
  1966. return NULL;
  1967. }
  1968. /** Given a string, convert it to a router purpose. */
  1969. uint8_t
  1970. router_purpose_from_string(const char *s)
  1971. {
  1972. if (!strcmp(s, "general"))
  1973. return ROUTER_PURPOSE_GENERAL;
  1974. else if (!strcmp(s, "bridge"))
  1975. return ROUTER_PURPOSE_BRIDGE;
  1976. else if (!strcmp(s, "controller"))
  1977. return ROUTER_PURPOSE_CONTROLLER;
  1978. else
  1979. return ROUTER_PURPOSE_UNKNOWN;
  1980. }
  1981. /** Release all static resources held in router.c */
  1982. void
  1983. router_free_all(void)
  1984. {
  1985. if (onionkey)
  1986. crypto_free_pk_env(onionkey);
  1987. if (lastonionkey)
  1988. crypto_free_pk_env(lastonionkey);
  1989. if (identitykey)
  1990. crypto_free_pk_env(identitykey);
  1991. if (key_lock)
  1992. tor_mutex_free(key_lock);
  1993. if (desc_routerinfo)
  1994. routerinfo_free(desc_routerinfo);
  1995. if (desc_extrainfo)
  1996. extrainfo_free(desc_extrainfo);
  1997. if (authority_signing_key)
  1998. crypto_free_pk_env(authority_signing_key);
  1999. if (authority_key_certificate)
  2000. authority_cert_free(authority_key_certificate);
  2001. if (legacy_signing_key)
  2002. crypto_free_pk_env(legacy_signing_key);
  2003. if (legacy_key_certificate)
  2004. authority_cert_free(legacy_key_certificate);
  2005. if (warned_nonexistent_family) {
  2006. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2007. smartlist_free(warned_nonexistent_family);
  2008. }
  2009. }