router.c 112 KB

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