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 */
15 /** Exposed for test.c. */ void get_platform_str(char *platform
, int len
);
17 /************************************************************/
20 * Key management: ORs only.
23 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
25 static tor_mutex_t
*key_lock
=NULL
;
26 static time_t onionkey_set_at
=0; /* When was onionkey last changed? */
27 static crypto_pk_env_t
*onionkey
=NULL
;
28 static crypto_pk_env_t
*lastonionkey
=NULL
;
29 static crypto_pk_env_t
*identitykey
=NULL
;
31 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
32 * to update onionkey correctly, call rotate_onion_key().
34 void set_onion_key(crypto_pk_env_t
*k
) {
35 tor_mutex_acquire(key_lock
);
37 onionkey_set_at
= time(NULL
);
38 tor_mutex_release(key_lock
);
41 /** Return the current onion key. Requires that the onion key has been
42 * loaded or generated. */
43 crypto_pk_env_t
*get_onion_key(void) {
48 /** Return the onion key that was current before the most recent onion
49 * key rotation. If no rotation has been performed since this process
50 * started, return NULL.
52 crypto_pk_env_t
*get_previous_onion_key(void) {
56 void dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
58 tor_assert(key
&& last
);
59 tor_mutex_acquire(key_lock
);
60 *key
= crypto_pk_dup_key(onionkey
);
62 *last
= crypto_pk_dup_key(lastonionkey
);
65 tor_mutex_release(key_lock
);
68 /** Return the time when the onion key was last set. This is either the time
69 * when the process launched, or the time of the most recent key rotation since
70 * the process launched.
72 time_t get_onion_key_set_at(void) {
73 return onionkey_set_at
;
76 /** Set the current identity key to k.
78 void set_identity_key(crypto_pk_env_t
*k
) {
82 /** Returns the current identity key; requires that the identity key has been
85 crypto_pk_env_t
*get_identity_key(void) {
86 tor_assert(identitykey
);
90 /** Replace the previous onion key with the current onion key, and generate
91 * a new previous onion key. Immediately after calling this function,
93 * - schedule all previous cpuworkers to shut down _after_ processing
94 * pending work. (This will cause fresh cpuworkers to be generated.)
95 * - generate and upload a fresh routerinfo.
97 void rotate_onion_key(void)
100 crypto_pk_env_t
*prkey
;
101 sprintf(fname
,"%s/keys/onion.key",options
.DataDirectory
);
102 if (!(prkey
= crypto_new_pk_env())) {
103 log(LOG_ERR
, "Error creating crypto environment.");
106 if (crypto_pk_generate_key(prkey
)) {
107 log(LOG_ERR
, "Error generating onion key");
110 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
111 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
114 tor_mutex_acquire(key_lock
);
116 crypto_free_pk_env(lastonionkey
);
117 log_fn(LOG_INFO
, "Rotating onion key");
118 lastonionkey
= onionkey
;
119 set_onion_key(prkey
);
120 tor_mutex_release(key_lock
);
123 log_fn(LOG_WARN
, "Couldn't rotate onion key.");
126 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
127 * create a new RSA key and save it in <b>fname</b>. Return the read/created
128 * key, or NULL on error.
130 crypto_pk_env_t
*init_key_from_file(const char *fname
)
132 crypto_pk_env_t
*prkey
= NULL
;
135 if (!(prkey
= crypto_new_pk_env())) {
136 log(LOG_ERR
, "Error creating crypto environment.");
140 switch(file_status(fname
)) {
143 log(LOG_ERR
, "Can't read key from %s", fname
);
146 log(LOG_INFO
, "No key found in %s; generating fresh key.", fname
);
147 if (crypto_pk_generate_key(prkey
)) {
148 log(LOG_ERR
, "Error generating onion key");
151 if (crypto_pk_check_key(prkey
) <= 0) {
152 log(LOG_ERR
, "Generated key seems invalid");
155 log(LOG_INFO
, "Generated key seems valid");
156 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
157 log(LOG_ERR
, "Couldn't write generated key to %s.", fname
);
162 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
163 log(LOG_ERR
, "Error loading private key.");
173 crypto_free_pk_env(prkey
);
179 /** Initialize all OR private keys, and the TLS context, as necessary.
180 * On OPs, this only initializes the tls context.
182 int init_keys(void) {
184 char fingerprint
[FINGERPRINT_LEN
+MAX_NICKNAME_LEN
+3];
186 const char *tmp
, *mydesc
;
187 crypto_pk_env_t
*prkey
;
190 key_lock
= tor_mutex_new();
192 /* OP's don't need keys. Just initialize the TLS context.*/
193 if (!options
.ORPort
) {
194 tor_assert(!options
.DirPort
);
195 if (tor_tls_context_new(NULL
, 0, NULL
, 0)<0) {
196 log_fn(LOG_ERR
, "Error creating TLS context for OP.");
201 /* Make sure DataDirectory exists, and is private. */
202 tor_assert(options
.DataDirectory
);
203 if (strlen(options
.DataDirectory
) > (512-128)) {
204 log_fn(LOG_ERR
, "DataDirectory is too long.");
207 if (check_private_dir(options
.DataDirectory
, 1)) {
210 /* Check the key directory. */
211 sprintf(keydir
,"%s/keys",options
.DataDirectory
);
212 if (check_private_dir(keydir
, 1)) {
215 cp
= keydir
+ strlen(keydir
); /* End of string. */
217 /* 1. Read identity key. Make it if none is found. */
218 strcpy(cp
, "/identity.key");
219 log_fn(LOG_INFO
,"Reading/making identity key %s...",keydir
);
220 prkey
= init_key_from_file(keydir
);
221 if (!prkey
) return -1;
222 set_identity_key(prkey
);
223 /* 2. Read onion key. Make it if none is found. */
224 strcpy(cp
, "/onion.key");
225 log_fn(LOG_INFO
,"Reading/making onion key %s...",keydir
);
226 prkey
= init_key_from_file(keydir
);
227 if (!prkey
) return -1;
228 set_onion_key(prkey
);
230 /* 3. Initialize link key and TLS context. */
231 if (tor_tls_context_new(get_identity_key(), 1, options
.Nickname
,
232 MAX_SSL_KEY_LIFETIME
) < 0) {
233 log_fn(LOG_ERR
, "Error initializing TLS context");
236 /* 4. Dump router descriptor to 'router.desc' */
237 /* Must be called after keys are initialized. */
238 if (!(router_get_my_descriptor())) {
239 log_fn(LOG_ERR
, "Error initializing descriptor.");
242 /* We need to add our own fingerprint so it gets recognized. */
243 if (dirserv_add_own_fingerprint(options
.Nickname
, get_identity_key())) {
244 log_fn(LOG_ERR
, "Error adding own fingerprint to approved set");
247 tmp
= mydesc
= router_get_my_descriptor();
248 if (dirserv_add_descriptor(&tmp
) != 1) {
249 log(LOG_ERR
, "Unable to add own descriptor to directory.");
252 sprintf(keydir
,"%s/router.desc", options
.DataDirectory
);
253 log_fn(LOG_INFO
,"Dumping descriptor to %s...",keydir
);
254 if (write_str_to_file(keydir
, mydesc
)) {
257 /* 5. Dump fingerprint to 'fingerprint' */
258 sprintf(keydir
,"%s/fingerprint", options
.DataDirectory
);
259 log_fn(LOG_INFO
,"Dumping fingerprint to %s...",keydir
);
260 tor_assert(strlen(options
.Nickname
) <= MAX_NICKNAME_LEN
);
261 strcpy(fingerprint
, options
.Nickname
);
262 strcat(fingerprint
, " ");
263 if (crypto_pk_get_fingerprint(get_identity_key(),
264 fingerprint
+strlen(fingerprint
))<0) {
265 log_fn(LOG_ERR
, "Error computing fingerprint");
268 strcat(fingerprint
, "\n");
269 if (write_str_to_file(keydir
, fingerprint
))
273 /* 6. [dirserver only] load approved-routers file */
274 sprintf(keydir
,"%s/approved-routers", options
.DataDirectory
);
275 log_fn(LOG_INFO
,"Loading approved fingerprints from %s...",keydir
);
276 if(dirserv_parse_fingerprint_file(keydir
) < 0) {
277 log_fn(LOG_ERR
, "Error loading fingerprints");
280 /* 7. [dirserver only] load old directory, if it's there */
281 sprintf(keydir
,"%s/cached-directory", options
.DataDirectory
);
282 log_fn(LOG_INFO
,"Loading cached directory from %s...",keydir
);
283 cp
= read_file_to_str(keydir
);
285 log_fn(LOG_INFO
,"Cached directory %s not present. Ok.",keydir
);
287 if(dirserv_init_from_directory_string(cp
) < 0) {
288 log_fn(LOG_ERR
, "Cached directory %s is corrupt", keydir
);
302 /** OR only: try to open connections to all of the other ORs we know about.
304 void router_retry_connections(void) {
306 routerinfo_t
*router
;
309 router_get_routerlist(&rl
);
310 for (i
=0;i
< smartlist_len(rl
->routers
);i
++) {
311 router
= smartlist_get(rl
->routers
, i
);
312 if(router_is_me(router
))
314 if(!connection_exact_get_by_addr_port(router
->addr
,router
->or_port
)) {
315 /* not in the list */
316 log_fn(LOG_DEBUG
,"connecting to OR %s:%u.",router
->address
,router
->or_port
);
317 connection_or_connect(router
);
323 * OR descriptor generation.
326 /** My routerinfo. */
327 static routerinfo_t
*desc_routerinfo
= NULL
;
328 /** String representation of my descriptor, signed by me. */
329 static char descriptor
[8192];
331 /** OR only: try to upload our signed descriptor to all the directory servers
334 void router_upload_dir_desc_to_dirservers(void) {
337 s
= router_get_my_descriptor();
339 log_fn(LOG_WARN
, "No descriptor; skipping upload");
342 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
, s
, strlen(s
));
345 #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 *:*"
347 /** Set the exit policy on <b>router</b> to match the exit policy in the
348 * current configuration file. If the exit policy doesn't have a catch-all
349 * rule, then append the default exit policy as well.
351 static void router_add_exit_policy_from_config(routerinfo_t
*router
) {
352 struct exit_policy_t
*ep
;
353 struct config_line_t default_policy
;
354 config_parse_exit_policy(options
.ExitPolicy
, &router
->exit_policy
);
356 for (ep
= router
->exit_policy
; ep
; ep
= ep
->next
) {
357 if (ep
->msk
== 0 && ep
->prt_min
<= 1 && ep
->prt_max
>= 65535) {
358 /* if exitpolicy includes a *:* line, then we're done. */
363 /* Else, append the default exitpolicy. */
364 default_policy
.key
= NULL
;
365 default_policy
.value
= DEFAULT_EXIT_POLICY
;
366 default_policy
.next
= NULL
;
367 config_parse_exit_policy(&default_policy
, &router
->exit_policy
);
370 /** OR only: Return false if my exit policy says to allow connection to
371 * conn. Else return true.
373 int router_compare_to_my_exit_policy(connection_t
*conn
)
375 tor_assert(desc_routerinfo
);
376 tor_assert(conn
->addr
); /* make sure it's resolved to something. this
377 way we can't get a 'maybe' below. */
379 return router_compare_addr_to_exit_policy(conn
->addr
, conn
->port
,
380 desc_routerinfo
->exit_policy
);
384 /** Return true iff <b>router</b> has the same nickname as this OR. (For an
385 * OP, always returns false.)
387 int router_is_me(routerinfo_t
*router
)
390 return options
.Nickname
&& !strcasecmp(router
->nickname
, options
.Nickname
);
393 /** Return a routerinfo for this OR, rebuilding a fresh one if
394 * necessary. Return NULL on error, or if called on an OP. */
395 routerinfo_t
*router_get_my_routerinfo(void)
400 if (!desc_routerinfo
) {
401 if (router_rebuild_descriptor())
404 return desc_routerinfo
;
407 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
408 * one if necessary. Return NULL on error.
410 const char *router_get_my_descriptor(void) {
411 if (!desc_routerinfo
) {
412 if (router_rebuild_descriptor())
415 log_fn(LOG_DEBUG
,"my desc is '%s'",descriptor
);
419 /** Rebuild a fresh routerinfo and signed server descriptor for this
420 * OR. Return 0 on success, -1 on error.
422 int router_rebuild_descriptor(void) {
426 if (!tor_inet_aton(options
.Address
, &addr
)) {
427 log_fn(LOG_ERR
, "options.Address didn't hold an IP.");
431 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
432 ri
->address
= tor_strdup(options
.Address
);
433 ri
->nickname
= tor_strdup(options
.Nickname
);
434 ri
->addr
= (uint32_t) ntohl(addr
.s_addr
);
435 ri
->or_port
= options
.ORPort
;
436 ri
->socks_port
= options
.SocksPort
;
437 ri
->dir_port
= options
.DirPort
;
438 ri
->published_on
= time(NULL
);
439 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
440 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
441 get_platform_str(platform
, sizeof(platform
));
442 ri
->platform
= tor_strdup(platform
);
443 ri
->bandwidthrate
= options
.BandwidthRate
;
444 ri
->bandwidthburst
= options
.BandwidthBurst
;
445 ri
->exit_policy
= NULL
; /* zero it out first */
446 router_add_exit_policy_from_config(ri
);
448 routerinfo_free(desc_routerinfo
);
449 desc_routerinfo
= ri
;
450 if (router_dump_router_to_string(descriptor
, 8192, ri
, get_identity_key())<0) {
451 log_fn(LOG_WARN
, "Couldn't dump router to string.");
455 ri
->is_trusted_dir
= 1;
459 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
460 * string describing the version of Tor and the operating system we're
461 * currently running on.
463 void get_platform_str(char *platform
, int len
)
465 snprintf(platform
, len
-1, "Tor %s on %s", VERSION
, get_uname());
466 platform
[len
-1] = '\0';
470 /* XXX need to audit this thing and count fenceposts. maybe
471 * refactor so we don't have to keep asking if we're
472 * near the end of maxlen?
474 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
476 /** OR only: Given a routerinfo for this router, and an identity key to sign
477 * with, encode the routerinfo as a signed server descriptor and write the
478 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
479 * failure, and the number of bytes used on success.
481 int router_dump_router_to_string(char *s
, int maxlen
, routerinfo_t
*router
,
482 crypto_pk_env_t
*ident_key
) {
483 char *onion_pkey
; /* Onion key, PEM-encoded. */
484 char *identity_pkey
; /* Identity key, PEM-encoded. */
489 int onion_pkeylen
, identity_pkeylen
;
492 struct exit_policy_t
*tmpe
;
493 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
496 routerinfo_t
*ri_tmp
;
499 /* Make sure the identity key matches the one in the routerinfo. */
500 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
501 log_fn(LOG_WARN
,"Tried to sign a router with a private key that didn't match router's public key!");
505 /* PEM-encode the onion key */
506 if(crypto_pk_write_public_key_to_string(router
->onion_pkey
,
507 &onion_pkey
,&onion_pkeylen
)<0) {
508 log_fn(LOG_WARN
,"write onion_pkey to string failed!");
512 /* PEM-encode the identity key key */
513 if(crypto_pk_write_public_key_to_string(router
->identity_pkey
,
514 &identity_pkey
,&identity_pkeylen
)<0) {
515 log_fn(LOG_WARN
,"write identity_pkey to string failed!");
516 tor_free(onion_pkey
);
520 /* Encode the publication time. */
521 strftime(published
, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router
->published_on
));
523 /* Generate the easy portion of the router descriptor. */
524 result
= snprintf(s
, maxlen
,
525 "router %s %s %d %d %d\n"
538 (int) router
->bandwidthrate
,
539 (int) router
->bandwidthburst
,
540 onion_pkey
, identity_pkey
);
542 tor_free(onion_pkey
);
543 tor_free(identity_pkey
);
545 if(result
< 0 || result
>= maxlen
) {
546 /* apparently different glibcs do different things on snprintf error.. so check both */
549 /* From now on, we use 'written' to remember the current length of 's'. */
552 /* Write the exit policy to the end of 's'. */
553 for(tmpe
=router
->exit_policy
; tmpe
; tmpe
=tmpe
->next
) {
554 in
.s_addr
= htonl(tmpe
->addr
);
555 /* Write: "accept 1.2.3.4" */
556 result
= snprintf(s
+written
, maxlen
-written
, "%s %s",
557 tmpe
->policy_type
== EXIT_POLICY_ACCEPT
? "accept" : "reject",
558 tmpe
->msk
== 0 ? "*" : inet_ntoa(in
));
559 if(result
< 0 || result
+written
> maxlen
) {
560 /* apparently different glibcs do different things on snprintf error.. so check both */
564 if (tmpe
->msk
!= 0xFFFFFFFFu
&& tmpe
->msk
!= 0) {
565 /* Write "/255.255.0.0" */
566 in
.s_addr
= htonl(tmpe
->msk
);
567 result
= snprintf(s
+written
, maxlen
-written
, "/%s", inet_ntoa(in
));
568 if (result
<0 || result
+written
> maxlen
)
572 if (tmpe
->prt_min
== 0 && tmpe
->prt_max
== 65535) {
573 /* There is no port set; write ":*" */
574 if (written
> maxlen
-4)
576 strcat(s
+written
, ":*\n");
578 } else if (tmpe
->prt_min
== tmpe
->prt_max
) {
579 /* There is only one port; write ":80". */
580 result
= snprintf(s
+written
, maxlen
-written
, ":%d\n", tmpe
->prt_min
);
581 if (result
<0 || result
+written
> maxlen
)
585 /* There is a range of ports; write ":79-80". */
586 result
= snprintf(s
+written
, maxlen
-written
, ":%d-%d\n", tmpe
->prt_min
,
588 if (result
<0 || result
+written
> maxlen
)
593 if (written
> maxlen
-256) /* Not enough room for signature. */
596 /* Sign the directory */
597 strcat(s
+written
, "router-signature\n");
598 written
+= strlen(s
+written
);
600 if (router_get_router_hash(s
, digest
) < 0)
603 if (crypto_pk_private_sign(ident_key
, digest
, 20, signature
) < 0) {
604 log_fn(LOG_WARN
, "Error signing digest");
607 strcat(s
+written
, "-----BEGIN SIGNATURE-----\n");
608 written
+= strlen(s
+written
);
609 if (base64_encode(s
+written
, maxlen
-written
, signature
, 128) < 0) {
610 log_fn(LOG_WARN
, "Couldn't base64-encode signature");
613 written
+= strlen(s
+written
);
614 strcat(s
+written
, "-----END SIGNATURE-----\n");
615 written
+= strlen(s
+written
);
617 if (written
> maxlen
-2)
619 /* include a last '\n' */
623 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
624 cp
= s_tmp
= s_dup
= tor_strdup(s
);
625 ri_tmp
= router_parse_entry_from_string(cp
, NULL
);
627 log_fn(LOG_ERR
, "We just generated a router descriptor we can't parse: <<%s>>",
632 routerinfo_free(ri_tmp
);