router.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #define ROUTER_PRIVATE
  7. #include "core/or/or.h"
  8. #include "core/or/circuitbuild.h"
  9. #include "core/or/circuitlist.h"
  10. #include "core/or/circuituse.h"
  11. #include "app/config/config.h"
  12. #include "core/mainloop/connection.h"
  13. #include "feature/control/control.h"
  14. #include "lib/crypt_ops/crypto_rand.h"
  15. #include "lib/crypt_ops/crypto_util.h"
  16. #include "lib/crypt_ops/crypto_curve25519.h"
  17. #include "feature/dircommon/directory.h"
  18. #include "feature/dirclient/dirclient.h"
  19. #include "feature/dircache/dirserv.h"
  20. #include "feature/dirauth/process_descs.h"
  21. #include "feature/relay/dns.h"
  22. #include "feature/stats/geoip.h"
  23. #include "feature/hibernate/hibernate.h"
  24. #include "app/main/main.h"
  25. #include "core/mainloop/mainloop.h"
  26. #include "feature/nodelist/networkstatus.h"
  27. #include "feature/nodelist/nodelist.h"
  28. #include "core/or/policies.h"
  29. #include "core/or/protover.h"
  30. #include "core/or/relay.h"
  31. #include "feature/keymgt/loadkey.h"
  32. #include "feature/stats/rephist.h"
  33. #include "feature/relay/router.h"
  34. #include "feature/relay/routerkeys.h"
  35. #include "feature/relay/routermode.h"
  36. #include "feature/relay/selftest.h"
  37. #include "feature/nodelist/authcert.h"
  38. #include "feature/nodelist/dirlist.h"
  39. #include "feature/nodelist/routerlist.h"
  40. #include "feature/nodelist/routerparse.h"
  41. #include "app/config/statefile.h"
  42. #include "feature/nodelist/torcert.h"
  43. #include "feature/client/transports.h"
  44. #include "feature/nodelist/routerset.h"
  45. #include "feature/dirauth/authmode.h"
  46. #include "feature/nodelist/authority_cert_st.h"
  47. #include "core/or/crypt_path_st.h"
  48. #include "feature/dircommon/dir_connection_st.h"
  49. #include "feature/dirclient/dir_server_st.h"
  50. #include "core/or/extend_info_st.h"
  51. #include "feature/nodelist/extrainfo_st.h"
  52. #include "feature/nodelist/node_st.h"
  53. #include "core/or/origin_circuit_st.h"
  54. #include "app/config/or_state_st.h"
  55. #include "core/or/port_cfg_st.h"
  56. #include "feature/nodelist/routerinfo_st.h"
  57. #include "lib/osinfo/uname.h"
  58. #include "lib/tls/tortls.h"
  59. #include "lib/encoding/confline.h"
  60. #include "lib/crypt_ops/crypto_format.h"
  61. #include "lib/crypt_ops/crypto_init.h"
  62. /**
  63. * \file router.c
  64. * \brief Miscellaneous relay functionality, including RSA key maintenance,
  65. * generating and uploading server descriptors, picking an address to
  66. * advertise, and so on.
  67. *
  68. * This module handles the job of deciding whether we are a Tor relay, and if
  69. * so what kind. (Mostly through functions like server_mode() that inspect an
  70. * or_options_t, but in some cases based on our own capabilities, such as when
  71. * we are deciding whether to be a directory cache in
  72. * router_has_bandwidth_to_be_dirserver().)
  73. *
  74. * Also in this module are the functions to generate our own routerinfo_t and
  75. * extrainfo_t, and to encode those to signed strings for upload to the
  76. * directory authorities.
  77. *
  78. * This module also handles key maintenance for RSA and Curve25519-ntor keys,
  79. * and for our TLS context. (These functions should eventually move to
  80. * routerkeys.c along with the code that handles Ed25519 keys now.)
  81. **/
  82. /************************************************************/
  83. /*****
  84. * Key management: ORs only.
  85. *****/
  86. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  87. */
  88. static tor_mutex_t *key_lock=NULL;
  89. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  90. /** Current private onionskin decryption key: used to decode CREATE cells. */
  91. static crypto_pk_t *onionkey=NULL;
  92. /** Previous private onionskin decryption key: used to decode CREATE cells
  93. * generated by clients that have an older version of our descriptor. */
  94. static crypto_pk_t *lastonionkey=NULL;
  95. /** Current private ntor secret key: used to perform the ntor handshake. */
  96. static curve25519_keypair_t curve25519_onion_key;
  97. /** Previous private ntor secret key: used to perform the ntor handshake
  98. * with clients that have an older version of our descriptor. */
  99. static curve25519_keypair_t last_curve25519_onion_key;
  100. /** Private server "identity key": used to sign directory info and TLS
  101. * certificates. Never changes. */
  102. static crypto_pk_t *server_identitykey=NULL;
  103. /** Digest of server_identitykey. */
  104. static char server_identitykey_digest[DIGEST_LEN];
  105. /** Private client "identity key": used to sign bridges' and clients'
  106. * outbound TLS certificates. Regenerated on startup and on IP address
  107. * change. */
  108. static crypto_pk_t *client_identitykey=NULL;
  109. /** Signing key used for v3 directory material; only set for authorities. */
  110. static crypto_pk_t *authority_signing_key = NULL;
  111. /** Key certificate to authenticate v3 directory material; only set for
  112. * authorities. */
  113. static authority_cert_t *authority_key_certificate = NULL;
  114. /** For emergency V3 authority key migration: An extra signing key that we use
  115. * with our old (obsolete) identity key for a while. */
  116. static crypto_pk_t *legacy_signing_key = NULL;
  117. /** For emergency V3 authority key migration: An extra certificate to
  118. * authenticate legacy_signing_key with our obsolete identity key.*/
  119. static authority_cert_t *legacy_key_certificate = NULL;
  120. /* (Note that v3 authorities also have a separate "authority identity key",
  121. * but this key is never actually loaded by the Tor process. Instead, it's
  122. * used by tor-gencert to sign new signing keys and make new key
  123. * certificates. */
  124. const char *format_node_description(char *buf,
  125. const char *id_digest,
  126. int is_named,
  127. const char *nickname,
  128. const tor_addr_t *addr,
  129. uint32_t addr32h);
  130. /** Return a readonly string with human readable description
  131. * of <b>err</b>.
  132. */
  133. const char *
  134. routerinfo_err_to_string(int err)
  135. {
  136. switch (err) {
  137. case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
  138. return "No known exit address yet";
  139. case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
  140. return "Cannot parse descriptor";
  141. case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
  142. return "Not running in server mode";
  143. case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
  144. return "Key digest failed";
  145. case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
  146. return "Cannot generate descriptor";
  147. case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
  148. return "Descriptor still rebuilding - not ready yet";
  149. }
  150. log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
  151. tor_assert_unreached();
  152. return "Unknown error";
  153. }
  154. /** Return true if we expect given error to be transient.
  155. * Return false otherwise.
  156. */
  157. int
  158. routerinfo_err_is_transient(int err)
  159. {
  160. /**
  161. * For simplicity, we consider all errors other than
  162. * "not a server" transient - see discussion on
  163. * https://trac.torproject.org/projects/tor/ticket/27034
  164. */
  165. return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
  166. }
  167. /** Replace the current onion key with <b>k</b>. Does not affect
  168. * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
  169. */
  170. static void
  171. set_onion_key(crypto_pk_t *k)
  172. {
  173. if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
  174. /* k is already our onion key; free it and return */
  175. crypto_pk_free(k);
  176. return;
  177. }
  178. tor_mutex_acquire(key_lock);
  179. crypto_pk_free(onionkey);
  180. onionkey = k;
  181. tor_mutex_release(key_lock);
  182. mark_my_descriptor_dirty("set onion key");
  183. }
  184. /** Return the current onion key. Requires that the onion key has been
  185. * loaded or generated. */
  186. crypto_pk_t *
  187. get_onion_key(void)
  188. {
  189. tor_assert(onionkey);
  190. return onionkey;
  191. }
  192. /** Store a full copy of the current onion key into *<b>key</b>, and a full
  193. * copy of the most recent onion key into *<b>last</b>. Store NULL into
  194. * a pointer if the corresponding key does not exist.
  195. */
  196. void
  197. dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
  198. {
  199. tor_assert(key);
  200. tor_assert(last);
  201. tor_mutex_acquire(key_lock);
  202. if (onionkey)
  203. *key = crypto_pk_copy_full(onionkey);
  204. else
  205. *key = NULL;
  206. if (lastonionkey)
  207. *last = crypto_pk_copy_full(lastonionkey);
  208. else
  209. *last = NULL;
  210. tor_mutex_release(key_lock);
  211. }
  212. /** Expire our old set of onion keys. This is done by setting
  213. * last_curve25519_onion_key and lastonionkey to all zero's and NULL
  214. * respectively.
  215. *
  216. * This function does not perform any grace period checks for the old onion
  217. * keys.
  218. */
  219. void
  220. expire_old_onion_keys(void)
  221. {
  222. char *fname = NULL;
  223. tor_mutex_acquire(key_lock);
  224. /* Free lastonionkey and set it to NULL. */
  225. if (lastonionkey) {
  226. crypto_pk_free(lastonionkey);
  227. lastonionkey = NULL;
  228. }
  229. /* We zero out the keypair. See the tor_mem_is_zero() check made in
  230. * construct_ntor_key_map() below. */
  231. memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
  232. tor_mutex_release(key_lock);
  233. fname = get_keydir_fname("secret_onion_key.old");
  234. if (file_status(fname) == FN_FILE) {
  235. if (tor_unlink(fname) != 0) {
  236. log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
  237. fname, strerror(errno));
  238. }
  239. }
  240. tor_free(fname);
  241. fname = get_keydir_fname("secret_onion_key_ntor.old");
  242. if (file_status(fname) == FN_FILE) {
  243. if (tor_unlink(fname) != 0) {
  244. log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
  245. fname, strerror(errno));
  246. }
  247. }
  248. tor_free(fname);
  249. }
  250. /** Return the current secret onion key for the ntor handshake. Must only
  251. * be called from the main thread. */
  252. static const curve25519_keypair_t *
  253. get_current_curve25519_keypair(void)
  254. {
  255. return &curve25519_onion_key;
  256. }
  257. /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
  258. * handshake. Must only be called from the main thread. */
  259. di_digest256_map_t *
  260. construct_ntor_key_map(void)
  261. {
  262. di_digest256_map_t *m = NULL;
  263. if (!tor_mem_is_zero((const char*)
  264. curve25519_onion_key.pubkey.public_key,
  265. CURVE25519_PUBKEY_LEN)) {
  266. dimap_add_entry(&m,
  267. curve25519_onion_key.pubkey.public_key,
  268. tor_memdup(&curve25519_onion_key,
  269. sizeof(curve25519_keypair_t)));
  270. }
  271. if (!tor_mem_is_zero((const char*)
  272. last_curve25519_onion_key.pubkey.public_key,
  273. CURVE25519_PUBKEY_LEN)) {
  274. dimap_add_entry(&m,
  275. last_curve25519_onion_key.pubkey.public_key,
  276. tor_memdup(&last_curve25519_onion_key,
  277. sizeof(curve25519_keypair_t)));
  278. }
  279. return m;
  280. }
  281. /** Helper used to deallocate a di_digest256_map_t returned by
  282. * construct_ntor_key_map. */
  283. static void
  284. ntor_key_map_free_helper(void *arg)
  285. {
  286. curve25519_keypair_t *k = arg;
  287. memwipe(k, 0, sizeof(*k));
  288. tor_free(k);
  289. }
  290. /** Release all storage from a keymap returned by construct_ntor_key_map. */
  291. void
  292. ntor_key_map_free_(di_digest256_map_t *map)
  293. {
  294. if (!map)
  295. return;
  296. dimap_free(map, ntor_key_map_free_helper);
  297. }
  298. /** Return the time when the onion key was last set. This is either the time
  299. * when the process launched, or the time of the most recent key rotation since
  300. * the process launched.
  301. */
  302. time_t
  303. get_onion_key_set_at(void)
  304. {
  305. return onionkey_set_at;
  306. }
  307. /** Set the current server identity key to <b>k</b>.
  308. */
  309. void
  310. set_server_identity_key(crypto_pk_t *k)
  311. {
  312. crypto_pk_free(server_identitykey);
  313. server_identitykey = k;
  314. if (crypto_pk_get_digest(server_identitykey,
  315. server_identitykey_digest) < 0) {
  316. log_err(LD_BUG, "Couldn't compute our own identity key digest.");
  317. tor_assert(0);
  318. }
  319. }
  320. /** Make sure that we have set up our identity keys to match or not match as
  321. * appropriate, and die with an assertion if we have not. */
  322. static void
  323. assert_identity_keys_ok(void)
  324. {
  325. if (1)
  326. return;
  327. tor_assert(client_identitykey);
  328. if (public_server_mode(get_options())) {
  329. /* assert that we have set the client and server keys to be equal */
  330. tor_assert(server_identitykey);
  331. tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
  332. } else {
  333. /* assert that we have set the client and server keys to be unequal */
  334. if (server_identitykey)
  335. tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
  336. }
  337. }
  338. /** Returns the current server identity key; requires that the key has
  339. * been set, and that we are running as a Tor server.
  340. */
  341. crypto_pk_t *
  342. get_server_identity_key(void)
  343. {
  344. tor_assert(server_identitykey);
  345. tor_assert(server_mode(get_options()));
  346. assert_identity_keys_ok();
  347. return server_identitykey;
  348. }
  349. /** Return true iff we are a server and the server identity key
  350. * has been set. */
  351. int
  352. server_identity_key_is_set(void)
  353. {
  354. return server_mode(get_options()) && server_identitykey != NULL;
  355. }
  356. /** Set the current client identity key to <b>k</b>.
  357. */
  358. void
  359. set_client_identity_key(crypto_pk_t *k)
  360. {
  361. crypto_pk_free(client_identitykey);
  362. client_identitykey = k;
  363. }
  364. /** Returns the current client identity key for use on outgoing TLS
  365. * connections; requires that the key has been set.
  366. */
  367. crypto_pk_t *
  368. get_tlsclient_identity_key(void)
  369. {
  370. tor_assert(client_identitykey);
  371. assert_identity_keys_ok();
  372. return client_identitykey;
  373. }
  374. /** Return true iff the client identity key has been set. */
  375. int
  376. client_identity_key_is_set(void)
  377. {
  378. return client_identitykey != NULL;
  379. }
  380. /** Return the key certificate for this v3 (voting) authority, or NULL
  381. * if we have no such certificate. */
  382. MOCK_IMPL(authority_cert_t *,
  383. get_my_v3_authority_cert, (void))
  384. {
  385. return authority_key_certificate;
  386. }
  387. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  388. * if we have no such key. */
  389. crypto_pk_t *
  390. get_my_v3_authority_signing_key(void)
  391. {
  392. return authority_signing_key;
  393. }
  394. /** If we're an authority, and we're using a legacy authority identity key for
  395. * emergency migration purposes, return the certificate associated with that
  396. * key. */
  397. authority_cert_t *
  398. get_my_v3_legacy_cert(void)
  399. {
  400. return legacy_key_certificate;
  401. }
  402. /** If we're an authority, and we're using a legacy authority identity key for
  403. * emergency migration purposes, return that key. */
  404. crypto_pk_t *
  405. get_my_v3_legacy_signing_key(void)
  406. {
  407. return legacy_signing_key;
  408. }
  409. /** Replace the previous onion key with the current onion key, and generate
  410. * a new previous onion key. Immediately after calling this function,
  411. * the OR should:
  412. * - schedule all previous cpuworkers to shut down _after_ processing
  413. * pending work. (This will cause fresh cpuworkers to be generated.)
  414. * - generate and upload a fresh routerinfo.
  415. */
  416. void
  417. rotate_onion_key(void)
  418. {
  419. char *fname, *fname_prev;
  420. crypto_pk_t *prkey = NULL;
  421. or_state_t *state = get_or_state();
  422. curve25519_keypair_t new_curve25519_keypair;
  423. time_t now;
  424. fname = get_keydir_fname("secret_onion_key");
  425. fname_prev = get_keydir_fname("secret_onion_key.old");
  426. /* There isn't much point replacing an old key with an empty file */
  427. if (file_status(fname) == FN_FILE) {
  428. if (replace_file(fname, fname_prev))
  429. goto error;
  430. }
  431. if (!(prkey = crypto_pk_new())) {
  432. log_err(LD_GENERAL,"Error constructing rotated onion key");
  433. goto error;
  434. }
  435. if (crypto_pk_generate_key(prkey)) {
  436. log_err(LD_BUG,"Error generating onion key");
  437. goto error;
  438. }
  439. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  440. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  441. goto error;
  442. }
  443. tor_free(fname);
  444. tor_free(fname_prev);
  445. fname = get_keydir_fname("secret_onion_key_ntor");
  446. fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
  447. if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
  448. goto error;
  449. /* There isn't much point replacing an old key with an empty file */
  450. if (file_status(fname) == FN_FILE) {
  451. if (replace_file(fname, fname_prev))
  452. goto error;
  453. }
  454. if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
  455. "onion") < 0) {
  456. log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
  457. goto error;
  458. }
  459. log_info(LD_GENERAL, "Rotating onion key");
  460. tor_mutex_acquire(key_lock);
  461. crypto_pk_free(lastonionkey);
  462. lastonionkey = onionkey;
  463. onionkey = prkey;
  464. memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
  465. sizeof(curve25519_keypair_t));
  466. memcpy(&curve25519_onion_key, &new_curve25519_keypair,
  467. sizeof(curve25519_keypair_t));
  468. now = time(NULL);
  469. state->LastRotatedOnionKey = onionkey_set_at = now;
  470. tor_mutex_release(key_lock);
  471. mark_my_descriptor_dirty("rotated onion key");
  472. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  473. goto done;
  474. error:
  475. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  476. if (prkey)
  477. crypto_pk_free(prkey);
  478. done:
  479. memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
  480. tor_free(fname);
  481. tor_free(fname_prev);
  482. }
  483. /** Log greeting message that points to new relay lifecycle document the
  484. * first time this function has been called.
  485. */
  486. static void
  487. log_new_relay_greeting(void)
  488. {
  489. static int already_logged = 0;
  490. if (already_logged)
  491. return;
  492. tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
  493. "Thanks for helping the Tor network! If you wish to know "
  494. "what will happen in the upcoming weeks regarding its usage, "
  495. "have a look at https://blog.torproject.org/blog/lifecycle-of"
  496. "-a-new-relay");
  497. already_logged = 1;
  498. }
  499. /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
  500. * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
  501. * is true, create a new keypair and write it into the file. If there are
  502. * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
  503. * in their ASCII wrapper. */
  504. static int
  505. init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
  506. const char *fname,
  507. int generate,
  508. int severity,
  509. const char *tag)
  510. {
  511. switch (file_status(fname)) {
  512. case FN_DIR:
  513. case FN_ERROR:
  514. tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  515. goto error;
  516. /* treat empty key files as if the file doesn't exist, and, if generate
  517. * is set, replace the empty file in curve25519_keypair_write_to_file() */
  518. case FN_NOENT:
  519. case FN_EMPTY:
  520. if (generate) {
  521. if (!have_lockfile()) {
  522. if (try_locking(get_options(), 0)<0) {
  523. /* Make sure that --list-fingerprint only creates new keys
  524. * if there is no possibility for a deadlock. */
  525. tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
  526. "Not writing any new keys.", fname);
  527. /*XXXX The 'other process' might make a key in a second or two;
  528. * maybe we should wait for it. */
  529. goto error;
  530. }
  531. }
  532. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  533. fname);
  534. if (curve25519_keypair_generate(keys_out, 1) < 0)
  535. goto error;
  536. if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
  537. tor_log(severity, LD_FS,
  538. "Couldn't write generated key to \"%s\".", fname);
  539. memwipe(keys_out, 0, sizeof(*keys_out));
  540. goto error;
  541. }
  542. } else {
  543. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  544. }
  545. return 0;
  546. case FN_FILE:
  547. {
  548. char *tag_in=NULL;
  549. if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
  550. tor_log(severity, LD_GENERAL,"Error loading private key.");
  551. tor_free(tag_in);
  552. goto error;
  553. }
  554. if (!tag_in || strcmp(tag_in, tag)) {
  555. tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
  556. escaped(tag_in));
  557. tor_free(tag_in);
  558. goto error;
  559. }
  560. tor_free(tag_in);
  561. return 0;
  562. }
  563. default:
  564. tor_assert(0);
  565. }
  566. error:
  567. return -1;
  568. }
  569. /** Try to load the vote-signing private key and certificate for being a v3
  570. * directory authority, and make sure they match. If <b>legacy</b>, load a
  571. * legacy key/cert set for emergency key migration; otherwise load the regular
  572. * key/cert set. On success, store them into *<b>key_out</b> and
  573. * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
  574. static int
  575. load_authority_keyset(int legacy, crypto_pk_t **key_out,
  576. authority_cert_t **cert_out)
  577. {
  578. int r = -1;
  579. char *fname = NULL, *cert = NULL;
  580. const char *eos = NULL;
  581. crypto_pk_t *signing_key = NULL;
  582. authority_cert_t *parsed = NULL;
  583. fname = get_keydir_fname(
  584. legacy ? "legacy_signing_key" : "authority_signing_key");
  585. signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
  586. if (!signing_key) {
  587. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  588. goto done;
  589. }
  590. tor_free(fname);
  591. fname = get_keydir_fname(
  592. legacy ? "legacy_certificate" : "authority_certificate");
  593. cert = read_file_to_str(fname, 0, NULL);
  594. if (!cert) {
  595. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  596. fname);
  597. goto done;
  598. }
  599. parsed = authority_cert_parse_from_string(cert, &eos);
  600. if (!parsed) {
  601. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  602. goto done;
  603. }
  604. if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
  605. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  606. "certificate");
  607. goto done;
  608. }
  609. crypto_pk_free(*key_out);
  610. authority_cert_free(*cert_out);
  611. *key_out = signing_key;
  612. *cert_out = parsed;
  613. r = 0;
  614. signing_key = NULL;
  615. parsed = NULL;
  616. done:
  617. tor_free(fname);
  618. tor_free(cert);
  619. crypto_pk_free(signing_key);
  620. authority_cert_free(parsed);
  621. return r;
  622. }
  623. /** Load the v3 (voting) authority signing key and certificate, if they are
  624. * present. Return -1 if anything is missing, mismatched, or unloadable;
  625. * return 0 on success. */
  626. static int
  627. init_v3_authority_keys(void)
  628. {
  629. if (load_authority_keyset(0, &authority_signing_key,
  630. &authority_key_certificate)<0)
  631. return -1;
  632. if (get_options()->V3AuthUseLegacyKey &&
  633. load_authority_keyset(1, &legacy_signing_key,
  634. &legacy_key_certificate)<0)
  635. return -1;
  636. return 0;
  637. }
  638. /** If we're a v3 authority, check whether we have a certificate that's
  639. * likely to expire soon. Warn if we do, but not too often. */
  640. void
  641. v3_authority_check_key_expiry(void)
  642. {
  643. time_t now, expires;
  644. static time_t last_warned = 0;
  645. int badness, time_left, warn_interval;
  646. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  647. return;
  648. now = time(NULL);
  649. expires = authority_key_certificate->expires;
  650. time_left = (int)( expires - now );
  651. if (time_left <= 0) {
  652. badness = LOG_ERR;
  653. warn_interval = 60*60;
  654. } else if (time_left <= 24*60*60) {
  655. badness = LOG_WARN;
  656. warn_interval = 60*60;
  657. } else if (time_left <= 24*60*60*7) {
  658. badness = LOG_WARN;
  659. warn_interval = 24*60*60;
  660. } else if (time_left <= 24*60*60*30) {
  661. badness = LOG_WARN;
  662. warn_interval = 24*60*60*5;
  663. } else {
  664. return;
  665. }
  666. if (last_warned + warn_interval > now)
  667. return;
  668. if (time_left <= 0) {
  669. tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
  670. " Generate a new one NOW.");
  671. } else if (time_left <= 24*60*60) {
  672. tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
  673. "hours; Generate a new one NOW.", time_left/(60*60));
  674. } else {
  675. tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
  676. "days; Generate a new one soon.", time_left/(24*60*60));
  677. }
  678. last_warned = now;
  679. }
  680. /** Get the lifetime of an onion key in days. This value is defined by the
  681. * network consesus parameter "onion-key-rotation-days". Always returns a value
  682. * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
  683. * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
  684. */
  685. static int
  686. get_onion_key_rotation_days_(void)
  687. {
  688. return networkstatus_get_param(NULL,
  689. "onion-key-rotation-days",
  690. DEFAULT_ONION_KEY_LIFETIME_DAYS,
  691. MIN_ONION_KEY_LIFETIME_DAYS,
  692. MAX_ONION_KEY_LIFETIME_DAYS);
  693. }
  694. /** Get the current lifetime of an onion key in seconds. This value is defined
  695. * by the network consesus parameter "onion-key-rotation-days", but the value
  696. * is converted to seconds.
  697. */
  698. int
  699. get_onion_key_lifetime(void)
  700. {
  701. return get_onion_key_rotation_days_()*24*60*60;
  702. }
  703. /** Get the grace period of an onion key in seconds. This value is defined by
  704. * the network consesus parameter "onion-key-grace-period-days", but the value
  705. * is converted to seconds.
  706. */
  707. int
  708. get_onion_key_grace_period(void)
  709. {
  710. int grace_period;
  711. grace_period = networkstatus_get_param(NULL,
  712. "onion-key-grace-period-days",
  713. DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
  714. MIN_ONION_KEY_GRACE_PERIOD_DAYS,
  715. get_onion_key_rotation_days_());
  716. return grace_period*24*60*60;
  717. }
  718. /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
  719. * on success, and -1 on failure. */
  720. int
  721. router_initialize_tls_context(void)
  722. {
  723. unsigned int flags = 0;
  724. const or_options_t *options = get_options();
  725. int lifetime = options->SSLKeyLifetime;
  726. if (public_server_mode(options))
  727. flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
  728. if (!lifetime) { /* we should guess a good ssl cert lifetime */
  729. /* choose between 5 and 365 days, and round to the day */
  730. unsigned int five_days = 5*24*3600;
  731. unsigned int one_year = 365*24*3600;
  732. lifetime = crypto_rand_int_range(five_days, one_year);
  733. lifetime -= lifetime % (24*3600);
  734. if (crypto_rand_int(2)) {
  735. /* Half the time we expire at midnight, and half the time we expire
  736. * one second before midnight. (Some CAs wobble their expiry times a
  737. * bit in practice, perhaps to reduce collision attacks; see ticket
  738. * 8443 for details about observed certs in the wild.) */
  739. lifetime--;
  740. }
  741. }
  742. /* It's ok to pass lifetime in as an unsigned int, since
  743. * config_parse_interval() checked it. */
  744. return tor_tls_context_init(flags,
  745. get_tlsclient_identity_key(),
  746. server_mode(options) ?
  747. get_server_identity_key() : NULL,
  748. (unsigned int)lifetime);
  749. }
  750. /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
  751. * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
  752. * -1 if Tor should die,
  753. */
  754. STATIC int
  755. router_write_fingerprint(int hashed)
  756. {
  757. char *keydir = NULL, *cp = NULL;
  758. const char *fname = hashed ? "hashed-fingerprint" :
  759. "fingerprint";
  760. char fingerprint[FINGERPRINT_LEN+1];
  761. const or_options_t *options = get_options();
  762. char *fingerprint_line = NULL;
  763. int result = -1;
  764. keydir = get_datadir_fname(fname);
  765. log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
  766. hashed ? "hashed " : "", keydir);
  767. if (!hashed) {
  768. if (crypto_pk_get_fingerprint(get_server_identity_key(),
  769. fingerprint, 0) < 0) {
  770. log_err(LD_GENERAL,"Error computing fingerprint");
  771. goto done;
  772. }
  773. } else {
  774. if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
  775. fingerprint) < 0) {
  776. log_err(LD_GENERAL,"Error computing hashed fingerprint");
  777. goto done;
  778. }
  779. }
  780. tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
  781. /* Check whether we need to write the (hashed-)fingerprint file. */
  782. cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
  783. if (!cp || strcmp(cp, fingerprint_line)) {
  784. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  785. log_err(LD_FS, "Error writing %sfingerprint line to file",
  786. hashed ? "hashed " : "");
  787. goto done;
  788. }
  789. }
  790. log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
  791. hashed ? "bridge's hashed" : "server's", options->Nickname,
  792. fingerprint);
  793. result = 0;
  794. done:
  795. tor_free(cp);
  796. tor_free(keydir);
  797. tor_free(fingerprint_line);
  798. return result;
  799. }
  800. static int
  801. init_keys_common(void)
  802. {
  803. if (!key_lock)
  804. key_lock = tor_mutex_new();
  805. /* There are a couple of paths that put us here before we've asked
  806. * openssl to initialize itself. */
  807. if (crypto_global_init(get_options()->HardwareAccel,
  808. get_options()->AccelName,
  809. get_options()->AccelDir)) {
  810. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  811. return -1;
  812. }
  813. return 0;
  814. }
  815. int
  816. init_keys_client(void)
  817. {
  818. crypto_pk_t *prkey;
  819. if (init_keys_common() < 0)
  820. return -1;
  821. if (!(prkey = crypto_pk_new()))
  822. return -1;
  823. if (crypto_pk_generate_key(prkey)) {
  824. crypto_pk_free(prkey);
  825. return -1;
  826. }
  827. set_client_identity_key(prkey);
  828. /* Create a TLS context. */
  829. if (router_initialize_tls_context() < 0) {
  830. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  831. return -1;
  832. }
  833. return 0;
  834. }
  835. /** Initialize all OR private keys, and the TLS context, as necessary.
  836. * On OPs, this only initializes the tls context. Return 0 on success,
  837. * or -1 if Tor should die.
  838. */
  839. int
  840. init_keys(void)
  841. {
  842. char *keydir;
  843. const char *mydesc;
  844. crypto_pk_t *prkey;
  845. char digest[DIGEST_LEN];
  846. char v3_digest[DIGEST_LEN];
  847. const or_options_t *options = get_options();
  848. dirinfo_type_t type;
  849. time_t now = time(NULL);
  850. dir_server_t *ds;
  851. int v3_digest_set = 0;
  852. authority_cert_t *cert = NULL;
  853. /* OP's don't need persistent keys; just make up an identity and
  854. * initialize the TLS context. */
  855. if (!server_mode(options)) {
  856. return init_keys_client();
  857. }
  858. if (init_keys_common() < 0)
  859. return -1;
  860. if (create_keys_directory(options) < 0)
  861. return -1;
  862. /* 1a. Read v3 directory authority key/cert information. */
  863. memset(v3_digest, 0, sizeof(v3_digest));
  864. if (authdir_mode_v3(options)) {
  865. if (init_v3_authority_keys()<0) {
  866. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  867. "were unable to load our v3 authority keys and certificate! "
  868. "Use tor-gencert to generate them. Dying.");
  869. return -1;
  870. }
  871. cert = get_my_v3_authority_cert();
  872. if (cert) {
  873. if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  874. v3_digest) < 0) {
  875. log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
  876. "digest.");
  877. return -1;
  878. }
  879. v3_digest_set = 1;
  880. }
  881. }
  882. /* 1b. Read identity key. Make it if none is found. */
  883. keydir = get_keydir_fname("secret_id_key");
  884. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  885. bool created = false;
  886. prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
  887. tor_free(keydir);
  888. if (!prkey) return -1;
  889. if (created)
  890. log_new_relay_greeting();
  891. set_server_identity_key(prkey);
  892. /* 1c. If we are configured as a bridge, generate a client key;
  893. * otherwise, set the server identity key as our client identity
  894. * key. */
  895. if (public_server_mode(options)) {
  896. set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
  897. } else {
  898. if (!(prkey = crypto_pk_new()))
  899. return -1;
  900. if (crypto_pk_generate_key(prkey)) {
  901. crypto_pk_free(prkey);
  902. return -1;
  903. }
  904. set_client_identity_key(prkey);
  905. }
  906. /* 1d. Load all ed25519 keys */
  907. const int new_signing_key = load_ed_keys(options,now);
  908. if (new_signing_key < 0)
  909. return -1;
  910. /* 2. Read onion key. Make it if none is found. */
  911. keydir = get_keydir_fname("secret_onion_key");
  912. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  913. prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
  914. if (created)
  915. log_new_relay_greeting();
  916. tor_free(keydir);
  917. if (!prkey) return -1;
  918. set_onion_key(prkey);
  919. if (options->command == CMD_RUN_TOR) {
  920. /* only mess with the state file if we're actually running Tor */
  921. or_state_t *state = get_or_state();
  922. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  923. /* We allow for some parsing slop, but we don't want to risk accepting
  924. * values in the distant future. If we did, we might never rotate the
  925. * onion key. */
  926. onionkey_set_at = state->LastRotatedOnionKey;
  927. } else {
  928. /* We have no LastRotatedOnionKey set; either we just created the key
  929. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  930. * start the clock ticking now so that we will eventually rotate it even
  931. * if we don't stay up for the full lifetime of an onion key. */
  932. state->LastRotatedOnionKey = onionkey_set_at = now;
  933. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  934. time(NULL)+3600 : 0);
  935. }
  936. }
  937. keydir = get_keydir_fname("secret_onion_key.old");
  938. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  939. /* Load keys from non-empty files only.
  940. * Missing old keys won't be replaced with freshly generated keys. */
  941. prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
  942. if (prkey)
  943. lastonionkey = prkey;
  944. }
  945. tor_free(keydir);
  946. {
  947. /* 2b. Load curve25519 onion keys. */
  948. int r;
  949. keydir = get_keydir_fname("secret_onion_key_ntor");
  950. r = init_curve25519_keypair_from_file(&curve25519_onion_key,
  951. keydir, 1, LOG_ERR, "onion");
  952. tor_free(keydir);
  953. if (r<0)
  954. return -1;
  955. keydir = get_keydir_fname("secret_onion_key_ntor.old");
  956. if (tor_mem_is_zero((const char *)
  957. last_curve25519_onion_key.pubkey.public_key,
  958. CURVE25519_PUBKEY_LEN) &&
  959. file_status(keydir) == FN_FILE) {
  960. /* Load keys from non-empty files only.
  961. * Missing old keys won't be replaced with freshly generated keys. */
  962. init_curve25519_keypair_from_file(&last_curve25519_onion_key,
  963. keydir, 0, LOG_ERR, "onion");
  964. }
  965. tor_free(keydir);
  966. }
  967. /* 3. Initialize link key and TLS context. */
  968. if (router_initialize_tls_context() < 0) {
  969. log_err(LD_GENERAL,"Error initializing TLS context");
  970. return -1;
  971. }
  972. /* 3b. Get an ed25519 link certificate. Note that we need to do this
  973. * after we set up the TLS context */
  974. if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
  975. log_err(LD_GENERAL,"Couldn't make link cert");
  976. return -1;
  977. }
  978. /* 4. Build our router descriptor. */
  979. /* Must be called after keys are initialized. */
  980. mydesc = router_get_my_descriptor();
  981. if (authdir_mode_v3(options)) {
  982. const char *m = NULL;
  983. routerinfo_t *ri;
  984. /* We need to add our own fingerprint so it gets recognized. */
  985. if (dirserv_add_own_fingerprint(get_server_identity_key())) {
  986. log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
  987. return -1;
  988. }
  989. if (mydesc) {
  990. was_router_added_t added;
  991. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
  992. if (!ri) {
  993. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  994. return -1;
  995. }
  996. added = dirserv_add_descriptor(ri, &m, "self");
  997. if (!WRA_WAS_ADDED(added)) {
  998. if (!WRA_WAS_OUTDATED(added)) {
  999. log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
  1000. m?m:"<unknown error>");
  1001. return -1;
  1002. } else {
  1003. /* If the descriptor was outdated, that's ok. This can happen
  1004. * when some config options are toggled that affect workers, but
  1005. * we don't really need new keys yet so the descriptor doesn't
  1006. * change and the old one is still fresh. */
  1007. log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
  1008. "after key init: %s This is usually not a problem.",
  1009. m?m:"<unknown error>");
  1010. }
  1011. }
  1012. }
  1013. }
  1014. /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
  1015. if (router_write_fingerprint(0)) {
  1016. log_err(LD_FS, "Error writing fingerprint to file");
  1017. return -1;
  1018. }
  1019. if (!public_server_mode(options) && router_write_fingerprint(1)) {
  1020. log_err(LD_FS, "Error writing hashed fingerprint to file");
  1021. return -1;
  1022. }
  1023. if (!authdir_mode(options))
  1024. return 0;
  1025. /* 6. [authdirserver only] load approved-routers file */
  1026. if (dirserv_load_fingerprint_file() < 0) {
  1027. log_err(LD_GENERAL,"Error loading fingerprints");
  1028. return -1;
  1029. }
  1030. /* 6b. [authdirserver only] add own key to approved directories. */
  1031. crypto_pk_get_digest(get_server_identity_key(), digest);
  1032. type = ((options->V3AuthoritativeDir ?
  1033. (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
  1034. (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
  1035. ds = router_get_trusteddirserver_by_digest(digest);
  1036. if (!ds) {
  1037. ds = trusted_dir_server_new(options->Nickname, NULL,
  1038. router_get_advertised_dir_port(options, 0),
  1039. router_get_advertised_or_port(options),
  1040. NULL,
  1041. digest,
  1042. v3_digest,
  1043. type, 0.0);
  1044. if (!ds) {
  1045. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  1046. "couldn't add ourselves to the authority list. Failing.");
  1047. return -1;
  1048. }
  1049. dir_server_add(ds);
  1050. }
  1051. if (ds->type != type) {
  1052. log_warn(LD_DIR, "Configured authority type does not match authority "
  1053. "type in DirAuthority list. Adjusting. (%d v %d)",
  1054. type, ds->type);
  1055. ds->type = type;
  1056. }
  1057. if (v3_digest_set && (ds->type & V3_DIRINFO) &&
  1058. tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  1059. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  1060. "DirAuthority line. Adjusting.");
  1061. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  1062. }
  1063. if (cert) { /* add my own cert to the list of known certs */
  1064. log_info(LD_DIR, "adding my own v3 cert");
  1065. if (trusted_dirs_load_certs_from_string(
  1066. cert->cache_info.signed_descriptor_body,
  1067. TRUSTED_DIRS_CERTS_SRC_SELF, 0,
  1068. NULL)<0) {
  1069. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  1070. return -1;
  1071. }
  1072. }
  1073. return 0; /* success */
  1074. }
  1075. /** The lower threshold of remaining bandwidth required to advertise (or
  1076. * automatically provide) directory services */
  1077. /* XXX Should this be increased? */
  1078. #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
  1079. /** Return true iff we have enough configured bandwidth to advertise or
  1080. * automatically provide directory services from cache directory
  1081. * information. */
  1082. int
  1083. router_has_bandwidth_to_be_dirserver(const or_options_t *options)
  1084. {
  1085. if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
  1086. return 0;
  1087. }
  1088. if (options->RelayBandwidthRate > 0 &&
  1089. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
  1090. return 0;
  1091. }
  1092. return 1;
  1093. }
  1094. /** Helper: Return 1 if we have sufficient resources for serving directory
  1095. * requests, return 0 otherwise.
  1096. * dir_port is either 0 or the configured DirPort number.
  1097. * If AccountingMax is set less than our advertised bandwidth, then don't
  1098. * serve requests. Likewise, if our advertised bandwidth is less than
  1099. * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
  1100. */
  1101. static int
  1102. router_should_be_dirserver(const or_options_t *options, int dir_port)
  1103. {
  1104. static int advertising=1; /* start out assuming we will advertise */
  1105. int new_choice=1;
  1106. const char *reason = NULL;
  1107. if (accounting_is_enabled(options) &&
  1108. get_options()->AccountingRule != ACCT_IN) {
  1109. /* Don't spend bytes for directory traffic if we could end up hibernating,
  1110. * but allow DirPort otherwise. Some relay operators set AccountingMax
  1111. * because they're confused or to get statistics. Directory traffic has a
  1112. * much larger effect on output than input so there is no reason to turn it
  1113. * off if using AccountingRule in. */
  1114. int interval_length = accounting_get_interval_length();
  1115. uint32_t effective_bw = get_effective_bwrate(options);
  1116. uint64_t acc_bytes;
  1117. if (!interval_length) {
  1118. log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
  1119. "seconds long. Raising to 1.");
  1120. interval_length = 1;
  1121. }
  1122. log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
  1123. "bwrate: %u, AccountingMax: %"PRIu64", "
  1124. "accounting interval length %d",
  1125. dir_port ? "dirport" : "begindir",
  1126. effective_bw, (options->AccountingMax),
  1127. interval_length);
  1128. acc_bytes = options->AccountingMax;
  1129. if (get_options()->AccountingRule == ACCT_SUM)
  1130. acc_bytes /= 2;
  1131. if (effective_bw >=
  1132. acc_bytes / interval_length) {
  1133. new_choice = 0;
  1134. reason = "AccountingMax enabled";
  1135. }
  1136. } else if (! router_has_bandwidth_to_be_dirserver(options)) {
  1137. /* if we're advertising a small amount */
  1138. new_choice = 0;
  1139. reason = "BandwidthRate under 50KB";
  1140. }
  1141. if (advertising != new_choice) {
  1142. if (new_choice == 1) {
  1143. if (dir_port > 0)
  1144. log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
  1145. else
  1146. log_notice(LD_DIR, "Advertising directory service support");
  1147. } else {
  1148. tor_assert(reason);
  1149. log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
  1150. dir_port ? "Port" : "ectory Service support", reason);
  1151. }
  1152. advertising = new_choice;
  1153. }
  1154. return advertising;
  1155. }
  1156. /** Look at a variety of factors, and return 0 if we don't want to
  1157. * advertise the fact that we have a DirPort open or begindir support, else
  1158. * return 1.
  1159. *
  1160. * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
  1161. * must be 0.
  1162. *
  1163. * Log a helpful message if we change our mind about whether to publish.
  1164. */
  1165. static int
  1166. decide_to_advertise_dir_impl(const or_options_t *options,
  1167. uint16_t dir_port,
  1168. int supports_tunnelled_dir_requests)
  1169. {
  1170. /* Part one: reasons to publish or not publish that aren't
  1171. * worth mentioning to the user, either because they're obvious
  1172. * or because they're normal behavior. */
  1173. /* short circuit the rest of the function */
  1174. if (!dir_port && !supports_tunnelled_dir_requests)
  1175. return 0;
  1176. if (authdir_mode(options)) /* always publish */
  1177. return 1;
  1178. if (net_is_disabled())
  1179. return 0;
  1180. if (dir_port && !router_get_advertised_dir_port(options, dir_port))
  1181. return 0;
  1182. if (supports_tunnelled_dir_requests &&
  1183. !router_get_advertised_or_port(options))
  1184. return 0;
  1185. /* Part two: consider config options that could make us choose to
  1186. * publish or not publish that the user might find surprising. */
  1187. return router_should_be_dirserver(options, dir_port);
  1188. }
  1189. /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
  1190. * advertise the fact that we have a DirPort open, else return the
  1191. * DirPort we want to advertise.
  1192. */
  1193. int
  1194. router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
  1195. {
  1196. /* supports_tunnelled_dir_requests is not relevant, pass 0 */
  1197. return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
  1198. }
  1199. /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
  1200. * advertise the fact that we support begindir requests, else return 1.
  1201. */
  1202. static int
  1203. router_should_advertise_begindir(const or_options_t *options,
  1204. int supports_tunnelled_dir_requests)
  1205. {
  1206. /* dir_port is not relevant, pass 0 */
  1207. return decide_to_advertise_dir_impl(options, 0,
  1208. supports_tunnelled_dir_requests);
  1209. }
  1210. /** Return true iff our network is in some sense disabled or shutting down:
  1211. * either we're hibernating, entering hibernation, or the network is turned
  1212. * off with DisableNetwork. */
  1213. int
  1214. net_is_disabled(void)
  1215. {
  1216. return get_options()->DisableNetwork || we_are_hibernating();
  1217. }
  1218. /** Return true iff our network is in some sense "completely disabled" either
  1219. * we're fully hibernating or the network is turned off with
  1220. * DisableNetwork. */
  1221. int
  1222. net_is_completely_disabled(void)
  1223. {
  1224. return get_options()->DisableNetwork || we_are_fully_hibernating();
  1225. }
  1226. /** Return true iff the combination of options in <b>options</b> and parameters
  1227. * in the consensus mean that we don't want to allow exits from circuits
  1228. * we got from addresses not known to be servers. */
  1229. int
  1230. should_refuse_unknown_exits(const or_options_t *options)
  1231. {
  1232. if (options->RefuseUnknownExits != -1) {
  1233. return options->RefuseUnknownExits;
  1234. } else {
  1235. return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
  1236. }
  1237. }
  1238. /** Decide if we're a publishable server. We are a publishable server if:
  1239. * - We don't have the ClientOnly option set
  1240. * and
  1241. * - We have the PublishServerDescriptor option set to non-empty
  1242. * and
  1243. * - We have ORPort set
  1244. * and
  1245. * - We believe our ORPort and DirPort (if present) are reachable from
  1246. * the outside; or
  1247. * - We believe our ORPort is reachable from the outside, and we can't
  1248. * check our DirPort because the consensus has no exits; or
  1249. * - We are an authoritative directory server.
  1250. */
  1251. static int
  1252. decide_if_publishable_server(void)
  1253. {
  1254. const or_options_t *options = get_options();
  1255. if (options->ClientOnly)
  1256. return 0;
  1257. if (options->PublishServerDescriptor_ == NO_DIRINFO)
  1258. return 0;
  1259. if (!server_mode(options))
  1260. return 0;
  1261. if (authdir_mode(options))
  1262. return 1;
  1263. if (!router_get_advertised_or_port(options))
  1264. return 0;
  1265. if (!check_whether_orport_reachable(options))
  1266. return 0;
  1267. if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
  1268. /* All set: there are no exits in the consensus (maybe this is a tiny
  1269. * test network), so we can't check our DirPort reachability. */
  1270. return 1;
  1271. } else {
  1272. return check_whether_dirport_reachable(options);
  1273. }
  1274. }
  1275. /** Initiate server descriptor upload as reasonable (if server is publishable,
  1276. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  1277. *
  1278. * We need to rebuild the descriptor if it's dirty even if we're not
  1279. * uploading, because our reachability testing *uses* our descriptor to
  1280. * determine what IP address and ports to test.
  1281. */
  1282. void
  1283. consider_publishable_server(int force)
  1284. {
  1285. int rebuilt;
  1286. if (!server_mode(get_options()))
  1287. return;
  1288. rebuilt = router_rebuild_descriptor(0);
  1289. if (decide_if_publishable_server()) {
  1290. set_server_advertised(1);
  1291. if (rebuilt == 0)
  1292. router_upload_dir_desc_to_dirservers(force);
  1293. } else {
  1294. set_server_advertised(0);
  1295. }
  1296. }
  1297. /** Return the port of the first active listener of type
  1298. * <b>listener_type</b>. */
  1299. /** XXX not a very good interface. it's not reliable when there are
  1300. multiple listeners. */
  1301. uint16_t
  1302. router_get_active_listener_port_by_type_af(int listener_type,
  1303. sa_family_t family)
  1304. {
  1305. /* Iterate all connections, find one of the right kind and return
  1306. the port. Not very sophisticated or fast, but effective. */
  1307. smartlist_t *conns = get_connection_array();
  1308. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1309. if (conn->type == listener_type && !conn->marked_for_close &&
  1310. conn->socket_family == family) {
  1311. return conn->port;
  1312. }
  1313. } SMARTLIST_FOREACH_END(conn);
  1314. return 0;
  1315. }
  1316. /** Return the port that we should advertise as our ORPort; this is either
  1317. * the one configured in the ORPort option, or the one we actually bound to
  1318. * if ORPort is "auto".
  1319. */
  1320. uint16_t
  1321. router_get_advertised_or_port(const or_options_t *options)
  1322. {
  1323. return router_get_advertised_or_port_by_af(options, AF_INET);
  1324. }
  1325. /** As router_get_advertised_or_port(), but allows an address family argument.
  1326. */
  1327. uint16_t
  1328. router_get_advertised_or_port_by_af(const or_options_t *options,
  1329. sa_family_t family)
  1330. {
  1331. int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
  1332. family);
  1333. (void)options;
  1334. /* If the port is in 'auto' mode, we have to use
  1335. router_get_listener_port_by_type(). */
  1336. if (port == CFG_AUTO_PORT)
  1337. return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
  1338. family);
  1339. return port;
  1340. }
  1341. /** Return the port that we should advertise as our DirPort;
  1342. * this is one of three possibilities:
  1343. * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
  1344. * the one configured in the DirPort option,
  1345. * or the one we actually bound to if DirPort is "auto". */
  1346. uint16_t
  1347. router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
  1348. {
  1349. int dirport_configured = get_primary_dir_port();
  1350. (void)options;
  1351. if (!dirport_configured)
  1352. return dirport;
  1353. if (dirport_configured == CFG_AUTO_PORT)
  1354. return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
  1355. AF_INET);
  1356. return dirport_configured;
  1357. }
  1358. /*
  1359. * OR descriptor generation.
  1360. */
  1361. /** My routerinfo. */
  1362. static routerinfo_t *desc_routerinfo = NULL;
  1363. /** My extrainfo */
  1364. static extrainfo_t *desc_extrainfo = NULL;
  1365. /** Why did we most recently decide to regenerate our descriptor? Used to
  1366. * tell the authorities why we're sending it to them. */
  1367. static const char *desc_gen_reason = "uninitialized reason";
  1368. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  1369. * now. */
  1370. static time_t desc_clean_since = 0;
  1371. /** Why did we mark the descriptor dirty? */
  1372. static const char *desc_dirty_reason = "Tor just started";
  1373. /** Boolean: do we need to regenerate the above? */
  1374. static int desc_needs_upload = 0;
  1375. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1376. * descriptor successfully yet, try to upload our signed descriptor to
  1377. * all the directory servers we know about.
  1378. */
  1379. void
  1380. router_upload_dir_desc_to_dirservers(int force)
  1381. {
  1382. const routerinfo_t *ri;
  1383. extrainfo_t *ei;
  1384. char *msg;
  1385. size_t desc_len, extra_len = 0, total_len;
  1386. dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
  1387. ri = router_get_my_routerinfo();
  1388. if (!ri) {
  1389. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1390. return;
  1391. }
  1392. ei = router_get_my_extrainfo();
  1393. if (auth == NO_DIRINFO)
  1394. return;
  1395. if (!force && !desc_needs_upload)
  1396. return;
  1397. log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
  1398. force ? " (forced)" : "");
  1399. desc_needs_upload = 0;
  1400. desc_len = ri->cache_info.signed_descriptor_len;
  1401. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1402. total_len = desc_len + extra_len + 1;
  1403. msg = tor_malloc(total_len);
  1404. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1405. if (ei) {
  1406. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1407. }
  1408. msg[desc_len+extra_len] = 0;
  1409. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1410. (auth & BRIDGE_DIRINFO) ?
  1411. ROUTER_PURPOSE_BRIDGE :
  1412. ROUTER_PURPOSE_GENERAL,
  1413. auth, msg, desc_len, extra_len);
  1414. tor_free(msg);
  1415. }
  1416. /** OR only: Check whether my exit policy says to allow connection to
  1417. * conn. Return 0 if we accept; non-0 if we reject.
  1418. */
  1419. int
  1420. router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
  1421. {
  1422. const routerinfo_t *me = router_get_my_routerinfo();
  1423. if (!me) /* make sure routerinfo exists */
  1424. return -1;
  1425. /* make sure it's resolved to something. this way we can't get a
  1426. 'maybe' below. */
  1427. if (tor_addr_is_null(addr))
  1428. return -1;
  1429. /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
  1430. * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
  1431. * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
  1432. * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
  1433. * summary. */
  1434. if ((tor_addr_family(addr) == AF_INET ||
  1435. tor_addr_family(addr) == AF_INET6)) {
  1436. return compare_tor_addr_to_addr_policy(addr, port,
  1437. me->exit_policy) != ADDR_POLICY_ACCEPTED;
  1438. #if 0
  1439. } else if (tor_addr_family(addr) == AF_INET6) {
  1440. return get_options()->IPv6Exit &&
  1441. desc_routerinfo->ipv6_exit_policy &&
  1442. compare_tor_addr_to_short_policy(addr, port,
  1443. me->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
  1444. #endif /* 0 */
  1445. } else {
  1446. return -1;
  1447. }
  1448. }
  1449. /** Return true iff my exit policy is reject *:*. Return -1 if we don't
  1450. * have a descriptor */
  1451. MOCK_IMPL(int,
  1452. router_my_exit_policy_is_reject_star,(void))
  1453. {
  1454. const routerinfo_t *me = router_get_my_routerinfo();
  1455. if (!me) /* make sure routerinfo exists */
  1456. return -1;
  1457. return me->policy_is_reject_star;
  1458. }
  1459. /** Return true iff I'm a server and <b>digest</b> is equal to
  1460. * my server identity key digest. */
  1461. int
  1462. router_digest_is_me(const char *digest)
  1463. {
  1464. return (server_identitykey &&
  1465. tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
  1466. }
  1467. /** Return my identity digest. */
  1468. const uint8_t *
  1469. router_get_my_id_digest(void)
  1470. {
  1471. return (const uint8_t *)server_identitykey_digest;
  1472. }
  1473. /** Return true iff I'm a server and <b>digest</b> is equal to
  1474. * my identity digest. */
  1475. int
  1476. router_extrainfo_digest_is_me(const char *digest)
  1477. {
  1478. extrainfo_t *ei = router_get_my_extrainfo();
  1479. if (!ei)
  1480. return 0;
  1481. return tor_memeq(digest,
  1482. ei->cache_info.signed_descriptor_digest,
  1483. DIGEST_LEN);
  1484. }
  1485. /** A wrapper around router_digest_is_me(). */
  1486. int
  1487. router_is_me(const routerinfo_t *router)
  1488. {
  1489. return router_digest_is_me(router->cache_info.identity_digest);
  1490. }
  1491. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1492. * necessary. Return NULL on error, or if called on an OP. */
  1493. MOCK_IMPL(const routerinfo_t *,
  1494. router_get_my_routerinfo,(void))
  1495. {
  1496. return router_get_my_routerinfo_with_err(NULL);
  1497. }
  1498. /** Return routerinfo of this OR. Rebuild it from
  1499. * scratch if needed. Set <b>*err</b> to 0 on success or to
  1500. * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
  1501. */
  1502. MOCK_IMPL(const routerinfo_t *,
  1503. router_get_my_routerinfo_with_err,(int *err))
  1504. {
  1505. if (!server_mode(get_options())) {
  1506. if (err)
  1507. *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
  1508. return NULL;
  1509. }
  1510. if (!desc_clean_since) {
  1511. int rebuild_err = router_rebuild_descriptor(0);
  1512. if (rebuild_err < 0) {
  1513. if (err)
  1514. *err = rebuild_err;
  1515. return NULL;
  1516. }
  1517. }
  1518. if (!desc_routerinfo) {
  1519. if (err)
  1520. *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
  1521. return NULL;
  1522. }
  1523. if (err)
  1524. *err = 0;
  1525. return desc_routerinfo;
  1526. }
  1527. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1528. * one if necessary. Return NULL on error.
  1529. */
  1530. const char *
  1531. router_get_my_descriptor(void)
  1532. {
  1533. const char *body;
  1534. const routerinfo_t *me = router_get_my_routerinfo();
  1535. if (! me)
  1536. return NULL;
  1537. tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
  1538. body = signed_descriptor_get_body(&me->cache_info);
  1539. /* Make sure this is nul-terminated. */
  1540. tor_assert(!body[me->cache_info.signed_descriptor_len]);
  1541. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1542. return body;
  1543. }
  1544. /** Return the extrainfo document for this OR, or NULL if we have none.
  1545. * Rebuilt it (and the server descriptor) if necessary. */
  1546. extrainfo_t *
  1547. router_get_my_extrainfo(void)
  1548. {
  1549. if (!server_mode(get_options()))
  1550. return NULL;
  1551. if (router_rebuild_descriptor(0))
  1552. return NULL;
  1553. return desc_extrainfo;
  1554. }
  1555. /** Return a human-readable string describing what triggered us to generate
  1556. * our current descriptor, or NULL if we don't know. */
  1557. const char *
  1558. router_get_descriptor_gen_reason(void)
  1559. {
  1560. return desc_gen_reason;
  1561. }
  1562. /** A list of nicknames that we've warned about including in our family
  1563. * declaration verbatim rather than as digests. */
  1564. static smartlist_t *warned_nonexistent_family = NULL;
  1565. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1566. /** Make a current best guess at our address, either because
  1567. * it's configured in torrc, or because we've learned it from
  1568. * dirserver headers. Place the answer in *<b>addr</b> and return
  1569. * 0 on success, else return -1 if we have no guess.
  1570. *
  1571. * If <b>cache_only</b> is true, just return any cached answers, and
  1572. * don't try to get any new answers.
  1573. */
  1574. MOCK_IMPL(int,
  1575. router_pick_published_address,(const or_options_t *options, uint32_t *addr,
  1576. int cache_only))
  1577. {
  1578. /* First, check the cached output from resolve_my_address(). */
  1579. *addr = get_last_resolved_addr();
  1580. if (*addr)
  1581. return 0;
  1582. /* Second, consider doing a resolve attempt right here. */
  1583. if (!cache_only) {
  1584. if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
  1585. log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
  1586. return 0;
  1587. }
  1588. }
  1589. /* Third, check the cached output from router_new_address_suggestion(). */
  1590. if (router_guess_address_from_dir_headers(addr) >= 0)
  1591. return 0;
  1592. /* We have no useful cached answers. Return failure. */
  1593. return -1;
  1594. }
  1595. /* Like router_check_descriptor_address_consistency, but specifically for the
  1596. * ORPort or DirPort.
  1597. * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
  1598. static void
  1599. router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
  1600. int listener_type)
  1601. {
  1602. tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
  1603. listener_type == CONN_TYPE_DIR_LISTENER);
  1604. /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
  1605. */
  1606. int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
  1607. AF_INET);
  1608. if (port_v4_cfg != 0 &&
  1609. !port_exists_by_type_addr32h_port(listener_type,
  1610. ipv4h_desc_addr, port_v4_cfg, 1)) {
  1611. const tor_addr_t *port_addr = get_first_advertised_addr_by_type_af(
  1612. listener_type,
  1613. AF_INET);
  1614. /* If we're building a descriptor with no advertised address,
  1615. * something is terribly wrong. */
  1616. tor_assert(port_addr);
  1617. tor_addr_t desc_addr;
  1618. char port_addr_str[TOR_ADDR_BUF_LEN];
  1619. char desc_addr_str[TOR_ADDR_BUF_LEN];
  1620. tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
  1621. tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
  1622. tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
  1623. const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
  1624. "OR" : "Dir");
  1625. log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
  1626. "descriptor address %s. If you have a static public IPv4 "
  1627. "address, use 'Address <IPv4>' and 'OutboundBindAddress "
  1628. "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
  1629. "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
  1630. "NoAdvertise'.",
  1631. listener_str, port_addr_str, desc_addr_str, listener_str,
  1632. listener_str, listener_str);
  1633. }
  1634. }
  1635. /* Tor relays only have one IPv4 address in the descriptor, which is derived
  1636. * from the Address torrc option, or guessed using various methods in
  1637. * router_pick_published_address().
  1638. * Warn the operator if there is no ORPort on the descriptor address
  1639. * ipv4h_desc_addr.
  1640. * Warn the operator if there is no DirPort on the descriptor address.
  1641. * This catches a few common config errors:
  1642. * - operators who expect ORPorts and DirPorts to be advertised on the
  1643. * ports' listen addresses, rather than the torrc Address (or guessed
  1644. * addresses in the absence of an Address config). This includes
  1645. * operators who attempt to put their ORPort and DirPort on different
  1646. * addresses;
  1647. * - discrepancies between guessed addresses and configured listen
  1648. * addresses (when the Address option isn't set).
  1649. * If a listener is listening on all IPv4 addresses, it is assumed that it
  1650. * is listening on the configured Address, and no messages are logged.
  1651. * If an operators has specified NoAdvertise ORPorts in a NAT setting,
  1652. * no messages are logged, unless they have specified other advertised
  1653. * addresses.
  1654. * The message tells operators to configure an ORPort and DirPort that match
  1655. * the Address (using NoListen if needed).
  1656. */
  1657. static void
  1658. router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
  1659. {
  1660. router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
  1661. CONN_TYPE_OR_LISTENER);
  1662. router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
  1663. CONN_TYPE_DIR_LISTENER);
  1664. }
  1665. /** Build a fresh routerinfo, signed server descriptor, and extra-info document
  1666. * for this OR. Set r to the generated routerinfo, e to the generated
  1667. * extra-info document. Return 0 on success, -1 on temporary error. Failure to
  1668. * generate an extra-info document is not an error and is indicated by setting
  1669. * e to NULL. Caller is responsible for freeing generated documents if 0 is
  1670. * returned.
  1671. */
  1672. int
  1673. router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
  1674. {
  1675. routerinfo_t *ri;
  1676. extrainfo_t *ei;
  1677. uint32_t addr;
  1678. char platform[256];
  1679. int hibernating = we_are_hibernating();
  1680. const or_options_t *options = get_options();
  1681. if (router_pick_published_address(options, &addr, 0) < 0) {
  1682. log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
  1683. return TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
  1684. }
  1685. /* Log a message if the address in the descriptor doesn't match the ORPort
  1686. * and DirPort addresses configured by the operator. */
  1687. router_check_descriptor_address_consistency(addr);
  1688. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1689. ri->cache_info.routerlist_index = -1;
  1690. ri->nickname = tor_strdup(options->Nickname);
  1691. ri->addr = addr;
  1692. ri->or_port = router_get_advertised_or_port(options);
  1693. ri->dir_port = router_get_advertised_dir_port(options, 0);
  1694. ri->supports_tunnelled_dir_requests =
  1695. directory_permits_begindir_requests(options);
  1696. ri->cache_info.published_on = time(NULL);
  1697. /* get_onion_key() must invoke from main thread */
  1698. router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
  1699. &ri->onion_pkey_len);
  1700. ri->onion_curve25519_pkey =
  1701. tor_memdup(&get_current_curve25519_keypair()->pubkey,
  1702. sizeof(curve25519_public_key_t));
  1703. /* For now, at most one IPv6 or-address is being advertised. */
  1704. {
  1705. const port_cfg_t *ipv6_orport = NULL;
  1706. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1707. if (p->type == CONN_TYPE_OR_LISTENER &&
  1708. ! p->server_cfg.no_advertise &&
  1709. ! p->server_cfg.bind_ipv4_only &&
  1710. tor_addr_family(&p->addr) == AF_INET6) {
  1711. /* Like IPv4, if the relay is configured using the default
  1712. * authorities, disallow internal IPs. Otherwise, allow them. */
  1713. const int default_auth = using_default_dir_authorities(options);
  1714. if (! tor_addr_is_internal(&p->addr, 0) || ! default_auth) {
  1715. ipv6_orport = p;
  1716. break;
  1717. } else {
  1718. char addrbuf[TOR_ADDR_BUF_LEN];
  1719. log_warn(LD_CONFIG,
  1720. "Unable to use configured IPv6 address \"%s\" in a "
  1721. "descriptor. Skipping it. "
  1722. "Try specifying a globally reachable address explicitly.",
  1723. tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
  1724. }
  1725. }
  1726. } SMARTLIST_FOREACH_END(p);
  1727. if (ipv6_orport) {
  1728. tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
  1729. ri->ipv6_orport = ipv6_orport->port;
  1730. }
  1731. }
  1732. ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
  1733. if (BUG(crypto_pk_get_digest(ri->identity_pkey,
  1734. ri->cache_info.identity_digest) < 0)) {
  1735. routerinfo_free(ri);
  1736. return TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
  1737. }
  1738. ri->cache_info.signing_key_cert =
  1739. tor_cert_dup(get_master_signing_key_cert());
  1740. get_platform_str(platform, sizeof(platform));
  1741. ri->platform = tor_strdup(platform);
  1742. ri->protocol_list = tor_strdup(protover_get_supported_protocols());
  1743. /* compute ri->bandwidthrate as the min of various options */
  1744. ri->bandwidthrate = get_effective_bwrate(options);
  1745. /* and compute ri->bandwidthburst similarly */
  1746. ri->bandwidthburst = get_effective_bwburst(options);
  1747. /* Report bandwidth, unless we're hibernating or shutting down */
  1748. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1749. if (dns_seems_to_be_broken() || has_dns_init_failed()) {
  1750. /* DNS is screwed up; don't claim to be an exit. */
  1751. policies_exit_policy_append_reject_star(&ri->exit_policy);
  1752. } else {
  1753. policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,
  1754. &ri->exit_policy);
  1755. }
  1756. ri->policy_is_reject_star =
  1757. policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
  1758. policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
  1759. if (options->IPv6Exit) {
  1760. char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
  1761. if (p_tmp)
  1762. ri->ipv6_exit_policy = parse_short_policy(p_tmp);
  1763. tor_free(p_tmp);
  1764. }
  1765. if (options->MyFamily && ! options->BridgeRelay) {
  1766. if (!warned_nonexistent_family)
  1767. warned_nonexistent_family = smartlist_new();
  1768. ri->declared_family = smartlist_new();
  1769. config_line_t *family;
  1770. for (family = options->MyFamily; family; family = family->next) {
  1771. char *name = family->value;
  1772. const node_t *member;
  1773. if (!strcasecmp(name, options->Nickname))
  1774. continue; /* Don't list ourself, that's redundant */
  1775. else
  1776. member = node_get_by_nickname(name, 0);
  1777. if (!member) {
  1778. int is_legal = is_legal_nickname_or_hexdigest(name);
  1779. if (!smartlist_contains_string(warned_nonexistent_family, name) &&
  1780. !is_legal_hexdigest(name)) {
  1781. if (is_legal)
  1782. log_warn(LD_CONFIG,
  1783. "I have no descriptor for the router named \"%s\" in my "
  1784. "declared family; I'll use the nickname as is, but "
  1785. "this may confuse clients.", name);
  1786. else
  1787. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1788. "declared family, but that isn't a legal nickname. "
  1789. "Skipping it.", escaped(name));
  1790. smartlist_add_strdup(warned_nonexistent_family, name);
  1791. }
  1792. if (is_legal) {
  1793. smartlist_add_strdup(ri->declared_family, name);
  1794. }
  1795. } else if (router_digest_is_me(member->identity)) {
  1796. /* Don't list ourself in our own family; that's redundant */
  1797. /* XXX shouldn't be possible */
  1798. } else {
  1799. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1800. fp[0] = '$';
  1801. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1802. member->identity, DIGEST_LEN);
  1803. smartlist_add(ri->declared_family, fp);
  1804. if (smartlist_contains_string(warned_nonexistent_family, name))
  1805. smartlist_string_remove(warned_nonexistent_family, name);
  1806. }
  1807. }
  1808. /* remove duplicates from the list */
  1809. smartlist_sort_strings(ri->declared_family);
  1810. smartlist_uniq_strings(ri->declared_family);
  1811. }
  1812. /* Now generate the extrainfo. */
  1813. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1814. ei->cache_info.is_extrainfo = 1;
  1815. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1816. ei->cache_info.published_on = ri->cache_info.published_on;
  1817. ei->cache_info.signing_key_cert =
  1818. tor_cert_dup(get_master_signing_key_cert());
  1819. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1820. DIGEST_LEN);
  1821. if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
  1822. ei, get_server_identity_key(),
  1823. get_master_signing_keypair()) < 0) {
  1824. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1825. extrainfo_free(ei);
  1826. ei = NULL;
  1827. } else {
  1828. ei->cache_info.signed_descriptor_len =
  1829. strlen(ei->cache_info.signed_descriptor_body);
  1830. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1831. ei->cache_info.signed_descriptor_len,
  1832. ei->cache_info.signed_descriptor_digest);
  1833. crypto_digest256((char*) ei->digest256,
  1834. ei->cache_info.signed_descriptor_body,
  1835. ei->cache_info.signed_descriptor_len,
  1836. DIGEST_SHA256);
  1837. }
  1838. /* Now finish the router descriptor. */
  1839. if (ei) {
  1840. memcpy(ri->cache_info.extra_info_digest,
  1841. ei->cache_info.signed_descriptor_digest,
  1842. DIGEST_LEN);
  1843. memcpy(ri->cache_info.extra_info_digest256,
  1844. ei->digest256,
  1845. DIGEST256_LEN);
  1846. } else {
  1847. /* ri was allocated with tor_malloc_zero, so there is no need to
  1848. * zero ri->cache_info.extra_info_digest here. */
  1849. }
  1850. if (! (ri->cache_info.signed_descriptor_body =
  1851. router_dump_router_to_string(ri, get_server_identity_key(),
  1852. get_onion_key(),
  1853. get_current_curve25519_keypair(),
  1854. get_master_signing_keypair())) ) {
  1855. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1856. routerinfo_free(ri);
  1857. extrainfo_free(ei);
  1858. return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
  1859. }
  1860. ri->cache_info.signed_descriptor_len =
  1861. strlen(ri->cache_info.signed_descriptor_body);
  1862. ri->purpose =
  1863. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1864. if (options->BridgeRelay) {
  1865. /* Bridges shouldn't be able to send their descriptors unencrypted,
  1866. anyway, since they don't have a DirPort, and always connect to the
  1867. bridge authority anonymously. But just in case they somehow think of
  1868. sending them on an unencrypted connection, don't allow them to try. */
  1869. ri->cache_info.send_unencrypted = 0;
  1870. if (ei)
  1871. ei->cache_info.send_unencrypted = 0;
  1872. } else {
  1873. ri->cache_info.send_unencrypted = 1;
  1874. if (ei)
  1875. ei->cache_info.send_unencrypted = 1;
  1876. }
  1877. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1878. strlen(ri->cache_info.signed_descriptor_body),
  1879. ri->cache_info.signed_descriptor_digest);
  1880. if (ei) {
  1881. tor_assert(!
  1882. routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
  1883. &ri->cache_info, NULL));
  1884. }
  1885. *r = ri;
  1886. *e = ei;
  1887. return 0;
  1888. }
  1889. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1890. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1891. * Return 0 on success, -1 on temporary error.
  1892. */
  1893. int
  1894. router_rebuild_descriptor(int force)
  1895. {
  1896. int err = 0;
  1897. routerinfo_t *ri;
  1898. extrainfo_t *ei;
  1899. uint32_t addr;
  1900. const or_options_t *options = get_options();
  1901. if (desc_clean_since && !force)
  1902. return 0;
  1903. if (router_pick_published_address(options, &addr, 0) < 0 ||
  1904. router_get_advertised_or_port(options) == 0) {
  1905. /* Stop trying to rebuild our descriptor every second. We'll
  1906. * learn that it's time to try again when ip_address_changed()
  1907. * marks it dirty. */
  1908. desc_clean_since = time(NULL);
  1909. return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
  1910. }
  1911. log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
  1912. err = router_build_fresh_descriptor(&ri, &ei);
  1913. if (err < 0) {
  1914. return err;
  1915. }
  1916. routerinfo_free(desc_routerinfo);
  1917. desc_routerinfo = ri;
  1918. extrainfo_free(desc_extrainfo);
  1919. desc_extrainfo = ei;
  1920. desc_clean_since = time(NULL);
  1921. desc_needs_upload = 1;
  1922. desc_gen_reason = desc_dirty_reason;
  1923. if (BUG(desc_gen_reason == NULL)) {
  1924. desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
  1925. }
  1926. desc_dirty_reason = NULL;
  1927. control_event_my_descriptor_changed();
  1928. return 0;
  1929. }
  1930. /** If our router descriptor ever goes this long without being regenerated
  1931. * because something changed, we force an immediate regenerate-and-upload. */
  1932. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  1933. /** If our router descriptor seems to be missing or unacceptable according
  1934. * to the authorities, regenerate and reupload it _this_ often. */
  1935. #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
  1936. /** Mark descriptor out of date if it's been "too long" since we last tried
  1937. * to upload one. */
  1938. void
  1939. mark_my_descriptor_dirty_if_too_old(time_t now)
  1940. {
  1941. networkstatus_t *ns;
  1942. const routerstatus_t *rs;
  1943. const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
  1944. const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
  1945. const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
  1946. /* If it's already dirty, don't mark it. */
  1947. if (! desc_clean_since)
  1948. return;
  1949. /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
  1950. * time to rebuild it. */
  1951. if (desc_clean_since < slow_cutoff) {
  1952. mark_my_descriptor_dirty("time for new descriptor");
  1953. return;
  1954. }
  1955. /* Now we see whether we want to be retrying frequently or no. The
  1956. * rule here is that we'll retry frequently if we aren't listed in the
  1957. * live consensus we have, or if the publication time of the
  1958. * descriptor listed for us in the consensus is very old. */
  1959. ns = networkstatus_get_live_consensus(now);
  1960. if (ns) {
  1961. rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
  1962. if (rs == NULL)
  1963. retry_fast_reason = "not listed in consensus";
  1964. else if (rs->published_on < slow_cutoff)
  1965. retry_fast_reason = "version listed in consensus is quite old";
  1966. }
  1967. if (retry_fast_reason && desc_clean_since < fast_cutoff)
  1968. mark_my_descriptor_dirty(retry_fast_reason);
  1969. }
  1970. /** Call when the current descriptor is out of date. */
  1971. void
  1972. mark_my_descriptor_dirty(const char *reason)
  1973. {
  1974. const or_options_t *options = get_options();
  1975. if (BUG(reason == NULL)) {
  1976. reason = "marked descriptor dirty for unspecified reason";
  1977. }
  1978. if (server_mode(options) && options->PublishServerDescriptor_)
  1979. log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
  1980. desc_clean_since = 0;
  1981. if (!desc_dirty_reason)
  1982. desc_dirty_reason = reason;
  1983. }
  1984. /** How frequently will we republish our descriptor because of large (factor
  1985. * of 2) shifts in estimated bandwidth? Note: We don't use this constant
  1986. * if our previous bandwidth estimate was exactly 0. */
  1987. #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
  1988. /** Maximum uptime to republish our descriptor because of large shifts in
  1989. * estimated bandwidth. */
  1990. #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
  1991. /** By which factor bandwidth shifts have to change to be considered large. */
  1992. #define BANDWIDTH_CHANGE_FACTOR 2
  1993. /** Check whether bandwidth has changed a lot since the last time we announced
  1994. * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
  1995. * If so, mark our descriptor dirty. */
  1996. void
  1997. check_descriptor_bandwidth_changed(time_t now)
  1998. {
  1999. static time_t last_changed = 0;
  2000. uint64_t prev, cur;
  2001. const int hibernating = we_are_hibernating();
  2002. /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
  2003. * the next regularly scheduled descriptor update (18h) will be enough */
  2004. if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
  2005. return;
  2006. const routerinfo_t *my_ri = router_get_my_routerinfo();
  2007. if (!my_ri)
  2008. return;
  2009. prev = my_ri->bandwidthcapacity;
  2010. /* Consider ourselves to have zero bandwidth if we're hibernating or
  2011. * shutting down. */
  2012. cur = hibernating ? 0 : rep_hist_bandwidth_assess();
  2013. if ((prev != cur && (!prev || !cur)) ||
  2014. cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
  2015. cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
  2016. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
  2017. log_info(LD_GENERAL,
  2018. "Measured bandwidth has changed; rebuilding descriptor.");
  2019. mark_my_descriptor_dirty("bandwidth has changed");
  2020. last_changed = now;
  2021. }
  2022. }
  2023. }
  2024. /** Note at log level severity that our best guess of address has changed from
  2025. * <b>prev</b> to <b>cur</b>. */
  2026. static void
  2027. log_addr_has_changed(int severity,
  2028. const tor_addr_t *prev,
  2029. const tor_addr_t *cur,
  2030. const char *source)
  2031. {
  2032. char addrbuf_prev[TOR_ADDR_BUF_LEN];
  2033. char addrbuf_cur[TOR_ADDR_BUF_LEN];
  2034. if (BUG(!server_mode(get_options())))
  2035. return;
  2036. if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
  2037. strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
  2038. if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
  2039. strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
  2040. if (!tor_addr_is_null(prev))
  2041. log_fn(severity, LD_GENERAL,
  2042. "Our IP Address has changed from %s to %s; "
  2043. "rebuilding descriptor (source: %s).",
  2044. addrbuf_prev, addrbuf_cur, source);
  2045. else
  2046. log_notice(LD_GENERAL,
  2047. "Guessed our IP address as %s (source: %s).",
  2048. addrbuf_cur, source);
  2049. }
  2050. /** Check whether our own address as defined by the Address configuration
  2051. * has changed. This is for routers that get their address from a service
  2052. * like dyndns. If our address has changed, mark our descriptor dirty. */
  2053. void
  2054. check_descriptor_ipaddress_changed(time_t now)
  2055. {
  2056. uint32_t prev, cur;
  2057. const or_options_t *options = get_options();
  2058. const char *method = NULL;
  2059. char *hostname = NULL;
  2060. const routerinfo_t *my_ri = router_get_my_routerinfo();
  2061. (void) now;
  2062. if (my_ri == NULL) /* make sure routerinfo exists */
  2063. return;
  2064. /* XXXX ipv6 */
  2065. prev = my_ri->addr;
  2066. if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
  2067. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  2068. return;
  2069. }
  2070. if (prev != cur) {
  2071. char *source;
  2072. tor_addr_t tmp_prev, tmp_cur;
  2073. tor_addr_from_ipv4h(&tmp_prev, prev);
  2074. tor_addr_from_ipv4h(&tmp_cur, cur);
  2075. tor_asprintf(&source, "METHOD=%s%s%s", method,
  2076. hostname ? " HOSTNAME=" : "",
  2077. hostname ? hostname : "");
  2078. log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
  2079. tor_free(source);
  2080. ip_address_changed(0);
  2081. }
  2082. tor_free(hostname);
  2083. }
  2084. /** The most recently guessed value of our IP address, based on directory
  2085. * headers. */
  2086. static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
  2087. /** A directory server <b>d_conn</b> told us our IP address is
  2088. * <b>suggestion</b>.
  2089. * If this address is different from the one we think we are now, and
  2090. * if our computer doesn't actually know its IP address, then switch. */
  2091. void
  2092. router_new_address_suggestion(const char *suggestion,
  2093. const dir_connection_t *d_conn)
  2094. {
  2095. tor_addr_t addr;
  2096. uint32_t cur = 0; /* Current IPv4 address. */
  2097. const or_options_t *options = get_options();
  2098. /* first, learn what the IP address actually is */
  2099. if (tor_addr_parse(&addr, suggestion) == -1) {
  2100. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  2101. escaped(suggestion));
  2102. return;
  2103. }
  2104. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  2105. if (!server_mode(options)) {
  2106. tor_addr_copy(&last_guessed_ip, &addr);
  2107. return;
  2108. }
  2109. /* XXXX ipv6 */
  2110. cur = get_last_resolved_addr();
  2111. if (cur ||
  2112. resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
  2113. /* We're all set -- we already know our address. Great. */
  2114. tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
  2115. need it later */
  2116. return;
  2117. }
  2118. if (tor_addr_is_internal(&addr, 0)) {
  2119. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  2120. return;
  2121. }
  2122. if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
  2123. /* Don't believe anybody who says our IP is their IP. */
  2124. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  2125. "but they are just reporting their own IP address. Ignoring.",
  2126. suggestion);
  2127. return;
  2128. }
  2129. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  2130. * us an answer different from what we had the last time we managed to
  2131. * resolve it. */
  2132. if (!tor_addr_eq(&last_guessed_ip, &addr)) {
  2133. control_event_server_status(LOG_NOTICE,
  2134. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  2135. suggestion);
  2136. log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
  2137. d_conn->base_.address);
  2138. ip_address_changed(0);
  2139. tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
  2140. will fetch it */
  2141. }
  2142. }
  2143. /** We failed to resolve our address locally, but we'd like to build
  2144. * a descriptor and publish / test reachability. If we have a guess
  2145. * about our address based on directory headers, answer it and return
  2146. * 0; else return -1. */
  2147. static int
  2148. router_guess_address_from_dir_headers(uint32_t *guess)
  2149. {
  2150. if (!tor_addr_is_null(&last_guessed_ip)) {
  2151. *guess = tor_addr_to_ipv4h(&last_guessed_ip);
  2152. return 0;
  2153. }
  2154. return -1;
  2155. }
  2156. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  2157. * string describing the version of Tor and the operating system we're
  2158. * currently running on.
  2159. */
  2160. STATIC void
  2161. get_platform_str(char *platform, size_t len)
  2162. {
  2163. tor_snprintf(platform, len, "Tor %s on %s",
  2164. get_short_version(), get_uname());
  2165. }
  2166. /* XXX need to audit this thing and count fenceposts. maybe
  2167. * refactor so we don't have to keep asking if we're
  2168. * near the end of maxlen?
  2169. */
  2170. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  2171. /** OR only: Given a routerinfo for this router, and an identity key to sign
  2172. * with, encode the routerinfo as a signed server descriptor and return a new
  2173. * string encoding the result, or NULL on failure.
  2174. */
  2175. char *
  2176. router_dump_router_to_string(routerinfo_t *router,
  2177. const crypto_pk_t *ident_key,
  2178. const crypto_pk_t *tap_key,
  2179. const curve25519_keypair_t *ntor_keypair,
  2180. const ed25519_keypair_t *signing_keypair)
  2181. {
  2182. char *address = NULL;
  2183. char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
  2184. crypto_pk_t *rsa_pubkey = NULL;
  2185. char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
  2186. char digest[DIGEST256_LEN];
  2187. char published[ISO_TIME_LEN+1];
  2188. char fingerprint[FINGERPRINT_LEN+1];
  2189. char *extra_info_line = NULL;
  2190. size_t onion_pkeylen, identity_pkeylen;
  2191. char *family_line = NULL;
  2192. char *extra_or_address = NULL;
  2193. const or_options_t *options = get_options();
  2194. smartlist_t *chunks = NULL;
  2195. char *output = NULL;
  2196. const int emit_ed_sigs = signing_keypair &&
  2197. router->cache_info.signing_key_cert;
  2198. char *ed_cert_line = NULL;
  2199. char *rsa_tap_cc_line = NULL;
  2200. char *ntor_cc_line = NULL;
  2201. char *proto_line = NULL;
  2202. /* Make sure the identity key matches the one in the routerinfo. */
  2203. if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
  2204. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  2205. "match router's public key!");
  2206. goto err;
  2207. }
  2208. if (emit_ed_sigs) {
  2209. if (!router->cache_info.signing_key_cert->signing_key_included ||
  2210. !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
  2211. &signing_keypair->pubkey)) {
  2212. log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
  2213. "ed25519 key chain %d",
  2214. router->cache_info.signing_key_cert->signing_key_included);
  2215. goto err;
  2216. }
  2217. }
  2218. /* record our fingerprint, so we can include it in the descriptor */
  2219. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  2220. log_err(LD_BUG,"Error computing fingerprint");
  2221. goto err;
  2222. }
  2223. if (emit_ed_sigs) {
  2224. /* Encode ed25519 signing cert */
  2225. char ed_cert_base64[256];
  2226. char ed_fp_base64[ED25519_BASE64_LEN+1];
  2227. if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
  2228. (const char*)router->cache_info.signing_key_cert->encoded,
  2229. router->cache_info.signing_key_cert->encoded_len,
  2230. BASE64_ENCODE_MULTILINE) < 0) {
  2231. log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
  2232. goto err;
  2233. }
  2234. if (ed25519_public_to_base64(ed_fp_base64,
  2235. &router->cache_info.signing_key_cert->signing_key)<0) {
  2236. log_err(LD_BUG,"Couldn't base64-encode identity key\n");
  2237. goto err;
  2238. }
  2239. tor_asprintf(&ed_cert_line, "identity-ed25519\n"
  2240. "-----BEGIN ED25519 CERT-----\n"
  2241. "%s"
  2242. "-----END ED25519 CERT-----\n"
  2243. "master-key-ed25519 %s\n",
  2244. ed_cert_base64, ed_fp_base64);
  2245. }
  2246. /* PEM-encode the onion key */
  2247. rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
  2248. router->onion_pkey_len);
  2249. if (crypto_pk_write_public_key_to_string(rsa_pubkey,
  2250. &onion_pkey,&onion_pkeylen)<0) {
  2251. log_warn(LD_BUG,"write onion_pkey to string failed!");
  2252. goto err;
  2253. }
  2254. /* PEM-encode the identity key */
  2255. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  2256. &identity_pkey,&identity_pkeylen)<0) {
  2257. log_warn(LD_BUG,"write identity_pkey to string failed!");
  2258. goto err;
  2259. }
  2260. /* Cross-certify with RSA key */
  2261. if (tap_key && router->cache_info.signing_key_cert &&
  2262. router->cache_info.signing_key_cert->signing_key_included) {
  2263. char buf[256];
  2264. int tap_cc_len = 0;
  2265. uint8_t *tap_cc =
  2266. make_tap_onion_key_crosscert(tap_key,
  2267. &router->cache_info.signing_key_cert->signing_key,
  2268. router->identity_pkey,
  2269. &tap_cc_len);
  2270. if (!tap_cc) {
  2271. log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
  2272. goto err;
  2273. }
  2274. if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
  2275. BASE64_ENCODE_MULTILINE) < 0) {
  2276. log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
  2277. tor_free(tap_cc);
  2278. goto err;
  2279. }
  2280. tor_free(tap_cc);
  2281. tor_asprintf(&rsa_tap_cc_line,
  2282. "onion-key-crosscert\n"
  2283. "-----BEGIN CROSSCERT-----\n"
  2284. "%s"
  2285. "-----END CROSSCERT-----\n", buf);
  2286. }
  2287. /* Cross-certify with onion keys */
  2288. if (ntor_keypair && router->cache_info.signing_key_cert &&
  2289. router->cache_info.signing_key_cert->signing_key_included) {
  2290. int sign = 0;
  2291. char buf[256];
  2292. /* XXXX Base the expiration date on the actual onion key expiration time?*/
  2293. tor_cert_t *cert =
  2294. make_ntor_onion_key_crosscert(ntor_keypair,
  2295. &router->cache_info.signing_key_cert->signing_key,
  2296. router->cache_info.published_on,
  2297. get_onion_key_lifetime(), &sign);
  2298. if (!cert) {
  2299. log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
  2300. goto err;
  2301. }
  2302. tor_assert(sign == 0 || sign == 1);
  2303. if (base64_encode(buf, sizeof(buf),
  2304. (const char*)cert->encoded, cert->encoded_len,
  2305. BASE64_ENCODE_MULTILINE)<0) {
  2306. log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
  2307. tor_cert_free(cert);
  2308. goto err;
  2309. }
  2310. tor_cert_free(cert);
  2311. tor_asprintf(&ntor_cc_line,
  2312. "ntor-onion-key-crosscert %d\n"
  2313. "-----BEGIN ED25519 CERT-----\n"
  2314. "%s"
  2315. "-----END ED25519 CERT-----\n", sign, buf);
  2316. }
  2317. /* Encode the publication time. */
  2318. format_iso_time(published, router->cache_info.published_on);
  2319. if (router->declared_family && smartlist_len(router->declared_family)) {
  2320. char *family = smartlist_join_strings(router->declared_family,
  2321. " ", 0, NULL);
  2322. tor_asprintf(&family_line, "family %s\n", family);
  2323. tor_free(family);
  2324. } else {
  2325. family_line = tor_strdup("");
  2326. }
  2327. if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
  2328. char extra_info_digest[HEX_DIGEST_LEN+1];
  2329. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  2330. router->cache_info.extra_info_digest, DIGEST_LEN);
  2331. if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
  2332. char d256_64[BASE64_DIGEST256_LEN+1];
  2333. digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
  2334. tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
  2335. extra_info_digest, d256_64);
  2336. } else {
  2337. tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
  2338. extra_info_digest);
  2339. }
  2340. }
  2341. if (router->ipv6_orport &&
  2342. tor_addr_family(&router->ipv6_addr) == AF_INET6) {
  2343. char addr[TOR_ADDR_BUF_LEN];
  2344. const char *a;
  2345. a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
  2346. if (a) {
  2347. tor_asprintf(&extra_or_address,
  2348. "or-address %s:%d\n", a, router->ipv6_orport);
  2349. log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
  2350. }
  2351. }
  2352. if (router->protocol_list) {
  2353. tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
  2354. } else {
  2355. proto_line = tor_strdup("");
  2356. }
  2357. address = tor_dup_ip(router->addr);
  2358. chunks = smartlist_new();
  2359. /* Generate the easy portion of the router descriptor. */
  2360. smartlist_add_asprintf(chunks,
  2361. "router %s %s %d 0 %d\n"
  2362. "%s"
  2363. "%s"
  2364. "platform %s\n"
  2365. "%s"
  2366. "published %s\n"
  2367. "fingerprint %s\n"
  2368. "uptime %ld\n"
  2369. "bandwidth %d %d %d\n"
  2370. "%s%s"
  2371. "onion-key\n%s"
  2372. "signing-key\n%s"
  2373. "%s%s"
  2374. "%s%s%s",
  2375. router->nickname,
  2376. address,
  2377. router->or_port,
  2378. router_should_advertise_dirport(options, router->dir_port),
  2379. ed_cert_line ? ed_cert_line : "",
  2380. extra_or_address ? extra_or_address : "",
  2381. router->platform,
  2382. proto_line,
  2383. published,
  2384. fingerprint,
  2385. get_uptime(),
  2386. (int) router->bandwidthrate,
  2387. (int) router->bandwidthburst,
  2388. (int) router->bandwidthcapacity,
  2389. extra_info_line ? extra_info_line : "",
  2390. (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
  2391. "caches-extra-info\n" : "",
  2392. onion_pkey, identity_pkey,
  2393. rsa_tap_cc_line ? rsa_tap_cc_line : "",
  2394. ntor_cc_line ? ntor_cc_line : "",
  2395. family_line,
  2396. we_are_hibernating() ? "hibernating 1\n" : "",
  2397. "hidden-service-dir\n");
  2398. if (options->ContactInfo && strlen(options->ContactInfo)) {
  2399. const char *ci = options->ContactInfo;
  2400. if (strchr(ci, '\n') || strchr(ci, '\r'))
  2401. ci = escaped(ci);
  2402. smartlist_add_asprintf(chunks, "contact %s\n", ci);
  2403. }
  2404. if (options->BridgeRelay) {
  2405. const char *bd;
  2406. if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
  2407. bd = options->BridgeDistribution;
  2408. } else {
  2409. bd = "any";
  2410. }
  2411. if (strchr(bd, '\n') || strchr(bd, '\r'))
  2412. bd = escaped(bd);
  2413. smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
  2414. }
  2415. if (router->onion_curve25519_pkey) {
  2416. char kbuf[128];
  2417. base64_encode(kbuf, sizeof(kbuf),
  2418. (const char *)router->onion_curve25519_pkey->public_key,
  2419. CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
  2420. smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
  2421. } else {
  2422. /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
  2423. log_err(LD_BUG, "A relay must have an ntor onion key");
  2424. goto err;
  2425. }
  2426. /* Write the exit policy to the end of 's'. */
  2427. if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
  2428. smartlist_add_strdup(chunks, "reject *:*\n");
  2429. } else if (router->exit_policy) {
  2430. char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
  2431. if (!exit_policy)
  2432. goto err;
  2433. smartlist_add_asprintf(chunks, "%s\n", exit_policy);
  2434. tor_free(exit_policy);
  2435. }
  2436. if (router->ipv6_exit_policy) {
  2437. char *p6 = write_short_policy(router->ipv6_exit_policy);
  2438. if (p6 && strcmp(p6, "reject 1-65535")) {
  2439. smartlist_add_asprintf(chunks,
  2440. "ipv6-policy %s\n", p6);
  2441. }
  2442. tor_free(p6);
  2443. }
  2444. if (router_should_advertise_begindir(options,
  2445. router->supports_tunnelled_dir_requests)) {
  2446. smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
  2447. }
  2448. /* Sign the descriptor with Ed25519 */
  2449. if (emit_ed_sigs) {
  2450. smartlist_add_strdup(chunks, "router-sig-ed25519 ");
  2451. crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
  2452. ED_DESC_SIGNATURE_PREFIX,
  2453. chunks, "", DIGEST_SHA256);
  2454. ed25519_signature_t sig;
  2455. char buf[ED25519_SIG_BASE64_LEN+1];
  2456. if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
  2457. signing_keypair) < 0)
  2458. goto err;
  2459. if (ed25519_signature_to_base64(buf, &sig) < 0)
  2460. goto err;
  2461. smartlist_add_asprintf(chunks, "%s\n", buf);
  2462. }
  2463. /* Sign the descriptor with RSA */
  2464. smartlist_add_strdup(chunks, "router-signature\n");
  2465. crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
  2466. {
  2467. char *sig;
  2468. if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
  2469. log_warn(LD_BUG, "Couldn't sign router descriptor");
  2470. goto err;
  2471. }
  2472. smartlist_add(chunks, sig);
  2473. }
  2474. /* include a last '\n' */
  2475. smartlist_add_strdup(chunks, "\n");
  2476. output = smartlist_join_strings(chunks, "", 0, NULL);
  2477. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  2478. {
  2479. char *s_dup;
  2480. const char *cp;
  2481. routerinfo_t *ri_tmp;
  2482. cp = s_dup = tor_strdup(output);
  2483. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
  2484. if (!ri_tmp) {
  2485. log_err(LD_BUG,
  2486. "We just generated a router descriptor we can't parse.");
  2487. log_err(LD_BUG, "Descriptor was: <<%s>>", output);
  2488. goto err;
  2489. }
  2490. tor_free(s_dup);
  2491. routerinfo_free(ri_tmp);
  2492. }
  2493. #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
  2494. goto done;
  2495. err:
  2496. tor_free(output); /* sets output to NULL */
  2497. done:
  2498. if (chunks) {
  2499. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2500. smartlist_free(chunks);
  2501. }
  2502. crypto_pk_free(rsa_pubkey);
  2503. tor_free(address);
  2504. tor_free(family_line);
  2505. tor_free(onion_pkey);
  2506. tor_free(identity_pkey);
  2507. tor_free(extra_or_address);
  2508. tor_free(ed_cert_line);
  2509. tor_free(rsa_tap_cc_line);
  2510. tor_free(ntor_cc_line);
  2511. tor_free(extra_info_line);
  2512. tor_free(proto_line);
  2513. return output;
  2514. }
  2515. /**
  2516. * OR only: Given <b>router</b>, produce a string with its exit policy.
  2517. * If <b>include_ipv4</b> is true, include IPv4 entries.
  2518. * If <b>include_ipv6</b> is true, include IPv6 entries.
  2519. */
  2520. char *
  2521. router_dump_exit_policy_to_string(const routerinfo_t *router,
  2522. int include_ipv4,
  2523. int include_ipv6)
  2524. {
  2525. if ((!router->exit_policy) || (router->policy_is_reject_star)) {
  2526. return tor_strdup("reject *:*");
  2527. }
  2528. return policy_dump_to_string(router->exit_policy,
  2529. include_ipv4,
  2530. include_ipv6);
  2531. }
  2532. /** Copy the primary (IPv4) OR port (IP address and TCP port) for
  2533. * <b>router</b> into *<b>ap_out</b>. */
  2534. void
  2535. router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  2536. {
  2537. tor_assert(ap_out != NULL);
  2538. tor_addr_from_ipv4h(&ap_out->addr, router->addr);
  2539. ap_out->port = router->or_port;
  2540. }
  2541. /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
  2542. * Otherwise return 0. */
  2543. int
  2544. router_has_addr(const routerinfo_t *router, const tor_addr_t *addr)
  2545. {
  2546. return
  2547. tor_addr_eq_ipv4h(addr, router->addr) ||
  2548. tor_addr_eq(&router->ipv6_addr, addr);
  2549. }
  2550. int
  2551. router_has_orport(const routerinfo_t *router, const tor_addr_port_t *orport)
  2552. {
  2553. return
  2554. (tor_addr_eq_ipv4h(&orport->addr, router->addr) &&
  2555. orport->port == router->or_port) ||
  2556. (tor_addr_eq(&orport->addr, &router->ipv6_addr) &&
  2557. orport->port == router->ipv6_orport);
  2558. }
  2559. /** Load the contents of <b>filename</b>, find the last line starting with
  2560. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  2561. * the past or more than 1 hour in the future with respect to <b>now</b>,
  2562. * and write the file contents starting with that line to *<b>out</b>.
  2563. * Return 1 for success, 0 if the file does not exist or is empty, or -1
  2564. * if the file does not contain a line matching these criteria or other
  2565. * failure. */
  2566. static int
  2567. load_stats_file(const char *filename, const char *end_line, time_t now,
  2568. char **out)
  2569. {
  2570. int r = -1;
  2571. char *fname = get_datadir_fname(filename);
  2572. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  2573. time_t written;
  2574. switch (file_status(fname)) {
  2575. case FN_FILE:
  2576. /* X022 Find an alternative to reading the whole file to memory. */
  2577. if ((contents = read_file_to_str(fname, 0, NULL))) {
  2578. tmp = strstr(contents, end_line);
  2579. /* Find last block starting with end_line */
  2580. while (tmp) {
  2581. start = tmp;
  2582. tmp = strstr(tmp + 1, end_line);
  2583. }
  2584. if (!start)
  2585. goto notfound;
  2586. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  2587. goto notfound;
  2588. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  2589. if (parse_iso_time(timestr, &written) < 0)
  2590. goto notfound;
  2591. if (written < now - (25*60*60) || written > now + (1*60*60))
  2592. goto notfound;
  2593. *out = tor_strdup(start);
  2594. r = 1;
  2595. }
  2596. notfound:
  2597. tor_free(contents);
  2598. break;
  2599. /* treat empty stats files as if the file doesn't exist */
  2600. case FN_NOENT:
  2601. case FN_EMPTY:
  2602. r = 0;
  2603. break;
  2604. case FN_ERROR:
  2605. case FN_DIR:
  2606. default:
  2607. break;
  2608. }
  2609. tor_free(fname);
  2610. return r;
  2611. }
  2612. /** Write the contents of <b>extrainfo</b> and aggregated statistics to
  2613. * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
  2614. * success, negative on failure. */
  2615. int
  2616. extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
  2617. crypto_pk_t *ident_key,
  2618. const ed25519_keypair_t *signing_keypair)
  2619. {
  2620. const or_options_t *options = get_options();
  2621. char identity[HEX_DIGEST_LEN+1];
  2622. char published[ISO_TIME_LEN+1];
  2623. char digest[DIGEST_LEN];
  2624. char *bandwidth_usage;
  2625. int result;
  2626. static int write_stats_to_extrainfo = 1;
  2627. char sig[DIROBJ_MAX_SIG_LEN+1];
  2628. char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
  2629. time_t now = time(NULL);
  2630. smartlist_t *chunks = smartlist_new();
  2631. extrainfo_t *ei_tmp = NULL;
  2632. const int emit_ed_sigs = signing_keypair &&
  2633. extrainfo->cache_info.signing_key_cert;
  2634. char *ed_cert_line = NULL;
  2635. base16_encode(identity, sizeof(identity),
  2636. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  2637. format_iso_time(published, extrainfo->cache_info.published_on);
  2638. bandwidth_usage = rep_hist_get_bandwidth_lines();
  2639. if (emit_ed_sigs) {
  2640. if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
  2641. !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
  2642. &signing_keypair->pubkey)) {
  2643. log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
  2644. "mismatched ed25519 key chain %d",
  2645. extrainfo->cache_info.signing_key_cert->signing_key_included);
  2646. goto err;
  2647. }
  2648. char ed_cert_base64[256];
  2649. if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
  2650. (const char*)extrainfo->cache_info.signing_key_cert->encoded,
  2651. extrainfo->cache_info.signing_key_cert->encoded_len,
  2652. BASE64_ENCODE_MULTILINE) < 0) {
  2653. log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
  2654. goto err;
  2655. }
  2656. tor_asprintf(&ed_cert_line, "identity-ed25519\n"
  2657. "-----BEGIN ED25519 CERT-----\n"
  2658. "%s"
  2659. "-----END ED25519 CERT-----\n", ed_cert_base64);
  2660. } else {
  2661. ed_cert_line = tor_strdup("");
  2662. }
  2663. tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
  2664. extrainfo->nickname, identity,
  2665. ed_cert_line,
  2666. published, bandwidth_usage);
  2667. smartlist_add(chunks, pre);
  2668. if (geoip_is_loaded(AF_INET))
  2669. smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
  2670. geoip_db_digest(AF_INET));
  2671. if (geoip_is_loaded(AF_INET6))
  2672. smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
  2673. geoip_db_digest(AF_INET6));
  2674. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  2675. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  2676. if (options->DirReqStatistics &&
  2677. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  2678. "dirreq-stats-end", now, &contents) > 0) {
  2679. smartlist_add(chunks, contents);
  2680. }
  2681. if (options->HiddenServiceStatistics &&
  2682. load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
  2683. "hidserv-stats-end", now, &contents) > 0) {
  2684. smartlist_add(chunks, contents);
  2685. }
  2686. if (options->EntryStatistics &&
  2687. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  2688. "entry-stats-end", now, &contents) > 0) {
  2689. smartlist_add(chunks, contents);
  2690. }
  2691. if (options->CellStatistics &&
  2692. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  2693. "cell-stats-end", now, &contents) > 0) {
  2694. smartlist_add(chunks, contents);
  2695. }
  2696. if (options->ExitPortStatistics &&
  2697. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  2698. "exit-stats-end", now, &contents) > 0) {
  2699. smartlist_add(chunks, contents);
  2700. }
  2701. if (options->ConnDirectionStatistics &&
  2702. load_stats_file("stats"PATH_SEPARATOR"conn-stats",
  2703. "conn-bi-direct", now, &contents) > 0) {
  2704. smartlist_add(chunks, contents);
  2705. }
  2706. }
  2707. if (options->PaddingStatistics) {
  2708. contents = rep_hist_get_padding_count_lines();
  2709. if (contents)
  2710. smartlist_add(chunks, contents);
  2711. }
  2712. /* Add information about the pluggable transports we support. */
  2713. if (options->ServerTransportPlugin) {
  2714. char *pluggable_transports = pt_get_extra_info_descriptor_string();
  2715. if (pluggable_transports)
  2716. smartlist_add(chunks, pluggable_transports);
  2717. }
  2718. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  2719. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  2720. if (bridge_stats) {
  2721. smartlist_add_strdup(chunks, bridge_stats);
  2722. }
  2723. }
  2724. if (emit_ed_sigs) {
  2725. char sha256_digest[DIGEST256_LEN];
  2726. smartlist_add_strdup(chunks, "router-sig-ed25519 ");
  2727. crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
  2728. ED_DESC_SIGNATURE_PREFIX,
  2729. chunks, "", DIGEST_SHA256);
  2730. ed25519_signature_t ed_sig;
  2731. char buf[ED25519_SIG_BASE64_LEN+1];
  2732. if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
  2733. signing_keypair) < 0)
  2734. goto err;
  2735. if (ed25519_signature_to_base64(buf, &ed_sig) < 0)
  2736. goto err;
  2737. smartlist_add_asprintf(chunks, "%s\n", buf);
  2738. }
  2739. smartlist_add_strdup(chunks, "router-signature\n");
  2740. s = smartlist_join_strings(chunks, "", 0, NULL);
  2741. while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
  2742. /* So long as there are at least two chunks (one for the initial
  2743. * extra-info line and one for the router-signature), we can keep removing
  2744. * things. */
  2745. if (smartlist_len(chunks) > 2) {
  2746. /* We remove the next-to-last element (remember, len-1 is the last
  2747. element), since we need to keep the router-signature element. */
  2748. int idx = smartlist_len(chunks) - 2;
  2749. char *e = smartlist_get(chunks, idx);
  2750. smartlist_del_keeporder(chunks, idx);
  2751. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2752. "with statistics that exceeds the 50 KB "
  2753. "upload limit. Removing last added "
  2754. "statistics.");
  2755. tor_free(e);
  2756. tor_free(s);
  2757. s = smartlist_join_strings(chunks, "", 0, NULL);
  2758. } else {
  2759. log_warn(LD_BUG, "We just generated an extra-info descriptors that "
  2760. "exceeds the 50 KB upload limit.");
  2761. goto err;
  2762. }
  2763. }
  2764. memset(sig, 0, sizeof(sig));
  2765. if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
  2766. router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
  2767. ident_key) < 0) {
  2768. log_warn(LD_BUG, "Could not append signature to extra-info "
  2769. "descriptor.");
  2770. goto err;
  2771. }
  2772. smartlist_add_strdup(chunks, sig);
  2773. tor_free(s);
  2774. s = smartlist_join_strings(chunks, "", 0, NULL);
  2775. cp = s_dup = tor_strdup(s);
  2776. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
  2777. if (!ei_tmp) {
  2778. if (write_stats_to_extrainfo) {
  2779. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2780. "with statistics that we can't parse. Not "
  2781. "adding statistics to this or any future "
  2782. "extra-info descriptors.");
  2783. write_stats_to_extrainfo = 0;
  2784. result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
  2785. signing_keypair);
  2786. goto done;
  2787. } else {
  2788. log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
  2789. "can't parse.");
  2790. goto err;
  2791. }
  2792. }
  2793. *s_out = s;
  2794. s = NULL; /* prevent free */
  2795. result = 0;
  2796. goto done;
  2797. err:
  2798. result = -1;
  2799. done:
  2800. tor_free(s);
  2801. SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
  2802. smartlist_free(chunks);
  2803. tor_free(s_dup);
  2804. tor_free(ed_cert_line);
  2805. extrainfo_free(ei_tmp);
  2806. tor_free(bandwidth_usage);
  2807. return result;
  2808. }
  2809. /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
  2810. * containing between 1 and MAX_NICKNAME_LEN characters from
  2811. * LEGAL_NICKNAME_CHARACTERS.) */
  2812. int
  2813. is_legal_nickname(const char *s)
  2814. {
  2815. size_t len;
  2816. tor_assert(s);
  2817. len = strlen(s);
  2818. return len > 0 && len <= MAX_NICKNAME_LEN &&
  2819. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  2820. }
  2821. /** Return true iff <b>s</b> is a valid server nickname or
  2822. * hex-encoded identity-key digest. */
  2823. int
  2824. is_legal_nickname_or_hexdigest(const char *s)
  2825. {
  2826. if (*s!='$')
  2827. return is_legal_nickname(s);
  2828. else
  2829. return is_legal_hexdigest(s);
  2830. }
  2831. /** Return true iff <b>s</b> is a valid hex-encoded identity-key
  2832. * digest. (That is, an optional $, followed by 40 hex characters,
  2833. * followed by either nothing, or = or ~ followed by a nickname, or
  2834. * a character other than =, ~, or a hex character.)
  2835. */
  2836. int
  2837. is_legal_hexdigest(const char *s)
  2838. {
  2839. size_t len;
  2840. tor_assert(s);
  2841. if (s[0] == '$') s++;
  2842. len = strlen(s);
  2843. if (len > HEX_DIGEST_LEN) {
  2844. if (s[HEX_DIGEST_LEN] == '=' ||
  2845. s[HEX_DIGEST_LEN] == '~') {
  2846. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  2847. return 0;
  2848. } else {
  2849. return 0;
  2850. }
  2851. }
  2852. return (len >= HEX_DIGEST_LEN &&
  2853. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  2854. }
  2855. /**
  2856. * Longest allowed output of format_node_description, plus 1 character for
  2857. * NUL. This allows space for:
  2858. * "$FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF~xxxxxxxxxxxxxxxxxxx at"
  2859. * " [ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255]"
  2860. * plus a terminating NUL.
  2861. */
  2862. #define NODE_DESC_BUF_LEN (MAX_VERBOSE_NICKNAME_LEN+4+TOR_ADDR_BUF_LEN)
  2863. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2864. * hold a human-readable description of a node with identity digest
  2865. * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
  2866. * and address <b>addr</b> or <b>addr32h</b>.
  2867. *
  2868. * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
  2869. * NULL. The <b>addr32h</b> field is optional and may be set to 0.
  2870. *
  2871. * Return a pointer to the front of <b>buf</b>.
  2872. */
  2873. const char *
  2874. format_node_description(char *buf,
  2875. const char *id_digest,
  2876. int is_named,
  2877. const char *nickname,
  2878. const tor_addr_t *addr,
  2879. uint32_t addr32h)
  2880. {
  2881. char *cp;
  2882. if (!buf)
  2883. return "<NULL BUFFER>";
  2884. buf[0] = '$';
  2885. base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  2886. cp = buf+1+HEX_DIGEST_LEN;
  2887. if (nickname) {
  2888. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2889. strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  2890. cp += strlen(cp);
  2891. }
  2892. if (addr32h || addr) {
  2893. memcpy(cp, " at ", 4);
  2894. cp += 4;
  2895. if (addr) {
  2896. tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
  2897. } else {
  2898. struct in_addr in;
  2899. in.s_addr = htonl(addr32h);
  2900. tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
  2901. }
  2902. }
  2903. return buf;
  2904. }
  2905. /** Return a human-readable description of the routerinfo_t <b>ri</b>.
  2906. *
  2907. * This function is not thread-safe. Each call to this function invalidates
  2908. * previous values returned by this function.
  2909. */
  2910. const char *
  2911. router_describe(const routerinfo_t *ri)
  2912. {
  2913. static char buf[NODE_DESC_BUF_LEN];
  2914. if (!ri)
  2915. return "<null>";
  2916. return format_node_description(buf,
  2917. ri->cache_info.identity_digest,
  2918. 0,
  2919. ri->nickname,
  2920. NULL,
  2921. ri->addr);
  2922. }
  2923. /** Return a human-readable description of the node_t <b>node</b>.
  2924. *
  2925. * This function is not thread-safe. Each call to this function invalidates
  2926. * previous values returned by this function.
  2927. */
  2928. const char *
  2929. node_describe(const node_t *node)
  2930. {
  2931. static char buf[NODE_DESC_BUF_LEN];
  2932. const char *nickname = NULL;
  2933. uint32_t addr32h = 0;
  2934. int is_named = 0;
  2935. if (!node)
  2936. return "<null>";
  2937. if (node->rs) {
  2938. nickname = node->rs->nickname;
  2939. is_named = node->rs->is_named;
  2940. addr32h = node->rs->addr;
  2941. } else if (node->ri) {
  2942. nickname = node->ri->nickname;
  2943. addr32h = node->ri->addr;
  2944. }
  2945. return format_node_description(buf,
  2946. node->identity,
  2947. is_named,
  2948. nickname,
  2949. NULL,
  2950. addr32h);
  2951. }
  2952. /** Return a human-readable description of the routerstatus_t <b>rs</b>.
  2953. *
  2954. * This function is not thread-safe. Each call to this function invalidates
  2955. * previous values returned by this function.
  2956. */
  2957. const char *
  2958. routerstatus_describe(const routerstatus_t *rs)
  2959. {
  2960. static char buf[NODE_DESC_BUF_LEN];
  2961. if (!rs)
  2962. return "<null>";
  2963. return format_node_description(buf,
  2964. rs->identity_digest,
  2965. rs->is_named,
  2966. rs->nickname,
  2967. NULL,
  2968. rs->addr);
  2969. }
  2970. /** Return a human-readable description of the extend_info_t <b>ei</b>.
  2971. *
  2972. * This function is not thread-safe. Each call to this function invalidates
  2973. * previous values returned by this function.
  2974. */
  2975. const char *
  2976. extend_info_describe(const extend_info_t *ei)
  2977. {
  2978. static char buf[NODE_DESC_BUF_LEN];
  2979. if (!ei)
  2980. return "<null>";
  2981. return format_node_description(buf,
  2982. ei->identity_digest,
  2983. 0,
  2984. ei->nickname,
  2985. &ei->addr,
  2986. 0);
  2987. }
  2988. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2989. * verbose representation of the identity of <b>router</b>. The format is:
  2990. * A dollar sign.
  2991. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2992. * A "=" if the router is named (no longer implemented); a "~" if it is not.
  2993. * The router's nickname.
  2994. **/
  2995. void
  2996. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  2997. {
  2998. buf[0] = '$';
  2999. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  3000. DIGEST_LEN);
  3001. buf[1+HEX_DIGEST_LEN] = '~';
  3002. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  3003. }
  3004. /** Forget that we have issued any router-related warnings, so that we'll
  3005. * warn again if we see the same errors. */
  3006. void
  3007. router_reset_warnings(void)
  3008. {
  3009. if (warned_nonexistent_family) {
  3010. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  3011. smartlist_clear(warned_nonexistent_family);
  3012. }
  3013. }
  3014. /** Given a router purpose, convert it to a string. Don't call this on
  3015. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  3016. * know its string representation. */
  3017. const char *
  3018. router_purpose_to_string(uint8_t p)
  3019. {
  3020. switch (p)
  3021. {
  3022. case ROUTER_PURPOSE_GENERAL: return "general";
  3023. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  3024. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  3025. default:
  3026. tor_assert(0);
  3027. }
  3028. return NULL;
  3029. }
  3030. /** Given a string, convert it to a router purpose. */
  3031. uint8_t
  3032. router_purpose_from_string(const char *s)
  3033. {
  3034. if (!strcmp(s, "general"))
  3035. return ROUTER_PURPOSE_GENERAL;
  3036. else if (!strcmp(s, "bridge"))
  3037. return ROUTER_PURPOSE_BRIDGE;
  3038. else if (!strcmp(s, "controller"))
  3039. return ROUTER_PURPOSE_CONTROLLER;
  3040. else
  3041. return ROUTER_PURPOSE_UNKNOWN;
  3042. }
  3043. /** Release all static resources held in router.c */
  3044. void
  3045. router_free_all(void)
  3046. {
  3047. crypto_pk_free(onionkey);
  3048. crypto_pk_free(lastonionkey);
  3049. crypto_pk_free(server_identitykey);
  3050. crypto_pk_free(client_identitykey);
  3051. tor_mutex_free(key_lock);
  3052. routerinfo_free(desc_routerinfo);
  3053. extrainfo_free(desc_extrainfo);
  3054. crypto_pk_free(authority_signing_key);
  3055. authority_cert_free(authority_key_certificate);
  3056. crypto_pk_free(legacy_signing_key);
  3057. authority_cert_free(legacy_key_certificate);
  3058. memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
  3059. memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
  3060. if (warned_nonexistent_family) {
  3061. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  3062. smartlist_free(warned_nonexistent_family);
  3063. }
  3064. }
  3065. /** Return a smartlist of tor_addr_port_t's with all the OR ports of
  3066. <b>ri</b>. Note that freeing of the items in the list as well as
  3067. the smartlist itself is the callers responsibility. */
  3068. smartlist_t *
  3069. router_get_all_orports(const routerinfo_t *ri)
  3070. {
  3071. tor_assert(ri);
  3072. node_t fake_node;
  3073. memset(&fake_node, 0, sizeof(fake_node));
  3074. /* we don't modify ri, fake_node is passed as a const node_t *
  3075. */
  3076. fake_node.ri = (routerinfo_t *)ri;
  3077. return node_get_all_orports(&fake_node);
  3078. }
  3079. /* From the given RSA key object, convert it to ASN-1 encoded format and set
  3080. * the newly allocated object in onion_pkey_out. The length of the key is set
  3081. * in onion_pkey_len_out. */
  3082. void
  3083. router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
  3084. size_t *onion_pkey_len_out)
  3085. {
  3086. int len;
  3087. char buf[1024];
  3088. tor_assert(pk);
  3089. tor_assert(onion_pkey_out);
  3090. tor_assert(onion_pkey_len_out);
  3091. len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
  3092. if (BUG(len < 0)) {
  3093. goto done;
  3094. }
  3095. *onion_pkey_out = tor_memdup(buf, len);
  3096. *onion_pkey_len_out = len;
  3097. done:
  3098. return;
  3099. }
  3100. /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
  3101. * It is the caller responsability to free the returned object.
  3102. *
  3103. * Return NULL if the pkey is NULL, malformed or if the length is 0. */
  3104. crypto_pk_t *
  3105. router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
  3106. {
  3107. if (!pkey || pkey_len == 0) {
  3108. return NULL;
  3109. }
  3110. return crypto_pk_asn1_decode(pkey, pkey_len);
  3111. }