router.c 108 KB

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