router.c 72 KB

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