router.c 88 KB

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