router.c 108 KB

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