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