router.c 91 KB

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