router.c 66 KB

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