router.c 63 KB

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