router.c 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  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-2010, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #define ROUTER_PRIVATE
  7. #include "or.h"
  8. #include "circuitlist.h"
  9. #include "circuituse.h"
  10. #include "config.h"
  11. #include "connection.h"
  12. #include "control.h"
  13. #include "geoip.h"
  14. #include "router.h"
  15. #include "routerlist.h"
  16. /**
  17. * \file router.c
  18. * \brief OR functionality, including key maintenance, generating
  19. * and uploading server descriptors, retrying OR connections.
  20. **/
  21. extern long stats_n_seconds_working;
  22. /************************************************************/
  23. /*****
  24. * Key management: ORs only.
  25. *****/
  26. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  27. */
  28. static tor_mutex_t *key_lock=NULL;
  29. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  30. /** Current private onionskin decryption key: used to decode CREATE cells. */
  31. static crypto_pk_env_t *onionkey=NULL;
  32. /** Previous private onionskin decryption key: used to decode CREATE cells
  33. * generated by clients that have an older version of our descriptor. */
  34. static crypto_pk_env_t *lastonionkey=NULL;
  35. /** Private "identity key": used to sign directory info and TLS
  36. * certificates. Never changes. */
  37. static crypto_pk_env_t *identitykey=NULL;
  38. /** Digest of identitykey. */
  39. static char identitykey_digest[DIGEST_LEN];
  40. /** Signing key used for v3 directory material; only set for authorities. */
  41. static crypto_pk_env_t *authority_signing_key = NULL;
  42. /** Key certificate to authenticate v3 directory material; only set for
  43. * authorities. */
  44. static authority_cert_t *authority_key_certificate = NULL;
  45. /** For emergency V3 authority key migration: An extra signing key that we use
  46. * with our old (obsolete) identity key for a while. */
  47. static crypto_pk_env_t *legacy_signing_key = NULL;
  48. /** For emergency V3 authority key migration: An extra certificate to
  49. * authenticate legacy_signing_key with our obsolete identity key.*/
  50. static authority_cert_t *legacy_key_certificate = NULL;
  51. /* (Note that v3 authorities also have a separate "authority identity key",
  52. * but this key is never actually loaded by the Tor process. Instead, it's
  53. * used by tor-gencert to sign new signing keys and make new key
  54. * certificates. */
  55. /** Replace the current onion key with <b>k</b>. Does not affect
  56. * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
  57. */
  58. static void
  59. set_onion_key(crypto_pk_env_t *k)
  60. {
  61. tor_mutex_acquire(key_lock);
  62. crypto_free_pk_env(onionkey);
  63. onionkey = k;
  64. onionkey_set_at = time(NULL);
  65. tor_mutex_release(key_lock);
  66. mark_my_descriptor_dirty();
  67. }
  68. /** Return the current onion key. Requires that the onion key has been
  69. * loaded or generated. */
  70. crypto_pk_env_t *
  71. get_onion_key(void)
  72. {
  73. tor_assert(onionkey);
  74. return onionkey;
  75. }
  76. /** Store a full copy of the current onion key into *<b>key</b>, and a full
  77. * copy of the most recent onion key into *<b>last</b>.
  78. */
  79. void
  80. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  81. {
  82. tor_assert(key);
  83. tor_assert(last);
  84. tor_mutex_acquire(key_lock);
  85. tor_assert(onionkey);
  86. *key = crypto_pk_copy_full(onionkey);
  87. if (lastonionkey)
  88. *last = crypto_pk_copy_full(lastonionkey);
  89. else
  90. *last = NULL;
  91. tor_mutex_release(key_lock);
  92. }
  93. /** Return the time when the onion key was last set. This is either the time
  94. * when the process launched, or the time of the most recent key rotation since
  95. * the process launched.
  96. */
  97. time_t
  98. get_onion_key_set_at(void)
  99. {
  100. return onionkey_set_at;
  101. }
  102. /** Set the current identity key to k.
  103. */
  104. void
  105. set_identity_key(crypto_pk_env_t *k)
  106. {
  107. crypto_free_pk_env(identitykey);
  108. identitykey = k;
  109. crypto_pk_get_digest(identitykey, identitykey_digest);
  110. }
  111. /** Returns the current identity key; requires that the identity key has been
  112. * set.
  113. */
  114. crypto_pk_env_t *
  115. get_identity_key(void)
  116. {
  117. tor_assert(identitykey);
  118. return identitykey;
  119. }
  120. /** Return true iff the identity key has been set. */
  121. int
  122. identity_key_is_set(void)
  123. {
  124. return identitykey != NULL;
  125. }
  126. /** Return the key certificate for this v3 (voting) authority, or NULL
  127. * if we have no such certificate. */
  128. authority_cert_t *
  129. get_my_v3_authority_cert(void)
  130. {
  131. return authority_key_certificate;
  132. }
  133. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  134. * if we have no such key. */
  135. crypto_pk_env_t *
  136. get_my_v3_authority_signing_key(void)
  137. {
  138. return authority_signing_key;
  139. }
  140. /** If we're an authority, and we're using a legacy authority identity key for
  141. * emergency migration purposes, return the certificate associated with that
  142. * key. */
  143. authority_cert_t *
  144. get_my_v3_legacy_cert(void)
  145. {
  146. return legacy_key_certificate;
  147. }
  148. /** If we're an authority, and we're using a legacy authority identity key for
  149. * emergency migration purposes, return that key. */
  150. crypto_pk_env_t *
  151. get_my_v3_legacy_signing_key(void)
  152. {
  153. return legacy_signing_key;
  154. }
  155. /** Replace the previous onion key with the current onion key, and generate
  156. * a new previous onion key. Immediately after calling this function,
  157. * the OR should:
  158. * - schedule all previous cpuworkers to shut down _after_ processing
  159. * pending work. (This will cause fresh cpuworkers to be generated.)
  160. * - generate and upload a fresh routerinfo.
  161. */
  162. void
  163. rotate_onion_key(void)
  164. {
  165. char *fname, *fname_prev;
  166. crypto_pk_env_t *prkey;
  167. or_state_t *state = get_or_state();
  168. time_t now;
  169. fname = get_datadir_fname2("keys", "secret_onion_key");
  170. fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
  171. if (!(prkey = crypto_new_pk_env())) {
  172. log_err(LD_GENERAL,"Error constructing rotated onion key");
  173. goto error;
  174. }
  175. if (crypto_pk_generate_key(prkey)) {
  176. log_err(LD_BUG,"Error generating onion key");
  177. goto error;
  178. }
  179. if (file_status(fname) == FN_FILE) {
  180. if (replace_file(fname, fname_prev))
  181. goto error;
  182. }
  183. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  184. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  185. goto error;
  186. }
  187. log_info(LD_GENERAL, "Rotating onion key");
  188. tor_mutex_acquire(key_lock);
  189. crypto_free_pk_env(lastonionkey);
  190. lastonionkey = onionkey;
  191. onionkey = prkey;
  192. now = time(NULL);
  193. state->LastRotatedOnionKey = onionkey_set_at = now;
  194. tor_mutex_release(key_lock);
  195. mark_my_descriptor_dirty();
  196. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  197. goto done;
  198. error:
  199. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  200. if (prkey)
  201. crypto_free_pk_env(prkey);
  202. done:
  203. tor_free(fname);
  204. tor_free(fname_prev);
  205. }
  206. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  207. * and <b>generate</b> is true, create a new RSA key and save it in
  208. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  209. * errors at level <b>severity</b>.
  210. */
  211. crypto_pk_env_t *
  212. init_key_from_file(const char *fname, int generate, int severity)
  213. {
  214. crypto_pk_env_t *prkey = NULL;
  215. if (!(prkey = crypto_new_pk_env())) {
  216. log(severity, LD_GENERAL,"Error constructing key");
  217. goto error;
  218. }
  219. switch (file_status(fname)) {
  220. case FN_DIR:
  221. case FN_ERROR:
  222. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  223. goto error;
  224. case FN_NOENT:
  225. if (generate) {
  226. if (!have_lockfile()) {
  227. if (try_locking(get_options(), 0)<0) {
  228. /* Make sure that --list-fingerprint only creates new keys
  229. * if there is no possibility for a deadlock. */
  230. log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
  231. "writing any new keys.", fname);
  232. /*XXXX The 'other process' might make a key in a second or two;
  233. * maybe we should wait for it. */
  234. goto error;
  235. }
  236. }
  237. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  238. fname);
  239. if (crypto_pk_generate_key(prkey)) {
  240. log(severity, LD_GENERAL,"Error generating onion key");
  241. goto error;
  242. }
  243. if (crypto_pk_check_key(prkey) <= 0) {
  244. log(severity, LD_GENERAL,"Generated key seems invalid");
  245. goto error;
  246. }
  247. log_info(LD_GENERAL, "Generated key seems valid");
  248. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  249. log(severity, LD_FS,
  250. "Couldn't write generated key to \"%s\".", fname);
  251. goto error;
  252. }
  253. } else {
  254. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  255. }
  256. return prkey;
  257. case FN_FILE:
  258. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  259. log(severity, LD_GENERAL,"Error loading private key.");
  260. goto error;
  261. }
  262. return prkey;
  263. default:
  264. tor_assert(0);
  265. }
  266. error:
  267. if (prkey)
  268. crypto_free_pk_env(prkey);
  269. return NULL;
  270. }
  271. /** Try to load the vote-signing private key and certificate for being a v3
  272. * directory authority, and make sure they match. If <b>legacy</b>, load a
  273. * legacy key/cert set for emergency key migration; otherwise load the regular
  274. * key/cert set. On success, store them into *<b>key_out</b> and
  275. * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
  276. static int
  277. load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
  278. authority_cert_t **cert_out)
  279. {
  280. int r = -1;
  281. char *fname = NULL, *cert = NULL;
  282. const char *eos = NULL;
  283. crypto_pk_env_t *signing_key = NULL;
  284. authority_cert_t *parsed = NULL;
  285. fname = get_datadir_fname2("keys",
  286. legacy ? "legacy_signing_key" : "authority_signing_key");
  287. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  288. if (!signing_key) {
  289. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  290. goto done;
  291. }
  292. tor_free(fname);
  293. fname = get_datadir_fname2("keys",
  294. legacy ? "legacy_certificate" : "authority_certificate");
  295. cert = read_file_to_str(fname, 0, NULL);
  296. if (!cert) {
  297. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  298. fname);
  299. goto done;
  300. }
  301. parsed = authority_cert_parse_from_string(cert, &eos);
  302. if (!parsed) {
  303. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  304. goto done;
  305. }
  306. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  307. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  308. "certificate");
  309. goto done;
  310. }
  311. crypto_free_pk_env(*key_out);
  312. authority_cert_free(*cert_out);
  313. *key_out = signing_key;
  314. *cert_out = parsed;
  315. r = 0;
  316. signing_key = NULL;
  317. parsed = NULL;
  318. done:
  319. tor_free(fname);
  320. tor_free(cert);
  321. crypto_free_pk_env(signing_key);
  322. authority_cert_free(parsed);
  323. return r;
  324. }
  325. /** Load the v3 (voting) authority signing key and certificate, if they are
  326. * present. Return -1 if anything is missing, mismatched, or unloadable;
  327. * return 0 on success. */
  328. static int
  329. init_v3_authority_keys(void)
  330. {
  331. if (load_authority_keyset(0, &authority_signing_key,
  332. &authority_key_certificate)<0)
  333. return -1;
  334. if (get_options()->V3AuthUseLegacyKey &&
  335. load_authority_keyset(1, &legacy_signing_key,
  336. &legacy_key_certificate)<0)
  337. return -1;
  338. return 0;
  339. }
  340. /** If we're a v3 authority, check whether we have a certificate that's
  341. * likely to expire soon. Warn if we do, but not too often. */
  342. void
  343. v3_authority_check_key_expiry(void)
  344. {
  345. time_t now, expires;
  346. static time_t last_warned = 0;
  347. int badness, time_left, warn_interval;
  348. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  349. return;
  350. now = time(NULL);
  351. expires = authority_key_certificate->expires;
  352. time_left = (int)( expires - now );
  353. if (time_left <= 0) {
  354. badness = LOG_ERR;
  355. warn_interval = 60*60;
  356. } else if (time_left <= 24*60*60) {
  357. badness = LOG_WARN;
  358. warn_interval = 60*60;
  359. } else if (time_left <= 24*60*60*7) {
  360. badness = LOG_WARN;
  361. warn_interval = 24*60*60;
  362. } else if (time_left <= 24*60*60*30) {
  363. badness = LOG_WARN;
  364. warn_interval = 24*60*60*5;
  365. } else {
  366. return;
  367. }
  368. if (last_warned + warn_interval > now)
  369. return;
  370. if (time_left <= 0) {
  371. log(badness, LD_DIR, "Your v3 authority certificate has expired."
  372. " Generate a new one NOW.");
  373. } else if (time_left <= 24*60*60) {
  374. log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
  375. " Generate a new one NOW.", time_left/(60*60));
  376. } else {
  377. log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
  378. " Generate a new one soon.", time_left/(24*60*60));
  379. }
  380. last_warned = now;
  381. }
  382. /** Initialize all OR private keys, and the TLS context, as necessary.
  383. * On OPs, this only initializes the tls context. Return 0 on success,
  384. * or -1 if Tor should die.
  385. */
  386. int
  387. init_keys(void)
  388. {
  389. char *keydir;
  390. char fingerprint[FINGERPRINT_LEN+1];
  391. /*nickname<space>fp\n\0 */
  392. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  393. const char *mydesc;
  394. crypto_pk_env_t *prkey;
  395. char digest[20];
  396. char v3_digest[20];
  397. char *cp;
  398. or_options_t *options = get_options();
  399. authority_type_t type;
  400. time_t now = time(NULL);
  401. trusted_dir_server_t *ds;
  402. int v3_digest_set = 0;
  403. authority_cert_t *cert = NULL;
  404. if (!key_lock)
  405. key_lock = tor_mutex_new();
  406. /* There are a couple of paths that put us here before */
  407. if (crypto_global_init(get_options()->HardwareAccel,
  408. get_options()->AccelName,
  409. get_options()->AccelDir)) {
  410. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  411. return -1;
  412. }
  413. /* OP's don't need persistent keys; just make up an identity and
  414. * initialize the TLS context. */
  415. if (!server_mode(options)) {
  416. if (!(prkey = crypto_new_pk_env()))
  417. return -1;
  418. if (crypto_pk_generate_key(prkey)) {
  419. crypto_free_pk_env(prkey);
  420. return -1;
  421. }
  422. set_identity_key(prkey);
  423. /* Create a TLS context; default the client nickname to "client". */
  424. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
  425. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  426. return -1;
  427. }
  428. return 0;
  429. }
  430. /* Make sure DataDirectory exists, and is private. */
  431. if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
  432. return -1;
  433. }
  434. /* Check the key directory. */
  435. keydir = get_datadir_fname("keys");
  436. if (check_private_dir(keydir, CPD_CREATE)) {
  437. tor_free(keydir);
  438. return -1;
  439. }
  440. tor_free(keydir);
  441. /* 1a. Read v3 directory authority key/cert information. */
  442. memset(v3_digest, 0, sizeof(v3_digest));
  443. if (authdir_mode_v3(options)) {
  444. if (init_v3_authority_keys()<0) {
  445. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  446. "were unable to load our v3 authority keys and certificate! "
  447. "Use tor-gencert to generate them. Dying.");
  448. return -1;
  449. }
  450. cert = get_my_v3_authority_cert();
  451. if (cert) {
  452. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  453. v3_digest);
  454. v3_digest_set = 1;
  455. }
  456. }
  457. /* 1. Read identity key. Make it if none is found. */
  458. keydir = get_datadir_fname2("keys", "secret_id_key");
  459. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  460. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  461. tor_free(keydir);
  462. if (!prkey) return -1;
  463. set_identity_key(prkey);
  464. /* 2. Read onion key. Make it if none is found. */
  465. keydir = get_datadir_fname2("keys", "secret_onion_key");
  466. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  467. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  468. tor_free(keydir);
  469. if (!prkey) return -1;
  470. set_onion_key(prkey);
  471. if (options->command == CMD_RUN_TOR) {
  472. /* only mess with the state file if we're actually running Tor */
  473. or_state_t *state = get_or_state();
  474. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  475. /* We allow for some parsing slop, but we don't want to risk accepting
  476. * values in the distant future. If we did, we might never rotate the
  477. * onion key. */
  478. onionkey_set_at = state->LastRotatedOnionKey;
  479. } else {
  480. /* We have no LastRotatedOnionKey set; either we just created the key
  481. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  482. * start the clock ticking now so that we will eventually rotate it even
  483. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  484. state->LastRotatedOnionKey = onionkey_set_at = now;
  485. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  486. time(NULL)+3600 : 0);
  487. }
  488. }
  489. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  490. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  491. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  492. if (prkey)
  493. lastonionkey = prkey;
  494. }
  495. tor_free(keydir);
  496. /* 3. Initialize link key and TLS context. */
  497. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
  498. log_err(LD_GENERAL,"Error initializing TLS context");
  499. return -1;
  500. }
  501. /* 4. Build our router descriptor. */
  502. /* Must be called after keys are initialized. */
  503. mydesc = router_get_my_descriptor();
  504. if (authdir_mode(options)) {
  505. const char *m = NULL;
  506. routerinfo_t *ri;
  507. /* We need to add our own fingerprint so it gets recognized. */
  508. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  509. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  510. return -1;
  511. }
  512. if (mydesc) {
  513. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
  514. if (!ri) {
  515. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  516. return -1;
  517. }
  518. if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m, "self"))) {
  519. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  520. m?m:"<unknown error>");
  521. return -1;
  522. }
  523. }
  524. }
  525. /* 5. Dump fingerprint to 'fingerprint' */
  526. keydir = get_datadir_fname("fingerprint");
  527. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  528. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 0)<0) {
  529. log_err(LD_GENERAL,"Error computing fingerprint");
  530. tor_free(keydir);
  531. return -1;
  532. }
  533. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  534. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  535. "%s %s\n",options->Nickname, fingerprint) < 0) {
  536. log_err(LD_GENERAL,"Error writing fingerprint line");
  537. tor_free(keydir);
  538. return -1;
  539. }
  540. /* Check whether we need to write the fingerprint file. */
  541. cp = NULL;
  542. if (file_status(keydir) == FN_FILE)
  543. cp = read_file_to_str(keydir, 0, NULL);
  544. if (!cp || strcmp(cp, fingerprint_line)) {
  545. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  546. log_err(LD_FS, "Error writing fingerprint line to file");
  547. tor_free(keydir);
  548. tor_free(cp);
  549. return -1;
  550. }
  551. }
  552. tor_free(cp);
  553. tor_free(keydir);
  554. log(LOG_NOTICE, LD_GENERAL,
  555. "Your Tor server's identity key fingerprint is '%s %s'",
  556. options->Nickname, fingerprint);
  557. if (!authdir_mode(options))
  558. return 0;
  559. /* 6. [authdirserver only] load approved-routers file */
  560. if (dirserv_load_fingerprint_file() < 0) {
  561. log_err(LD_GENERAL,"Error loading fingerprints");
  562. return -1;
  563. }
  564. /* 6b. [authdirserver only] add own key to approved directories. */
  565. crypto_pk_get_digest(get_identity_key(), digest);
  566. type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
  567. (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
  568. (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
  569. (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
  570. (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
  571. ds = router_get_trusteddirserver_by_digest(digest);
  572. if (!ds) {
  573. ds = add_trusted_dir_server(options->Nickname, NULL,
  574. (uint16_t)options->DirPort,
  575. (uint16_t)options->ORPort,
  576. digest,
  577. v3_digest,
  578. type);
  579. if (!ds) {
  580. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  581. "couldn't add ourselves to the authority list. Failing.");
  582. return -1;
  583. }
  584. }
  585. if (ds->type != type) {
  586. log_warn(LD_DIR, "Configured authority type does not match authority "
  587. "type in DirServer list. Adjusting. (%d v %d)",
  588. type, ds->type);
  589. ds->type = type;
  590. }
  591. if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
  592. memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  593. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  594. "DirServer line. Adjusting.");
  595. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  596. }
  597. if (cert) { /* add my own cert to the list of known certs */
  598. log_info(LD_DIR, "adding my own v3 cert");
  599. if (trusted_dirs_load_certs_from_string(
  600. cert->cache_info.signed_descriptor_body, 0, 0)<0) {
  601. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  602. return -1;
  603. }
  604. }
  605. return 0; /* success */
  606. }
  607. /* Keep track of whether we should upload our server descriptor,
  608. * and what type of server we are.
  609. */
  610. /** Whether we can reach our ORPort from the outside. */
  611. static int can_reach_or_port = 0;
  612. /** Whether we can reach our DirPort from the outside. */
  613. static int can_reach_dir_port = 0;
  614. /** Forget what we have learned about our reachability status. */
  615. void
  616. router_reset_reachability(void)
  617. {
  618. can_reach_or_port = can_reach_dir_port = 0;
  619. }
  620. /** Return 1 if ORPort is known reachable; else return 0. */
  621. int
  622. check_whether_orport_reachable(void)
  623. {
  624. or_options_t *options = get_options();
  625. return options->AssumeReachable ||
  626. can_reach_or_port;
  627. }
  628. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  629. int
  630. check_whether_dirport_reachable(void)
  631. {
  632. or_options_t *options = get_options();
  633. return !options->DirPort ||
  634. options->AssumeReachable ||
  635. we_are_hibernating() ||
  636. can_reach_dir_port;
  637. }
  638. /** Look at a variety of factors, and return 0 if we don't want to
  639. * advertise the fact that we have a DirPort open. Else return the
  640. * DirPort we want to advertise.
  641. *
  642. * Log a helpful message if we change our mind about whether to publish
  643. * a DirPort.
  644. */
  645. static int
  646. decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
  647. {
  648. static int advertising=1; /* start out assuming we will advertise */
  649. int new_choice=1;
  650. const char *reason = NULL;
  651. /* Section one: reasons to publish or not publish that aren't
  652. * worth mentioning to the user, either because they're obvious
  653. * or because they're normal behavior. */
  654. if (!dir_port) /* short circuit the rest of the function */
  655. return 0;
  656. if (authdir_mode(options)) /* always publish */
  657. return dir_port;
  658. if (we_are_hibernating())
  659. return 0;
  660. if (!check_whether_dirport_reachable())
  661. return 0;
  662. /* Section two: reasons to publish or not publish that the user
  663. * might find surprising. These are generally config options that
  664. * make us choose not to publish. */
  665. if (accounting_is_enabled(options)) {
  666. /* if we might potentially hibernate */
  667. new_choice = 0;
  668. reason = "AccountingMax enabled";
  669. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  670. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  671. (options->RelayBandwidthRate > 0 &&
  672. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  673. /* if we're advertising a small amount */
  674. new_choice = 0;
  675. reason = "BandwidthRate under 50KB";
  676. }
  677. if (advertising != new_choice) {
  678. if (new_choice == 1) {
  679. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  680. } else {
  681. tor_assert(reason);
  682. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  683. }
  684. advertising = new_choice;
  685. }
  686. return advertising ? dir_port : 0;
  687. }
  688. /** Some time has passed, or we just got new directory information.
  689. * See if we currently believe our ORPort or DirPort to be
  690. * unreachable. If so, launch a new test for it.
  691. *
  692. * For ORPort, we simply try making a circuit that ends at ourselves.
  693. * Success is noticed in onionskin_answer().
  694. *
  695. * For DirPort, we make a connection via Tor to our DirPort and ask
  696. * for our own server descriptor.
  697. * Success is noticed in connection_dir_client_reached_eof().
  698. */
  699. void
  700. consider_testing_reachability(int test_or, int test_dir)
  701. {
  702. routerinfo_t *me = router_get_my_routerinfo();
  703. int orport_reachable = check_whether_orport_reachable();
  704. tor_addr_t addr;
  705. if (!me)
  706. return;
  707. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  708. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  709. !orport_reachable ? "reachability" : "bandwidth",
  710. me->address, me->or_port);
  711. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
  712. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  713. }
  714. tor_addr_from_ipv4h(&addr, me->addr);
  715. if (test_dir && !check_whether_dirport_reachable() &&
  716. !connection_get_by_type_addr_port_purpose(
  717. CONN_TYPE_DIR, &addr, me->dir_port,
  718. DIR_PURPOSE_FETCH_SERVERDESC)) {
  719. /* ask myself, via tor, for my server descriptor. */
  720. directory_initiate_command(me->address, &addr,
  721. me->or_port, me->dir_port,
  722. 0, /* does not matter */
  723. 0, me->cache_info.identity_digest,
  724. DIR_PURPOSE_FETCH_SERVERDESC,
  725. ROUTER_PURPOSE_GENERAL,
  726. 1, "authority.z", NULL, 0, 0);
  727. }
  728. }
  729. /** Annotate that we found our ORPort reachable. */
  730. void
  731. router_orport_found_reachable(void)
  732. {
  733. if (!can_reach_or_port) {
  734. routerinfo_t *me = router_get_my_routerinfo();
  735. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  736. "the outside. Excellent.%s",
  737. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  738. " Publishing server descriptor." : "");
  739. can_reach_or_port = 1;
  740. mark_my_descriptor_dirty();
  741. if (!me) { /* should never happen */
  742. log_warn(LD_BUG, "ORPort found reachable, but I have no routerinfo "
  743. "yet. Failing to inform controller of success.");
  744. return;
  745. }
  746. control_event_server_status(LOG_NOTICE,
  747. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  748. me->address, me->or_port);
  749. }
  750. }
  751. /** Annotate that we found our DirPort reachable. */
  752. void
  753. router_dirport_found_reachable(void)
  754. {
  755. if (!can_reach_dir_port) {
  756. routerinfo_t *me = router_get_my_routerinfo();
  757. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  758. "from the outside. Excellent.");
  759. can_reach_dir_port = 1;
  760. if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
  761. mark_my_descriptor_dirty();
  762. if (!me) { /* should never happen */
  763. log_warn(LD_BUG, "DirPort found reachable, but I have no routerinfo "
  764. "yet. Failing to inform controller of success.");
  765. return;
  766. }
  767. control_event_server_status(LOG_NOTICE,
  768. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  769. me->address, me->dir_port);
  770. }
  771. }
  772. /** We have enough testing circuits open. Send a bunch of "drop"
  773. * cells down each of them, to exercise our bandwidth. */
  774. void
  775. router_perform_bandwidth_test(int num_circs, time_t now)
  776. {
  777. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  778. int max_cells = num_cells < CIRCWINDOW_START ?
  779. num_cells : CIRCWINDOW_START;
  780. int cells_per_circuit = max_cells / num_circs;
  781. origin_circuit_t *circ = NULL;
  782. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  783. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  784. CIRCUIT_PURPOSE_TESTING))) {
  785. /* dump cells_per_circuit drop cells onto this circ */
  786. int i = cells_per_circuit;
  787. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  788. continue;
  789. circ->_base.timestamp_dirty = now;
  790. while (i-- > 0) {
  791. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  792. RELAY_COMMAND_DROP,
  793. NULL, 0, circ->cpath->prev)<0) {
  794. return; /* stop if error */
  795. }
  796. }
  797. }
  798. }
  799. /** Return true iff we believe ourselves to be an authoritative
  800. * directory server.
  801. */
  802. int
  803. authdir_mode(or_options_t *options)
  804. {
  805. return options->AuthoritativeDir != 0;
  806. }
  807. /** Return true iff we believe ourselves to be a v1 authoritative
  808. * directory server.
  809. */
  810. int
  811. authdir_mode_v1(or_options_t *options)
  812. {
  813. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  814. }
  815. /** Return true iff we believe ourselves to be a v2 authoritative
  816. * directory server.
  817. */
  818. int
  819. authdir_mode_v2(or_options_t *options)
  820. {
  821. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  822. }
  823. /** Return true iff we believe ourselves to be a v3 authoritative
  824. * directory server.
  825. */
  826. int
  827. authdir_mode_v3(or_options_t *options)
  828. {
  829. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  830. }
  831. /** Return true iff we are a v1, v2, or v3 directory authority. */
  832. int
  833. authdir_mode_any_main(or_options_t *options)
  834. {
  835. return options->V1AuthoritativeDir ||
  836. options->V2AuthoritativeDir ||
  837. options->V3AuthoritativeDir;
  838. }
  839. /** Return true if we believe ourselves to be any kind of
  840. * authoritative directory beyond just a hidserv authority. */
  841. int
  842. authdir_mode_any_nonhidserv(or_options_t *options)
  843. {
  844. return options->BridgeAuthoritativeDir ||
  845. authdir_mode_any_main(options);
  846. }
  847. /** Return true iff we are an authoritative directory server that is
  848. * authoritative about receiving and serving descriptors of type
  849. * <b>purpose</b> its dirport. Use -1 for "any purpose". */
  850. int
  851. authdir_mode_handles_descs(or_options_t *options, int purpose)
  852. {
  853. if (purpose < 0)
  854. return authdir_mode_any_nonhidserv(options);
  855. else if (purpose == ROUTER_PURPOSE_GENERAL)
  856. return authdir_mode_any_main(options);
  857. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  858. return (options->BridgeAuthoritativeDir);
  859. else
  860. return 0;
  861. }
  862. /** Return true iff we are an authoritative directory server that
  863. * publishes its own network statuses.
  864. */
  865. int
  866. authdir_mode_publishes_statuses(or_options_t *options)
  867. {
  868. if (authdir_mode_bridge(options))
  869. return 0;
  870. return authdir_mode_any_nonhidserv(options);
  871. }
  872. /** Return true iff we are an authoritative directory server that
  873. * tests reachability of the descriptors it learns about.
  874. */
  875. int
  876. authdir_mode_tests_reachability(or_options_t *options)
  877. {
  878. return authdir_mode_handles_descs(options, -1);
  879. }
  880. /** Return true iff we believe ourselves to be a bridge authoritative
  881. * directory server.
  882. */
  883. int
  884. authdir_mode_bridge(or_options_t *options)
  885. {
  886. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  887. }
  888. /** Return true iff we are trying to be a server.
  889. */
  890. int
  891. server_mode(or_options_t *options)
  892. {
  893. if (options->ClientOnly) return 0;
  894. return (options->ORPort != 0 || options->ORListenAddress);
  895. }
  896. /** Remember if we've advertised ourselves to the dirservers. */
  897. static int server_is_advertised=0;
  898. /** Return true iff we have published our descriptor lately.
  899. */
  900. int
  901. advertised_server_mode(void)
  902. {
  903. return server_is_advertised;
  904. }
  905. /**
  906. * Called with a boolean: set whether we have recently published our
  907. * descriptor.
  908. */
  909. static void
  910. set_server_advertised(int s)
  911. {
  912. server_is_advertised = s;
  913. }
  914. /** Return true iff we are trying to be a socks proxy. */
  915. int
  916. proxy_mode(or_options_t *options)
  917. {
  918. return (options->SocksPort != 0 || options->SocksListenAddress ||
  919. options->TransPort != 0 || options->TransListenAddress ||
  920. options->NatdPort != 0 || options->NatdListenAddress ||
  921. options->DNSPort != 0 || options->DNSListenAddress);
  922. }
  923. /** Decide if we're a publishable server. We are a publishable server if:
  924. * - We don't have the ClientOnly option set
  925. * and
  926. * - We have the PublishServerDescriptor option set to non-empty
  927. * and
  928. * - We have ORPort set
  929. * and
  930. * - We believe we are reachable from the outside; or
  931. * - We are an authoritative directory server.
  932. */
  933. static int
  934. decide_if_publishable_server(void)
  935. {
  936. or_options_t *options = get_options();
  937. if (options->ClientOnly)
  938. return 0;
  939. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  940. return 0;
  941. if (!server_mode(options))
  942. return 0;
  943. if (authdir_mode(options))
  944. return 1;
  945. return check_whether_orport_reachable();
  946. }
  947. /** Initiate server descriptor upload as reasonable (if server is publishable,
  948. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  949. *
  950. * We need to rebuild the descriptor if it's dirty even if we're not
  951. * uploading, because our reachability testing *uses* our descriptor to
  952. * determine what IP address and ports to test.
  953. */
  954. void
  955. consider_publishable_server(int force)
  956. {
  957. int rebuilt;
  958. if (!server_mode(get_options()))
  959. return;
  960. rebuilt = router_rebuild_descriptor(0);
  961. if (decide_if_publishable_server()) {
  962. set_server_advertised(1);
  963. if (rebuilt == 0)
  964. router_upload_dir_desc_to_dirservers(force);
  965. } else {
  966. set_server_advertised(0);
  967. }
  968. }
  969. /*
  970. * OR descriptor generation.
  971. */
  972. /** My routerinfo. */
  973. static routerinfo_t *desc_routerinfo = NULL;
  974. /** My extrainfo */
  975. static extrainfo_t *desc_extrainfo = NULL;
  976. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  977. * now. */
  978. static time_t desc_clean_since = 0;
  979. /** Boolean: do we need to regenerate the above? */
  980. static int desc_needs_upload = 0;
  981. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  982. * descriptor successfully yet, try to upload our signed descriptor to
  983. * all the directory servers we know about.
  984. */
  985. void
  986. router_upload_dir_desc_to_dirservers(int force)
  987. {
  988. routerinfo_t *ri;
  989. extrainfo_t *ei;
  990. char *msg;
  991. size_t desc_len, extra_len = 0, total_len;
  992. authority_type_t auth = get_options()->_PublishServerDescriptor;
  993. ri = router_get_my_routerinfo();
  994. if (!ri) {
  995. log_info(LD_GENERAL, "No descriptor; skipping upload");
  996. return;
  997. }
  998. ei = router_get_my_extrainfo();
  999. if (auth == NO_AUTHORITY)
  1000. return;
  1001. if (!force && !desc_needs_upload)
  1002. return;
  1003. desc_needs_upload = 0;
  1004. desc_len = ri->cache_info.signed_descriptor_len;
  1005. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1006. total_len = desc_len + extra_len + 1;
  1007. msg = tor_malloc(total_len);
  1008. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1009. if (ei) {
  1010. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1011. }
  1012. msg[desc_len+extra_len] = 0;
  1013. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1014. (auth & BRIDGE_AUTHORITY) ?
  1015. ROUTER_PURPOSE_BRIDGE :
  1016. ROUTER_PURPOSE_GENERAL,
  1017. auth, msg, desc_len, extra_len);
  1018. tor_free(msg);
  1019. }
  1020. /** OR only: Check whether my exit policy says to allow connection to
  1021. * conn. Return 0 if we accept; non-0 if we reject.
  1022. */
  1023. int
  1024. router_compare_to_my_exit_policy(edge_connection_t *conn)
  1025. {
  1026. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1027. return -1;
  1028. /* make sure it's resolved to something. this way we can't get a
  1029. 'maybe' below. */
  1030. if (tor_addr_is_null(&conn->_base.addr))
  1031. return -1;
  1032. /* XXXX IPv6 */
  1033. if (tor_addr_family(&conn->_base.addr) != AF_INET)
  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. size_t ei_size;
  1146. or_options_t *options = get_options();
  1147. if (desc_clean_since && !force)
  1148. return 0;
  1149. if (router_pick_published_address(options, &addr) < 0) {
  1150. /* Stop trying to rebuild our descriptor every second. We'll
  1151. * learn that it's time to try again when server_has_changed_ip()
  1152. * marks it dirty. */
  1153. desc_clean_since = time(NULL);
  1154. return -1;
  1155. }
  1156. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1157. ri->cache_info.routerlist_index = -1;
  1158. ri->address = tor_dup_ip(addr);
  1159. ri->nickname = tor_strdup(options->Nickname);
  1160. ri->addr = addr;
  1161. ri->or_port = options->ORPort;
  1162. ri->dir_port = options->DirPort;
  1163. ri->cache_info.published_on = time(NULL);
  1164. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1165. * main thread */
  1166. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  1167. if (crypto_pk_get_digest(ri->identity_pkey,
  1168. ri->cache_info.identity_digest)<0) {
  1169. routerinfo_free(ri);
  1170. return -1;
  1171. }
  1172. get_platform_str(platform, sizeof(platform));
  1173. ri->platform = tor_strdup(platform);
  1174. /* compute ri->bandwidthrate as the min of various options */
  1175. ri->bandwidthrate = get_effective_bwrate(options);
  1176. /* and compute ri->bandwidthburst similarly */
  1177. ri->bandwidthburst = get_effective_bwburst(options);
  1178. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1179. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1180. options->ExitPolicyRejectPrivate,
  1181. ri->address, !options->BridgeRelay);
  1182. if (desc_routerinfo) { /* inherit values */
  1183. ri->is_valid = desc_routerinfo->is_valid;
  1184. ri->is_running = desc_routerinfo->is_running;
  1185. ri->is_named = desc_routerinfo->is_named;
  1186. }
  1187. if (authdir_mode(options))
  1188. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1189. if (options->MyFamily) {
  1190. smartlist_t *family;
  1191. if (!warned_nonexistent_family)
  1192. warned_nonexistent_family = smartlist_create();
  1193. family = smartlist_create();
  1194. ri->declared_family = smartlist_create();
  1195. smartlist_split_string(family, options->MyFamily, ",",
  1196. SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1197. SMARTLIST_FOREACH(family, char *, name,
  1198. {
  1199. routerinfo_t *member;
  1200. if (!strcasecmp(name, options->Nickname))
  1201. member = ri;
  1202. else
  1203. member = router_get_by_nickname(name, 1);
  1204. if (!member) {
  1205. int is_legal = is_legal_nickname_or_hexdigest(name);
  1206. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1207. !is_legal_hexdigest(name)) {
  1208. if (is_legal)
  1209. log_warn(LD_CONFIG,
  1210. "I have no descriptor for the router named \"%s\" in my "
  1211. "declared family; I'll use the nickname as is, but "
  1212. "this may confuse clients.", name);
  1213. else
  1214. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1215. "declared family, but that isn't a legal nickname. "
  1216. "Skipping it.", escaped(name));
  1217. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1218. }
  1219. if (is_legal) {
  1220. smartlist_add(ri->declared_family, name);
  1221. name = NULL;
  1222. }
  1223. } else if (router_is_me(member)) {
  1224. /* Don't list ourself in our own family; that's redundant */
  1225. } else {
  1226. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1227. fp[0] = '$';
  1228. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1229. member->cache_info.identity_digest, DIGEST_LEN);
  1230. smartlist_add(ri->declared_family, fp);
  1231. if (smartlist_string_isin(warned_nonexistent_family, name))
  1232. smartlist_string_remove(warned_nonexistent_family, name);
  1233. }
  1234. tor_free(name);
  1235. });
  1236. /* remove duplicates from the list */
  1237. smartlist_sort_strings(ri->declared_family);
  1238. smartlist_uniq_strings(ri->declared_family);
  1239. smartlist_free(family);
  1240. }
  1241. /* Now generate the extrainfo. */
  1242. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1243. ei->cache_info.is_extrainfo = 1;
  1244. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1245. ei->cache_info.published_on = ri->cache_info.published_on;
  1246. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1247. DIGEST_LEN);
  1248. ei_size = options->ExtraInfoStatistics ? MAX_EXTRAINFO_UPLOAD_SIZE : 8192;
  1249. ei->cache_info.signed_descriptor_body = tor_malloc(ei_size);
  1250. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body,
  1251. ei_size, ei, get_identity_key()) < 0) {
  1252. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1253. routerinfo_free(ri);
  1254. extrainfo_free(ei);
  1255. return -1;
  1256. }
  1257. ei->cache_info.signed_descriptor_len =
  1258. strlen(ei->cache_info.signed_descriptor_body);
  1259. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1260. ei->cache_info.signed_descriptor_digest);
  1261. /* Now finish the router descriptor. */
  1262. memcpy(ri->cache_info.extra_info_digest,
  1263. ei->cache_info.signed_descriptor_digest,
  1264. DIGEST_LEN);
  1265. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1266. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1267. ri, get_identity_key())<0) {
  1268. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1269. routerinfo_free(ri);
  1270. extrainfo_free(ei);
  1271. return -1;
  1272. }
  1273. ri->cache_info.signed_descriptor_len =
  1274. strlen(ri->cache_info.signed_descriptor_body);
  1275. ri->purpose =
  1276. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1277. ri->cache_info.send_unencrypted = 1;
  1278. /* Let bridges serve their own descriptors unencrypted, so they can
  1279. * pass reachability testing. (If they want to be harder to notice,
  1280. * they can always leave the DirPort off). */
  1281. if (!options->BridgeRelay)
  1282. ei->cache_info.send_unencrypted = 1;
  1283. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1284. strlen(ri->cache_info.signed_descriptor_body),
  1285. ri->cache_info.signed_descriptor_digest);
  1286. routerinfo_set_country(ri);
  1287. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1288. routerinfo_free(desc_routerinfo);
  1289. desc_routerinfo = ri;
  1290. extrainfo_free(desc_extrainfo);
  1291. desc_extrainfo = ei;
  1292. desc_clean_since = time(NULL);
  1293. desc_needs_upload = 1;
  1294. control_event_my_descriptor_changed();
  1295. return 0;
  1296. }
  1297. /** Mark descriptor out of date if it's older than <b>when</b> */
  1298. void
  1299. mark_my_descriptor_dirty_if_older_than(time_t when)
  1300. {
  1301. if (desc_clean_since < when)
  1302. mark_my_descriptor_dirty();
  1303. }
  1304. /** Call when the current descriptor is out of date. */
  1305. void
  1306. mark_my_descriptor_dirty(void)
  1307. {
  1308. desc_clean_since = 0;
  1309. }
  1310. /** How frequently will we republish our descriptor because of large (factor
  1311. * of 2) shifts in estimated bandwidth? */
  1312. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1313. /** Check whether bandwidth has changed a lot since the last time we announced
  1314. * bandwidth. If so, mark our descriptor dirty. */
  1315. void
  1316. check_descriptor_bandwidth_changed(time_t now)
  1317. {
  1318. static time_t last_changed = 0;
  1319. uint64_t prev, cur;
  1320. if (!desc_routerinfo)
  1321. return;
  1322. prev = desc_routerinfo->bandwidthcapacity;
  1323. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1324. if ((prev != cur && (!prev || !cur)) ||
  1325. cur > prev*2 ||
  1326. cur < prev/2) {
  1327. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1328. log_info(LD_GENERAL,
  1329. "Measured bandwidth has changed; rebuilding descriptor.");
  1330. mark_my_descriptor_dirty();
  1331. last_changed = now;
  1332. }
  1333. }
  1334. }
  1335. /** Note at log level severity that our best guess of address has changed from
  1336. * <b>prev</b> to <b>cur</b>. */
  1337. static void
  1338. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
  1339. const char *source)
  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 (source: %s).",
  1353. addrbuf_prev, addrbuf_cur, source);
  1354. else
  1355. log_notice(LD_GENERAL,
  1356. "Guessed our IP address as %s (source: %s).",
  1357. addrbuf_cur, source);
  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_NOTICE, prev, cur, "resolve");
  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. d_conn->_base.address);
  1431. ip_address_changed(0);
  1432. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1433. }
  1434. }
  1435. /** We failed to resolve our address locally, but we'd like to build
  1436. * a descriptor and publish / test reachability. If we have a guess
  1437. * about our address based on directory headers, answer it and return
  1438. * 0; else return -1. */
  1439. static int
  1440. router_guess_address_from_dir_headers(uint32_t *guess)
  1441. {
  1442. if (last_guessed_ip) {
  1443. *guess = last_guessed_ip;
  1444. return 0;
  1445. }
  1446. return -1;
  1447. }
  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 */
  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%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->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
  1551. options->AllowSingleHopExits ? "opt allow-single-hop-exits\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() || has_dns_init_failed() ||
  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 descriptor */
  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, strlen(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,DIGEST_LEN,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. /** Load the contents of <b>filename</b>, find the last line starting with
  1642. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  1643. * the past or more than 1 hour in the future with respect to <b>now</b>,
  1644. * and write the file contents starting with that line to *<b>out</b>.
  1645. * Return 1 for success, 0 if the file does not exist, or -1 if the file
  1646. * does not contain a line matching these criteria or other failure. */
  1647. static int
  1648. load_stats_file(const char *filename, const char *end_line, time_t now,
  1649. char **out)
  1650. {
  1651. int r = -1;
  1652. char *fname = get_datadir_fname(filename);
  1653. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  1654. time_t written;
  1655. switch (file_status(fname)) {
  1656. case FN_FILE:
  1657. /* X022 Find an alternative to reading the whole file to memory. */
  1658. if ((contents = read_file_to_str(fname, 0, NULL))) {
  1659. tmp = strstr(contents, end_line);
  1660. /* Find last block starting with end_line */
  1661. while (tmp) {
  1662. start = tmp;
  1663. tmp = strstr(tmp + 1, end_line);
  1664. }
  1665. if (!start)
  1666. goto notfound;
  1667. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  1668. goto notfound;
  1669. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  1670. if (parse_iso_time(timestr, &written) < 0)
  1671. goto notfound;
  1672. if (written < now - (25*60*60) || written > now + (1*60*60))
  1673. goto notfound;
  1674. *out = tor_strdup(start);
  1675. r = 1;
  1676. }
  1677. notfound:
  1678. tor_free(contents);
  1679. break;
  1680. case FN_NOENT:
  1681. r = 0;
  1682. break;
  1683. case FN_ERROR:
  1684. case FN_DIR:
  1685. default:
  1686. break;
  1687. }
  1688. tor_free(fname);
  1689. return r;
  1690. }
  1691. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1692. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1693. * negative on failure. */
  1694. int
  1695. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1696. crypto_pk_env_t *ident_key)
  1697. {
  1698. or_options_t *options = get_options();
  1699. char identity[HEX_DIGEST_LEN+1];
  1700. char published[ISO_TIME_LEN+1];
  1701. char digest[DIGEST_LEN];
  1702. char *bandwidth_usage;
  1703. int result;
  1704. size_t len;
  1705. static int write_stats_to_extrainfo = 1;
  1706. time_t now = time(NULL);
  1707. base16_encode(identity, sizeof(identity),
  1708. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1709. format_iso_time(published, extrainfo->cache_info.published_on);
  1710. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1711. result = tor_snprintf(s, maxlen,
  1712. "extra-info %s %s\n"
  1713. "published %s\n%s",
  1714. extrainfo->nickname, identity,
  1715. published, bandwidth_usage);
  1716. tor_free(bandwidth_usage);
  1717. if (result<0)
  1718. return -1;
  1719. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  1720. char *contents = NULL;
  1721. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  1722. if (options->DirReqStatistics &&
  1723. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  1724. "dirreq-stats-end", now, &contents) > 0) {
  1725. size_t pos = strlen(s);
  1726. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1727. strlen(contents)) {
  1728. log_warn(LD_DIR, "Could not write dirreq-stats to extra-info "
  1729. "descriptor.");
  1730. s[pos] = '\0';
  1731. write_stats_to_extrainfo = 0;
  1732. }
  1733. tor_free(contents);
  1734. }
  1735. if (options->EntryStatistics &&
  1736. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  1737. "entry-stats-end", now, &contents) > 0) {
  1738. size_t pos = strlen(s);
  1739. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1740. strlen(contents)) {
  1741. log_warn(LD_DIR, "Could not write entry-stats to extra-info "
  1742. "descriptor.");
  1743. s[pos] = '\0';
  1744. write_stats_to_extrainfo = 0;
  1745. }
  1746. tor_free(contents);
  1747. }
  1748. if (options->CellStatistics &&
  1749. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  1750. "cell-stats-end", now, &contents) > 0) {
  1751. size_t pos = strlen(s);
  1752. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1753. strlen(contents)) {
  1754. log_warn(LD_DIR, "Could not write buffer-stats to extra-info "
  1755. "descriptor.");
  1756. s[pos] = '\0';
  1757. write_stats_to_extrainfo = 0;
  1758. }
  1759. tor_free(contents);
  1760. }
  1761. if (options->ExitPortStatistics &&
  1762. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  1763. "exit-stats-end", now, &contents) > 0) {
  1764. size_t pos = strlen(s);
  1765. if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
  1766. strlen(contents)) {
  1767. log_warn(LD_DIR, "Could not write exit-stats to extra-info "
  1768. "descriptor.");
  1769. s[pos] = '\0';
  1770. write_stats_to_extrainfo = 0;
  1771. }
  1772. tor_free(contents);
  1773. }
  1774. }
  1775. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  1776. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  1777. if (bridge_stats) {
  1778. size_t pos = strlen(s);
  1779. if (strlcpy(s + pos, bridge_stats, maxlen - strlen(s)) !=
  1780. strlen(bridge_stats)) {
  1781. log_warn(LD_DIR, "Could not write bridge-stats to extra-info "
  1782. "descriptor.");
  1783. s[pos] = '\0';
  1784. write_stats_to_extrainfo = 0;
  1785. }
  1786. }
  1787. }
  1788. len = strlen(s);
  1789. strlcat(s+len, "router-signature\n", maxlen-len);
  1790. len += strlen(s+len);
  1791. if (router_get_extrainfo_hash(s, digest)<0)
  1792. return -1;
  1793. if (router_append_dirobj_signature(s+len, maxlen-len, digest, DIGEST_LEN,
  1794. ident_key)<0)
  1795. return -1;
  1796. {
  1797. char *cp, *s_dup;
  1798. extrainfo_t *ei_tmp;
  1799. cp = s_dup = tor_strdup(s);
  1800. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1801. if (!ei_tmp) {
  1802. log_err(LD_BUG,
  1803. "We just generated an extrainfo descriptor we can't parse.");
  1804. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1805. tor_free(s_dup);
  1806. return -1;
  1807. }
  1808. tor_free(s_dup);
  1809. extrainfo_free(ei_tmp);
  1810. }
  1811. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  1812. char *cp, *s_dup;
  1813. extrainfo_t *ei_tmp;
  1814. cp = s_dup = tor_strdup(s);
  1815. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1816. if (!ei_tmp) {
  1817. log_warn(LD_GENERAL,
  1818. "We just generated an extra-info descriptor with "
  1819. "statistics that we can't parse. Not adding statistics to "
  1820. "this or any future extra-info descriptors. Descriptor "
  1821. "was:\n%s", s);
  1822. write_stats_to_extrainfo = 0;
  1823. extrainfo_dump_to_string(s, maxlen, extrainfo, ident_key);
  1824. }
  1825. tor_free(s_dup);
  1826. extrainfo_free(ei_tmp);
  1827. }
  1828. return (int)strlen(s)+1;
  1829. }
  1830. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1831. int
  1832. is_legal_nickname(const char *s)
  1833. {
  1834. size_t len;
  1835. tor_assert(s);
  1836. len = strlen(s);
  1837. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1838. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1839. }
  1840. /** Return true iff <b>s</b> is a legally valid server nickname or
  1841. * hex-encoded identity-key digest. */
  1842. int
  1843. is_legal_nickname_or_hexdigest(const char *s)
  1844. {
  1845. if (*s!='$')
  1846. return is_legal_nickname(s);
  1847. else
  1848. return is_legal_hexdigest(s);
  1849. }
  1850. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1851. * digest. */
  1852. int
  1853. is_legal_hexdigest(const char *s)
  1854. {
  1855. size_t len;
  1856. tor_assert(s);
  1857. if (s[0] == '$') s++;
  1858. len = strlen(s);
  1859. if (len > HEX_DIGEST_LEN) {
  1860. if (s[HEX_DIGEST_LEN] == '=' ||
  1861. s[HEX_DIGEST_LEN] == '~') {
  1862. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1863. return 0;
  1864. } else {
  1865. return 0;
  1866. }
  1867. }
  1868. return (len >= HEX_DIGEST_LEN &&
  1869. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1870. }
  1871. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1872. * verbose representation of the identity of <b>router</b>. The format is:
  1873. * A dollar sign.
  1874. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1875. * A "=" if the router is named; a "~" if it is not.
  1876. * The router's nickname.
  1877. **/
  1878. void
  1879. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  1880. {
  1881. buf[0] = '$';
  1882. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1883. DIGEST_LEN);
  1884. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1885. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1886. }
  1887. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1888. * verbose representation of the identity of <b>router</b>. The format is:
  1889. * A dollar sign.
  1890. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1891. * A "=" if the router is named; a "~" if it is not.
  1892. * The router's nickname.
  1893. **/
  1894. void
  1895. routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
  1896. {
  1897. buf[0] = '$';
  1898. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
  1899. DIGEST_LEN);
  1900. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1901. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1902. }
  1903. /** Forget that we have issued any router-related warnings, so that we'll
  1904. * warn again if we see the same errors. */
  1905. void
  1906. router_reset_warnings(void)
  1907. {
  1908. if (warned_nonexistent_family) {
  1909. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1910. smartlist_clear(warned_nonexistent_family);
  1911. }
  1912. }
  1913. /** Given a router purpose, convert it to a string. Don't call this on
  1914. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  1915. * know its string representation. */
  1916. const char *
  1917. router_purpose_to_string(uint8_t p)
  1918. {
  1919. switch (p)
  1920. {
  1921. case ROUTER_PURPOSE_GENERAL: return "general";
  1922. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  1923. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  1924. default:
  1925. tor_assert(0);
  1926. }
  1927. return NULL;
  1928. }
  1929. /** Given a string, convert it to a router purpose. */
  1930. uint8_t
  1931. router_purpose_from_string(const char *s)
  1932. {
  1933. if (!strcmp(s, "general"))
  1934. return ROUTER_PURPOSE_GENERAL;
  1935. else if (!strcmp(s, "bridge"))
  1936. return ROUTER_PURPOSE_BRIDGE;
  1937. else if (!strcmp(s, "controller"))
  1938. return ROUTER_PURPOSE_CONTROLLER;
  1939. else
  1940. return ROUTER_PURPOSE_UNKNOWN;
  1941. }
  1942. /** Release all static resources held in router.c */
  1943. void
  1944. router_free_all(void)
  1945. {
  1946. crypto_free_pk_env(onionkey);
  1947. crypto_free_pk_env(lastonionkey);
  1948. crypto_free_pk_env(identitykey);
  1949. tor_mutex_free(key_lock);
  1950. routerinfo_free(desc_routerinfo);
  1951. extrainfo_free(desc_extrainfo);
  1952. crypto_free_pk_env(authority_signing_key);
  1953. authority_cert_free(authority_key_certificate);
  1954. crypto_free_pk_env(legacy_signing_key);
  1955. authority_cert_free(legacy_key_certificate);
  1956. if (warned_nonexistent_family) {
  1957. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1958. smartlist_free(warned_nonexistent_family);
  1959. }
  1960. }