1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
9 * \brief OR functionality, including key maintenance, generating
10 * and uploading server descriptors, retrying OR connections.
13 extern or_options_t options
; /* command-line and config-file options */
14 extern long stats_n_seconds_uptime
;
16 /** Exposed for test.c. */ void get_platform_str(char *platform
, int len
);
18 /************************************************************/
21 * Key management: ORs only.
24 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
26 static tor_mutex_t
*key_lock
=NULL
;
27 static time_t onionkey_set_at
=0; /* When was onionkey last changed? */
28 static crypto_pk_env_t
*onionkey
=NULL
;
29 static crypto_pk_env_t
*lastonionkey
=NULL
;
30 static crypto_pk_env_t
*identitykey
=NULL
;
32 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
33 * to update onionkey correctly, call rotate_onion_key().
35 void set_onion_key(crypto_pk_env_t
*k
) {
36 tor_mutex_acquire(key_lock
);
38 onionkey_set_at
= time(NULL
);
39 tor_mutex_release(key_lock
);
42 /** Return the current onion key. Requires that the onion key has been
43 * loaded or generated. */
44 crypto_pk_env_t
*get_onion_key(void) {
49 /** Return the onion key that was current before the most recent onion
50 * key rotation. If no rotation has been performed since this process
51 * started, return NULL.
53 crypto_pk_env_t
*get_previous_onion_key(void) {
57 void dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
59 tor_assert(key
&& last
);
60 tor_mutex_acquire(key_lock
);
61 *key
= crypto_pk_dup_key(onionkey
);
63 *last
= crypto_pk_dup_key(lastonionkey
);
66 tor_mutex_release(key_lock
);
69 /** Return the time when the onion key was last set. This is either the time
70 * when the process launched, or the time of the most recent key rotation since
71 * the process launched.
73 time_t get_onion_key_set_at(void) {
74 return onionkey_set_at
;
77 /** Set the current identity key to k.
79 void set_identity_key(crypto_pk_env_t
*k
) {
83 /** Returns the current identity key; requires that the identity key has been
86 crypto_pk_env_t
*get_identity_key(void) {
87 tor_assert(identitykey
);
91 /** Replace the previous onion key with the current onion key, and generate
92 * a new previous onion key. Immediately after calling this function,
94 * - schedule all previous cpuworkers to shut down _after_ processing
95 * pending work. (This will cause fresh cpuworkers to be generated.)
96 * - generate and upload a fresh routerinfo.
98 void rotate_onion_key(void)
101 crypto_pk_env_t
*prkey
;
102 sprintf(fname
,"%s/keys/onion.key",get_data_directory(&options
));
103 if (!(prkey
= crypto_new_pk_env())) {
104 log(LOG_ERR
, "Error creating crypto environment.");
107 if (crypto_pk_generate_key(prkey
)) {
108 log(LOG_ERR
, "Error generating onion key");
111 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
112 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
115 tor_mutex_acquire(key_lock
);
117 crypto_free_pk_env(lastonionkey
);
118 log_fn(LOG_INFO
, "Rotating onion key");
119 lastonionkey
= onionkey
;
120 set_onion_key(prkey
);
121 tor_mutex_release(key_lock
);
124 log_fn(LOG_WARN
, "Couldn't rotate onion key.");
127 /* Read an RSA secret key key from a file that was once named fname_old,
128 * but is now named fname_new. Rename the file from old to new as needed.
130 crypto_pk_env_t
*init_key_from_file_name_changed(const char *fname_old
,
131 const char *fname_new
)
135 fs
= file_status(fname_new
);
137 /* The new filename is there. */
138 return init_key_from_file(fname_new
);
139 fs
= file_status(fname_old
);
141 /* There is no key under either name. */
142 return init_key_from_file(fname_new
);
144 /* The old filename exists, and the new one doesn't. Rename and load. */
145 if (rename(fname_old
, fname_new
) < 0) {
146 log_fn(LOG_ERR
, "Couldn't rename %s to %s: %s", fname_old
, fname_new
,
150 return init_key_from_file(fname_new
);
153 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
154 * create a new RSA key and save it in <b>fname</b>. Return the read/created
155 * key, or NULL on error.
157 crypto_pk_env_t
*init_key_from_file(const char *fname
)
159 crypto_pk_env_t
*prkey
= NULL
;
162 if (!(prkey
= crypto_new_pk_env())) {
163 log(LOG_ERR
, "Error creating crypto environment.");
167 switch(file_status(fname
)) {
170 log(LOG_ERR
, "Can't read key from %s", fname
);
173 log(LOG_INFO
, "No key found in %s; generating fresh key.", fname
);
174 if (crypto_pk_generate_key(prkey
)) {
175 log(LOG_ERR
, "Error generating onion key");
178 if (crypto_pk_check_key(prkey
) <= 0) {
179 log(LOG_ERR
, "Generated key seems invalid");
182 log(LOG_INFO
, "Generated key seems valid");
183 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
184 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
189 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
190 log(LOG_ERR
, "Error loading private key.");
200 crypto_free_pk_env(prkey
);
206 /** Initialize all OR private keys, and the TLS context, as necessary.
207 * On OPs, this only initializes the tls context.
209 int init_keys(void) {
212 char fingerprint
[FINGERPRINT_LEN
+MAX_NICKNAME_LEN
+3];
214 const char *tmp
, *mydesc
, *datadir
;
215 crypto_pk_env_t
*prkey
;
218 key_lock
= tor_mutex_new();
220 /* OP's don't need persistant keys; just make up an identity and
221 * initialize the TLS context. */
222 if (!server_mode()) {
223 tor_assert(!options
.DirPort
);
225 /* XXXX008 enable this once we make ORs tolerate unknown routers. */
226 if (!(prkey
= crypto_new_pk_env()))
228 if (crypto_pk_generate_key(prkey
))
230 set_identity_key(prkey
);
231 if (tor_tls_context_new(get_identity_key(), 1, options
.Nickname
,
232 MAX_SSL_KEY_LIFETIME
) < 0) {
233 log_fn(LOG_ERR
, "Error creating TLS context for OP.");
237 if (tor_tls_context_new(NULL
, 0, NULL
, MAX_SSL_KEY_LIFETIME
)<0) {
238 log_fn(LOG_ERR
, "Error creating TLS context for OP.");
243 /* Make sure DataDirectory exists, and is private. */
244 datadir
= get_data_directory(&options
);
246 if (strlen(datadir
) > (512-128)) {
247 log_fn(LOG_ERR
, "DataDirectory is too long.");
250 if (check_private_dir(datadir
, 1)) {
253 /* Check the key directory. */
254 sprintf(keydir
,"%s/keys", datadir
);
255 if (check_private_dir(keydir
, 1)) {
258 cp
= keydir
+ strlen(keydir
); /* End of string. */
260 /* 1. Read identity key. Make it if none is found. */
261 sprintf(keydir
,"%s/keys/identity.key",datadir
);
262 sprintf(keydir2
,"%s/keys/secret_id_key",datadir
);
263 log_fn(LOG_INFO
,"Reading/making identity key %s...",keydir2
);
264 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
265 if (!prkey
) return -1;
266 set_identity_key(prkey
);
267 /* 2. Read onion key. Make it if none is found. */
268 sprintf(keydir
,"%s/keys/onion.key",datadir
);
269 sprintf(keydir2
,"%s/keys/secret_onion_key",datadir
);
270 log_fn(LOG_INFO
,"Reading/making onion key %s...",keydir2
);
271 prkey
= init_key_from_file_name_changed(keydir
,keydir2
);
272 if (!prkey
) return -1;
273 set_onion_key(prkey
);
275 /* 3. Initialize link key and TLS context. */
276 if (tor_tls_context_new(get_identity_key(), 1, options
.Nickname
,
277 MAX_SSL_KEY_LIFETIME
) < 0) {
278 log_fn(LOG_ERR
, "Error initializing TLS context");
281 /* 4. Dump router descriptor to 'router.desc' */
282 /* Must be called after keys are initialized. */
283 tmp
= mydesc
= router_get_my_descriptor();
285 log_fn(LOG_ERR
, "Error initializing descriptor.");
289 /* We need to add our own fingerprint so it gets recognized. */
290 if (dirserv_add_own_fingerprint(options
.Nickname
, get_identity_key())) {
291 log_fn(LOG_ERR
, "Error adding own fingerprint to approved set");
294 if (dirserv_add_descriptor(&tmp
) != 1) {
295 log(LOG_ERR
, "Unable to add own descriptor to directory.");
300 sprintf(keydir
,"%s/router.desc", datadir
);
301 log_fn(LOG_INFO
,"Dumping descriptor to %s...",keydir
);
302 if (write_str_to_file(keydir
, mydesc
)) {
305 /* 5. Dump fingerprint to 'fingerprint' */
306 sprintf(keydir
,"%s/fingerprint", datadir
);
307 log_fn(LOG_INFO
,"Dumping fingerprint to %s...",keydir
);
308 tor_assert(strlen(options
.Nickname
) <= MAX_NICKNAME_LEN
);
309 strcpy(fingerprint
, options
.Nickname
);
310 strcat(fingerprint
, " ");
311 if (crypto_pk_get_fingerprint(get_identity_key(),
312 fingerprint
+strlen(fingerprint
))<0) {
313 log_fn(LOG_ERR
, "Error computing fingerprint");
316 strcat(fingerprint
, "\n");
317 if (write_str_to_file(keydir
, fingerprint
))
321 /* 6. [authdirserver only] load approved-routers file */
322 sprintf(keydir
,"%s/approved-routers", datadir
);
323 log_fn(LOG_INFO
,"Loading approved fingerprints from %s...",keydir
);
324 if(dirserv_parse_fingerprint_file(keydir
) < 0) {
325 log_fn(LOG_ERR
, "Error loading fingerprints");
328 /* 7. [authdirserver only] load old directory, if it's there */
329 sprintf(keydir
,"%s/cached-directory", datadir
);
330 log_fn(LOG_INFO
,"Loading cached directory from %s...",keydir
);
331 cp
= read_file_to_str(keydir
);
333 log_fn(LOG_INFO
,"Cached directory %s not present. Ok.",keydir
);
335 if(dirserv_load_from_directory_string(cp
) < 0){
336 log_fn(LOG_ERR
, "Cached directory %s is corrupt", keydir
);
350 /** OR only: try to open connections to all of the other ORs we know about.
352 void router_retry_connections(void) {
354 routerinfo_t
*router
;
357 router_get_routerlist(&rl
);
358 for (i
=0;i
< smartlist_len(rl
->routers
);i
++) {
359 router
= smartlist_get(rl
->routers
, i
);
360 if(router_is_me(router
))
362 if(!connection_get_by_identity_digest(router
->identity_digest
,
364 /* not in the list */
365 log_fn(LOG_DEBUG
,"connecting to OR %s:%u.",router
->address
,router
->or_port
);
366 connection_or_connect(router
->addr
, router
->or_port
, router
->identity_digest
);
372 * OR descriptor generation.
375 /** My routerinfo. */
376 static routerinfo_t
*desc_routerinfo
= NULL
;
377 /** String representation of my descriptor, signed by me. */
378 static char descriptor
[8192];
380 /** OR only: try to upload our signed descriptor to all the directory servers
383 void router_upload_dir_desc_to_dirservers(void) {
386 s
= router_get_my_descriptor();
388 log_fn(LOG_WARN
, "No descriptor; skipping upload");
391 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
, s
, strlen(s
));
394 #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,accept *:20-22,accept *:53,accept *:79-81,accept *:110,accept *:143,accept *:443,accept *:873,accept *:993,accept *:995,accept *:1024-65535,reject *:*"
396 /** Set the exit policy on <b>router</b> to match the exit policy in the
397 * current configuration file. If the exit policy doesn't have a catch-all
398 * rule, then append the default exit policy as well.
400 static void router_add_exit_policy_from_config(routerinfo_t
*router
) {
401 struct exit_policy_t
*ep
;
402 struct config_line_t default_policy
;
403 config_parse_exit_policy(options
.ExitPolicy
, &router
->exit_policy
);
405 for (ep
= router
->exit_policy
; ep
; ep
= ep
->next
) {
406 if (ep
->msk
== 0 && ep
->prt_min
<= 1 && ep
->prt_max
>= 65535) {
407 /* if exitpolicy includes a *:* line, then we're done. */
412 /* Else, append the default exitpolicy. */
413 default_policy
.key
= NULL
;
414 default_policy
.value
= DEFAULT_EXIT_POLICY
;
415 default_policy
.next
= NULL
;
416 config_parse_exit_policy(&default_policy
, &router
->exit_policy
);
419 /** OR only: Return false if my exit policy says to allow connection to
420 * conn. Else return true.
422 int router_compare_to_my_exit_policy(connection_t
*conn
)
424 tor_assert(desc_routerinfo
);
426 /* make sure it's resolved to something. this way we can't get a
431 return router_compare_addr_to_exit_policy(conn
->addr
, conn
->port
,
432 desc_routerinfo
->exit_policy
);
436 /** Return true iff <b>router</b> has the same nickname as this OR. (For an
437 * OP, always returns false.)
439 int router_is_me(routerinfo_t
*router
)
442 /* XXXX008 should compare identity instead? */
443 return options
.Nickname
&& !strcasecmp(router
->nickname
, options
.Nickname
);
446 /** Return a routerinfo for this OR, rebuilding a fresh one if
447 * necessary. Return NULL on error, or if called on an OP. */
448 routerinfo_t
*router_get_my_routerinfo(void)
453 if (!desc_routerinfo
) {
454 if (router_rebuild_descriptor())
457 return desc_routerinfo
;
460 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
461 * one if necessary. Return NULL on error.
463 const char *router_get_my_descriptor(void) {
464 if (!desc_routerinfo
) {
465 if (router_rebuild_descriptor())
468 log_fn(LOG_DEBUG
,"my desc is '%s'",descriptor
);
472 /** Rebuild a fresh routerinfo and signed server descriptor for this
473 * OR. Return 0 on success, -1 on error.
475 int router_rebuild_descriptor(void) {
479 if (!tor_inet_aton(options
.Address
, &addr
)) {
480 log_fn(LOG_ERR
, "options.Address didn't hold an IP.");
484 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
485 ri
->address
= tor_strdup(options
.Address
);
486 ri
->nickname
= tor_strdup(options
.Nickname
);
487 ri
->addr
= (uint32_t) ntohl(addr
.s_addr
);
488 ri
->or_port
= options
.ORPort
;
489 ri
->socks_port
= options
.SocksPort
;
490 ri
->dir_port
= options
.DirPort
;
491 ri
->published_on
= time(NULL
);
492 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
493 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
494 if (crypto_pk_get_digest(ri
->identity_pkey
, ri
->identity_digest
)<0) {
498 get_platform_str(platform
, sizeof(platform
));
499 ri
->platform
= tor_strdup(platform
);
500 ri
->bandwidthrate
= options
.BandwidthRate
;
501 ri
->bandwidthburst
= options
.BandwidthBurst
;
502 ri
->exit_policy
= NULL
; /* zero it out first */
503 router_add_exit_policy_from_config(ri
);
505 routerinfo_free(desc_routerinfo
);
506 desc_routerinfo
= ri
;
507 if (router_dump_router_to_string(descriptor
, 8192, ri
, get_identity_key())<0) {
508 log_fn(LOG_WARN
, "Couldn't dump router to string.");
511 /* XXX008 NM: no, we shouldn't just blindly assume we're an
512 * authdirserver just because our dir_port is set. We should
513 * take these next two lines out, and then set our is_trusted_dir
514 * variable if we find ourselves in the dirservers file. Yes/no? */
516 ri
->is_trusted_dir
= 1;
520 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
521 * string describing the version of Tor and the operating system we're
522 * currently running on.
524 void get_platform_str(char *platform
, int len
)
526 snprintf(platform
, len
-1, "Tor %s (up %ld sec) on %s",
527 VERSION
, stats_n_seconds_uptime
, get_uname());
528 platform
[len
-1] = '\0';
532 /* XXX need to audit this thing and count fenceposts. maybe
533 * refactor so we don't have to keep asking if we're
534 * near the end of maxlen?
536 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
538 /** OR only: Given a routerinfo for this router, and an identity key to sign
539 * with, encode the routerinfo as a signed server descriptor and write the
540 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
541 * failure, and the number of bytes used on success.
543 int router_dump_router_to_string(char *s
, int maxlen
, routerinfo_t
*router
,
544 crypto_pk_env_t
*ident_key
) {
545 char *onion_pkey
; /* Onion key, PEM-encoded. */
546 char *identity_pkey
; /* Identity key, PEM-encoded. */
551 int onion_pkeylen
, identity_pkeylen
;
554 struct exit_policy_t
*tmpe
;
555 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
558 routerinfo_t
*ri_tmp
;
561 /* Make sure the identity key matches the one in the routerinfo. */
562 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
563 log_fn(LOG_WARN
,"Tried to sign a router with a private key that didn't match router's public key!");
567 /* PEM-encode the onion key */
568 if(crypto_pk_write_public_key_to_string(router
->onion_pkey
,
569 &onion_pkey
,&onion_pkeylen
)<0) {
570 log_fn(LOG_WARN
,"write onion_pkey to string failed!");
574 /* PEM-encode the identity key key */
575 if(crypto_pk_write_public_key_to_string(router
->identity_pkey
,
576 &identity_pkey
,&identity_pkeylen
)<0) {
577 log_fn(LOG_WARN
,"write identity_pkey to string failed!");
578 tor_free(onion_pkey
);
582 /* Encode the publication time. */
583 strftime(published
, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router
->published_on
));
585 /* Generate the easy portion of the router descriptor. */
586 result
= snprintf(s
, maxlen
,
587 "router %s %s %d %d %d\n"
590 "bandwidth %d %d %d\n"
597 /* Due to an 0.0.7 bug, we can't actually say that we have a dirport unles
598 * we're an authoritative directory.
600 router
->is_trusted_dir
? router
->dir_port
: 0,
603 (int) router
->bandwidthrate
,
604 (int) router
->bandwidthburst
,
605 (int) router
->advertisedbandwidth
,
606 onion_pkey
, identity_pkey
);
608 tor_free(onion_pkey
);
609 tor_free(identity_pkey
);
611 if(result
< 0 || result
>= maxlen
) {
612 /* apparently different glibcs do different things on snprintf error.. so check both */
615 /* From now on, we use 'written' to remember the current length of 's'. */
618 if (router
->dir_port
&& !router
->is_trusted_dir
) {
619 /* dircacheport wasn't recognized before 0.0.8pre. (When 0.0.7 is gone,
620 * we can fold this back into dirport anyway.) */
621 result
= snprintf(s
+written
,maxlen
-written
, "opt dircacheport %d\n",
623 if (result
<0 || result
+written
> maxlen
)
628 if (options
.ContactInfo
&& strlen(options
.ContactInfo
)) {
629 result
= snprintf(s
+written
,maxlen
-written
, "opt contact %s\n",
630 options
.ContactInfo
);
631 if (result
<0 || result
+written
> maxlen
)
636 /* Write the exit policy to the end of 's'. */
637 for(tmpe
=router
->exit_policy
; tmpe
; tmpe
=tmpe
->next
) {
638 in
.s_addr
= htonl(tmpe
->addr
);
639 /* Write: "accept 1.2.3.4" */
640 result
= snprintf(s
+written
, maxlen
-written
, "%s %s",
641 tmpe
->policy_type
== EXIT_POLICY_ACCEPT
? "accept" : "reject",
642 tmpe
->msk
== 0 ? "*" : inet_ntoa(in
));
643 if(result
< 0 || result
+written
> maxlen
) {
644 /* apparently different glibcs do different things on snprintf error.. so check both */
648 if (tmpe
->msk
!= 0xFFFFFFFFu
&& tmpe
->msk
!= 0) {
649 /* Write "/255.255.0.0" */
650 in
.s_addr
= htonl(tmpe
->msk
);
651 result
= snprintf(s
+written
, maxlen
-written
, "/%s", inet_ntoa(in
));
652 if (result
<0 || result
+written
> maxlen
)
656 if (tmpe
->prt_min
== 0 && tmpe
->prt_max
== 65535) {
657 /* There is no port set; write ":*" */
658 if (written
> maxlen
-4)
660 strcat(s
+written
, ":*\n");
662 } else if (tmpe
->prt_min
== tmpe
->prt_max
) {
663 /* There is only one port; write ":80". */
664 result
= snprintf(s
+written
, maxlen
-written
, ":%d\n", tmpe
->prt_min
);
665 if (result
<0 || result
+written
> maxlen
)
669 /* There is a range of ports; write ":79-80". */
670 result
= snprintf(s
+written
, maxlen
-written
, ":%d-%d\n", tmpe
->prt_min
,
672 if (result
<0 || result
+written
> maxlen
)
677 if (written
> maxlen
-256) /* Not enough room for signature. */
680 /* Sign the directory */
681 strcat(s
+written
, "router-signature\n");
682 written
+= strlen(s
+written
);
684 if (router_get_router_hash(s
, digest
) < 0)
687 if (crypto_pk_private_sign(ident_key
, digest
, 20, signature
) < 0) {
688 log_fn(LOG_WARN
, "Error signing digest");
691 strcat(s
+written
, "-----BEGIN SIGNATURE-----\n");
692 written
+= strlen(s
+written
);
693 if (base64_encode(s
+written
, maxlen
-written
, signature
, 128) < 0) {
694 log_fn(LOG_WARN
, "Couldn't base64-encode signature");
697 written
+= strlen(s
+written
);
698 strcat(s
+written
, "-----END SIGNATURE-----\n");
699 written
+= strlen(s
+written
);
701 if (written
> maxlen
-2)
703 /* include a last '\n' */
707 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
708 cp
= s_tmp
= s_dup
= tor_strdup(s
);
709 ri_tmp
= router_parse_entry_from_string(cp
, NULL
);
711 log_fn(LOG_ERR
, "We just generated a router descriptor we can't parse: <<%s>>",
716 routerinfo_free(ri_tmp
);