router.c 62 KB

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