router.c 116 KB

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