router.c 102 KB

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