Merge branch 'feature16769_squashed'
[tor.git] / src / or / routerkeys.c
blob765dac883a5dae3961d60f65b3eaacc633b432f2
1 /* Copyright (c) 2014, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 #include "or.h"
5 #include "config.h"
6 #include "router.h"
7 #include "crypto_pwbox.h"
8 #include "routerkeys.h"
9 #include "torcert.h"
11 #define ENC_KEY_HEADER "Boxed Ed25519 key"
12 #define ENC_KEY_TAG "master"
14 static ssize_t
15 do_getpass(const char *prompt, char *buf, size_t buflen,
16 int twice, const or_options_t *options)
18 if (options->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
19 tor_assert(buflen);
20 buf[0] = 0;
21 return 0;
24 char *prompt2 = NULL;
25 char *buf2 = NULL;
26 int fd = -1;
27 ssize_t length = -1;
29 if (options->use_keygen_passphrase_fd) {
30 twice = 0;
31 fd = options->keygen_passphrase_fd;
32 length = read_all(fd, buf, buflen-1, 0);
33 if (length >= 0)
34 buf[length] = 0;
35 goto done_reading;
38 if (twice) {
39 const char msg[] = "One more time:";
40 size_t p2len = strlen(prompt) + 1;
41 if (p2len < sizeof(msg))
42 p2len = sizeof(msg);
43 prompt2 = tor_malloc(strlen(prompt)+1);
44 memset(prompt2, ' ', p2len);
45 memcpy(prompt2 + p2len - sizeof(msg), msg, sizeof(msg));
47 buf2 = tor_malloc_zero(buflen);
50 while (1) {
51 length = tor_getpass(prompt, buf, buflen);
52 if (length < 0)
53 goto done_reading;
55 if (! twice)
56 break;
58 ssize_t length2 = tor_getpass(prompt2, buf2, buflen);
60 if (length != length2 || tor_memneq(buf, buf2, length)) {
61 fprintf(stderr, "That didn't match.\n");
62 } else {
63 break;
67 done_reading:
68 if (twice) {
69 tor_free(prompt2);
70 memwipe(buf2, 0, buflen);
71 tor_free(buf2);
74 if (options->keygen_force_passphrase == FORCE_PASSPHRASE_ON && length == 0)
75 return -1;
77 return length;
80 int
81 read_encrypted_secret_key(ed25519_secret_key_t *out,
82 const char *fname)
84 int r = -1;
85 uint8_t *secret = NULL;
86 size_t secret_len = 0;
87 char pwbuf[256];
88 uint8_t encrypted_key[256];
89 char *tag = NULL;
90 int saved_errno = 0;
92 ssize_t encrypted_len = crypto_read_tagged_contents_from_file(fname,
93 ENC_KEY_HEADER,
94 &tag,
95 encrypted_key,
96 sizeof(encrypted_key));
97 if (encrypted_len < 0) {
98 saved_errno = errno;
99 log_info(LD_OR, "%s is missing", fname);
100 r = 0;
101 goto done;
103 if (strcmp(tag, ENC_KEY_TAG)) {
104 saved_errno = EINVAL;
105 goto done;
108 while (1) {
109 ssize_t pwlen =
110 do_getpass("Enter pasphrase for master key:", pwbuf, sizeof(pwbuf), 0,
111 get_options());
112 if (pwlen < 0) {
113 saved_errno = EINVAL;
114 goto done;
116 const int r = crypto_unpwbox(&secret, &secret_len,
117 encrypted_key, encrypted_len,
118 pwbuf, pwlen);
119 if (r == UNPWBOX_CORRUPTED) {
120 log_err(LD_OR, "%s is corrupted.", fname);
121 saved_errno = EINVAL;
122 goto done;
123 } else if (r == UNPWBOX_OKAY) {
124 break;
127 /* Otherwise, passphrase is bad, so try again till user does ctrl-c or gets
128 * it right. */
131 if (secret_len != ED25519_SECKEY_LEN) {
132 log_err(LD_OR, "%s is corrupted.", fname);
133 saved_errno = EINVAL;
134 goto done;
136 memcpy(out->seckey, secret, ED25519_SECKEY_LEN);
137 r = 1;
139 done:
140 memwipe(encrypted_key, 0, sizeof(encrypted_key));
141 memwipe(pwbuf, 0, sizeof(pwbuf));
142 tor_free(tag);
143 if (secret) {
144 memwipe(secret, 0, secret_len);
145 tor_free(secret);
147 if (saved_errno)
148 errno = saved_errno;
149 return r;
153 write_encrypted_secret_key(const ed25519_secret_key_t *key,
154 const char *fname)
156 int r = -1;
157 char pwbuf0[256];
158 uint8_t *encrypted_key = NULL;
159 size_t encrypted_len = 0;
161 if (do_getpass("Enter new passphrase:", pwbuf0, sizeof(pwbuf0), 1,
162 get_options()) < 0) {
163 log_warn(LD_OR, "NO/failed passphrase");
164 return -1;
167 if (strlen(pwbuf0) == 0) {
168 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_ON)
169 return -1;
170 else
171 return 0;
174 if (crypto_pwbox(&encrypted_key, &encrypted_len,
175 key->seckey, sizeof(key->seckey),
176 pwbuf0, strlen(pwbuf0), 0) < 0) {
177 log_warn(LD_OR, "crypto_pwbox failed!?");
178 goto done;
180 if (crypto_write_tagged_contents_to_file(fname,
181 ENC_KEY_HEADER,
182 ENC_KEY_TAG,
183 encrypted_key, encrypted_len) < 0)
184 goto done;
185 r = 1;
186 done:
187 if (encrypted_key) {
188 memwipe(encrypted_key, 0, encrypted_len);
189 tor_free(encrypted_key);
191 memwipe(pwbuf0, 0, sizeof(pwbuf0));
192 return r;
195 static int
196 write_secret_key(const ed25519_secret_key_t *key, int encrypted,
197 const char *fname,
198 const char *fname_tag,
199 const char *encrypted_fname)
201 if (encrypted) {
202 int r = write_encrypted_secret_key(key, encrypted_fname);
203 if (r == 1) {
204 /* Success! */
206 /* Try to unlink the unencrypted key, if any existed before */
207 if (strcmp(fname, encrypted_fname))
208 unlink(fname);
209 return r;
210 } else if (r != 0) {
211 /* Unrecoverable failure! */
212 return r;
215 fprintf(stderr, "Not encrypting the secret key.\n");
217 return ed25519_seckey_write_to_file(key, fname, fname_tag);
221 * Read an ed25519 key and associated certificates from files beginning with
222 * <b>fname</b>, with certificate type <b>cert_type</b>. On failure, return
223 * NULL; on success return the keypair.
225 * If INIT_ED_KEY_CREATE is set in <b>flags</b>, then create the key (and
226 * certificate if requested) if it doesn't exist, and save it to disk.
228 * If INIT_ED_KEY_NEEDCERT is set in <b>flags</b>, load/create a certificate
229 * too and store it in *<b>cert_out</b>. Fail if the cert can't be
230 * found/created. To create a certificate, <b>signing_key</b> must be set to
231 * the key that should sign it; <b>now</b> to the current time, and
232 * <b>lifetime</b> to the lifetime of the key.
234 * If INIT_ED_KEY_REPLACE is set in <b>flags</b>, then create and save new key
235 * whether we can read the old one or not.
237 * If INIT_ED_KEY_EXTRA_STRONG is set in <b>flags</b>, set the extra_strong
238 * flag when creating the secret key.
240 * If INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT is set in <b>flags</b>, and
241 * we create a new certificate, create it with the signing key embedded.
243 * If INIT_ED_KEY_SPLIT is set in <b>flags</b>, and we create a new key,
244 * store the public key in a separate file from the secret key.
246 * If INIT_ED_KEY_MISSING_SECRET_OK is set in <b>flags</b>, and we find a
247 * public key file but no secret key file, return successfully anyway.
249 * If INIT_ED_KEY_OMIT_SECRET is set in <b>flags</b>, do not try to load a
250 * secret key unless no public key is found. Do not return a secret key. (but
251 * create and save one if needed).
253 * If INIT_ED_KEY_NO_LOAD_SECRET is set in <b>flags</b>, don't try to load
254 * a secret key, no matter what.
256 * If INIT_ED_KEY_TRY_ENCRYPTED is set, we look for an encrypted secret key
257 * and consider encrypting any new secret key.
259 * If INIT_ED_KEY_NO_REPAIR is set, and there is any issue loading the keys
260 * from disk _other than their absence_ (full or partial), we do not try to
261 * replace them.
263 * If INIT_ED_KEY_SUGGEST_KEYGEN is set, have log messages about failures
264 * refer to the --keygen option.
266 * If INIT_ED_KEY_EXPLICIT_FNAME is set, use the provided file name for the
267 * secret key file, encrypted or not.
269 ed25519_keypair_t *
270 ed_key_init_from_file(const char *fname, uint32_t flags,
271 int severity,
272 const ed25519_keypair_t *signing_key,
273 time_t now,
274 time_t lifetime,
275 uint8_t cert_type,
276 struct tor_cert_st **cert_out)
278 char *secret_fname = NULL;
279 char *encrypted_secret_fname = NULL;
280 char *public_fname = NULL;
281 char *cert_fname = NULL;
282 const char *loaded_secret_fname = NULL;
283 int created_pk = 0, created_sk = 0, created_cert = 0;
284 const int try_to_load = ! (flags & INIT_ED_KEY_REPLACE);
285 const int encrypt_key = !! (flags & INIT_ED_KEY_TRY_ENCRYPTED);
286 const int norepair = !! (flags & INIT_ED_KEY_NO_REPAIR);
287 const int split = !! (flags & INIT_ED_KEY_SPLIT);
288 const int omit_secret = !! (flags & INIT_ED_KEY_OMIT_SECRET);
289 const int offline_secret = !! (flags & INIT_ED_KEY_OFFLINE_SECRET);
290 const int explicit_fname = !! (flags & INIT_ED_KEY_EXPLICIT_FNAME);
292 /* we don't support setting both of these flags at once. */
293 tor_assert((flags & (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT)) !=
294 (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT));
296 char tag[8];
297 tor_snprintf(tag, sizeof(tag), "type%d", (int)cert_type);
299 tor_cert_t *cert = NULL;
300 char *got_tag = NULL;
301 ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
303 if (explicit_fname) {
304 secret_fname = tor_strdup(fname);
305 encrypted_secret_fname = tor_strdup(fname);
306 } else {
307 tor_asprintf(&secret_fname, "%s_secret_key", fname);
308 tor_asprintf(&encrypted_secret_fname, "%s_secret_key_encrypted", fname);
310 tor_asprintf(&public_fname, "%s_public_key", fname);
311 tor_asprintf(&cert_fname, "%s_cert", fname);
313 /* Try to read the secret key. */
314 int have_secret = 0;
315 int load_secret = try_to_load &&
316 !offline_secret &&
317 (!omit_secret || file_status(public_fname)==FN_NOENT);
318 if (load_secret) {
319 int rv = ed25519_seckey_read_from_file(&keypair->seckey,
320 &got_tag, secret_fname);
321 if (rv == 0) {
322 have_secret = 1;
323 loaded_secret_fname = secret_fname;
324 tor_assert(got_tag);
325 } else {
326 if (errno != ENOENT && norepair) {
327 tor_log(severity, LD_OR, "Unable to read %s: %s", secret_fname,
328 strerror(errno));
329 goto err;
334 /* Should we try for an encrypted key? */
335 int have_encrypted_secret_file = 0;
336 if (!have_secret && try_to_load && encrypt_key) {
337 int r = read_encrypted_secret_key(&keypair->seckey,
338 encrypted_secret_fname);
339 if (r > 0) {
340 have_secret = 1;
341 have_encrypted_secret_file = 1;
342 tor_free(got_tag); /* convince coverity we aren't leaking */
343 got_tag = tor_strdup(tag);
344 loaded_secret_fname = encrypted_secret_fname;
345 } else if (errno != ENOENT && norepair) {
346 tor_log(severity, LD_OR, "Unable to read %s: %s",
347 encrypted_secret_fname, strerror(errno));
348 goto err;
350 } else {
351 if (try_to_load) {
352 /* Check if it's there anyway, so we don't replace it. */
353 if (file_status(encrypted_secret_fname) != FN_NOENT)
354 have_encrypted_secret_file = 1;
358 if (have_secret) {
359 if (strcmp(got_tag, tag)) {
360 tor_log(severity, LD_OR, "%s has wrong tag", loaded_secret_fname);
361 goto err;
363 /* Derive the public key */
364 if (ed25519_public_key_generate(&keypair->pubkey, &keypair->seckey)<0) {
365 tor_log(severity, LD_OR, "%s can't produce a public key",
366 loaded_secret_fname);
367 goto err;
371 /* If we do split keys here, try to read the pubkey. */
372 int found_public = 0;
373 if (try_to_load && (!have_secret || split)) {
374 ed25519_public_key_t pubkey_tmp;
375 tor_free(got_tag);
376 found_public = ed25519_pubkey_read_from_file(&pubkey_tmp,
377 &got_tag, public_fname) == 0;
378 if (!found_public && errno != ENOENT && norepair) {
379 tor_log(severity, LD_OR, "Unable to read %s: %s", public_fname,
380 strerror(errno));
381 goto err;
383 if (found_public && strcmp(got_tag, tag)) {
384 tor_log(severity, LD_OR, "%s has wrong tag", public_fname);
385 goto err;
387 if (found_public) {
388 if (have_secret) {
389 /* If we have a secret key and we're reloading the public key,
390 * the key must match! */
391 if (! ed25519_pubkey_eq(&keypair->pubkey, &pubkey_tmp)) {
392 tor_log(severity, LD_OR, "%s does not match %s! If you are trying "
393 "to restore from backup, make sure you didn't mix up the "
394 "key files. If you are absolutely sure that %s is the right "
395 "key for this relay, delete %s or move it out of the way.",
396 public_fname, loaded_secret_fname,
397 loaded_secret_fname, public_fname);
398 goto err;
400 } else {
401 /* We only have the public key; better use that. */
402 tor_assert(split);
403 memcpy(&keypair->pubkey, &pubkey_tmp, sizeof(pubkey_tmp));
405 } else {
406 /* We have no public key file, but we do have a secret key, make the
407 * public key file! */
408 if (have_secret) {
409 if (ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag)
410 < 0) {
411 tor_log(severity, LD_OR, "Couldn't repair %s", public_fname);
412 goto err;
413 } else {
414 tor_log(LOG_NOTICE, LD_OR,
415 "Found secret key but not %s. Regenerating.",
416 public_fname);
422 /* If the secret key is absent and it's not allowed to be, fail. */
423 if (!have_secret && found_public &&
424 !(flags & INIT_ED_KEY_MISSING_SECRET_OK)) {
425 if (have_encrypted_secret_file) {
426 tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
427 "but it was encrypted. Try 'tor --keygen' instead, so you "
428 "can enter the passphrase.",
429 secret_fname);
430 } else {
431 tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
432 "but couldn't find it. %s", secret_fname,
433 (flags & INIT_ED_KEY_SUGGEST_KEYGEN) ?
434 "If you're keeping your master secret key offline, you will "
435 "need to run 'tor --keygen' to generate new signing keys." :
436 "Did you forget to copy it over when you copied the rest of the "
437 "signing key material?");
439 goto err;
442 /* If it's absent, and we're not supposed to make a new keypair, fail. */
443 if (!have_secret && !found_public && !(flags & INIT_ED_KEY_CREATE)) {
444 if (split) {
445 tor_log(severity, LD_OR, "No key found in %s or %s.",
446 secret_fname, public_fname);
447 } else {
448 tor_log(severity, LD_OR, "No key found in %s.", secret_fname);
450 goto err;
453 /* If the secret key is absent, but the encrypted key would be present,
454 * that's an error */
455 if (!have_secret && !found_public && have_encrypted_secret_file) {
456 tor_assert(!encrypt_key);
457 tor_log(severity, LD_OR, "Found an encrypted secret key, "
458 "but not public key file %s!", public_fname);
459 goto err;
462 /* if it's absent, make a new keypair... */
463 if (!have_secret && !found_public) {
464 tor_free(keypair);
465 keypair = ed_key_new(signing_key, flags, now, lifetime,
466 cert_type, &cert);
467 if (!keypair) {
468 tor_log(severity, LD_OR, "Couldn't create keypair");
469 goto err;
471 created_pk = created_sk = created_cert = 1;
474 /* Write it to disk if we're supposed to do with a new passphrase, or if
475 * we just created it. */
476 if (created_sk || (have_secret && get_options()->change_key_passphrase)) {
477 if (write_secret_key(&keypair->seckey,
478 encrypt_key,
479 secret_fname, tag, encrypted_secret_fname) < 0
481 (split &&
482 ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag) < 0)
484 (cert &&
485 crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
486 tag, cert->encoded, cert->encoded_len) < 0)) {
487 tor_log(severity, LD_OR, "Couldn't write keys or cert to file.");
488 goto err;
490 goto done;
493 /* If we're not supposed to get a cert, we're done. */
494 if (! (flags & INIT_ED_KEY_NEEDCERT))
495 goto done;
497 /* Read a cert. */
498 tor_free(got_tag);
499 uint8_t certbuf[256];
500 ssize_t cert_body_len = crypto_read_tagged_contents_from_file(
501 cert_fname, "ed25519v1-cert",
502 &got_tag, certbuf, sizeof(certbuf));
503 if (cert_body_len >= 0 && !strcmp(got_tag, tag))
504 cert = tor_cert_parse(certbuf, cert_body_len);
506 /* If we got it, check it to the extent we can. */
507 int bad_cert = 0;
509 if (! cert) {
510 tor_log(severity, LD_OR, "Cert was unparseable");
511 bad_cert = 1;
512 } else if (!tor_memeq(cert->signed_key.pubkey, keypair->pubkey.pubkey,
513 ED25519_PUBKEY_LEN)) {
514 tor_log(severity, LD_OR, "Cert was for wrong key");
515 bad_cert = 1;
516 } else if (signing_key &&
517 tor_cert_checksig(cert, &signing_key->pubkey, now) < 0) {
518 tor_log(severity, LD_OR, "Can't check certificate");
519 bad_cert = 1;
520 } else if (cert->cert_expired) {
521 tor_log(severity, LD_OR, "Certificate is expired");
522 bad_cert = 1;
523 } else if (signing_key && cert->signing_key_included &&
524 ! ed25519_pubkey_eq(&signing_key->pubkey, &cert->signing_key)) {
525 tor_log(severity, LD_OR, "Certificate signed by unexpectd key!");
526 bad_cert = 1;
529 if (bad_cert) {
530 tor_cert_free(cert);
531 cert = NULL;
534 /* If we got a cert, we're done. */
535 if (cert)
536 goto done;
538 /* If we didn't get a cert, and we're not supposed to make one, fail. */
539 if (!signing_key || !(flags & INIT_ED_KEY_CREATE)) {
540 tor_log(severity, LD_OR, "Without signing key, can't create certificate");
541 goto err;
544 /* We have keys but not a certificate, so make one. */
545 uint32_t cert_flags = 0;
546 if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
547 cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
548 cert = tor_cert_create(signing_key, cert_type,
549 &keypair->pubkey,
550 now, lifetime,
551 cert_flags);
553 if (! cert) {
554 tor_log(severity, LD_OR, "Couldn't create certificate");
555 goto err;
558 /* Write it to disk. */
559 created_cert = 1;
560 if (crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
561 tag, cert->encoded, cert->encoded_len) < 0) {
562 tor_log(severity, LD_OR, "Couldn't write cert to disk.");
563 goto err;
566 done:
567 if (cert_out)
568 *cert_out = cert;
569 else
570 tor_cert_free(cert);
572 goto cleanup;
574 err:
575 if (keypair)
576 memwipe(keypair, 0, sizeof(*keypair));
577 tor_free(keypair);
578 tor_cert_free(cert);
579 if (cert_out)
580 *cert_out = NULL;
581 if (created_sk)
582 unlink(secret_fname);
583 if (created_pk)
584 unlink(public_fname);
585 if (created_cert)
586 unlink(cert_fname);
588 cleanup:
589 tor_free(encrypted_secret_fname);
590 tor_free(secret_fname);
591 tor_free(public_fname);
592 tor_free(cert_fname);
593 tor_free(got_tag);
595 return keypair;
599 * Create a new signing key and (optionally) certficiate; do not read or write
600 * from disk. See ed_key_init_from_file() for more information.
602 ed25519_keypair_t *
603 ed_key_new(const ed25519_keypair_t *signing_key,
604 uint32_t flags,
605 time_t now,
606 time_t lifetime,
607 uint8_t cert_type,
608 struct tor_cert_st **cert_out)
610 if (cert_out)
611 *cert_out = NULL;
613 const int extra_strong = !! (flags & INIT_ED_KEY_EXTRA_STRONG);
614 ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
615 if (ed25519_keypair_generate(keypair, extra_strong) < 0)
616 goto err;
618 if (! (flags & INIT_ED_KEY_NEEDCERT))
619 return keypair;
621 tor_assert(signing_key);
622 tor_assert(cert_out);
623 uint32_t cert_flags = 0;
624 if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
625 cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
626 tor_cert_t *cert = tor_cert_create(signing_key, cert_type,
627 &keypair->pubkey,
628 now, lifetime,
629 cert_flags);
630 if (! cert)
631 goto err;
633 *cert_out = cert;
634 return keypair;
636 err:
637 tor_free(keypair);
638 return NULL;
641 static ed25519_keypair_t *master_identity_key = NULL;
642 static ed25519_keypair_t *master_signing_key = NULL;
643 static ed25519_keypair_t *current_auth_key = NULL;
644 static tor_cert_t *signing_key_cert = NULL;
645 static tor_cert_t *link_cert_cert = NULL;
646 static tor_cert_t *auth_key_cert = NULL;
648 static uint8_t *rsa_ed_crosscert = NULL;
649 static size_t rsa_ed_crosscert_len = 0;
652 * Running as a server: load, reload, or refresh our ed25519 keys and
653 * certificates, creating and saving new ones as needed.
656 load_ed_keys(const or_options_t *options, time_t now)
658 ed25519_keypair_t *id = NULL;
659 ed25519_keypair_t *sign = NULL;
660 ed25519_keypair_t *auth = NULL;
661 const ed25519_keypair_t *sign_signing_key_with_id = NULL;
662 const ed25519_keypair_t *use_signing = NULL;
663 const tor_cert_t *check_signing_cert = NULL;
664 tor_cert_t *sign_cert = NULL;
665 tor_cert_t *auth_cert = NULL;
667 #define FAIL(msg) do { \
668 log_warn(LD_OR, (msg)); \
669 goto err; \
670 } while (0)
671 #define SET_KEY(key, newval) do { \
672 if ((key) != (newval)) \
673 ed25519_keypair_free(key); \
674 key = (newval); \
675 } while (0)
676 #define SET_CERT(cert, newval) do { \
677 if ((cert) != (newval)) \
678 tor_cert_free(cert); \
679 cert = (newval); \
680 } while (0)
681 #define EXPIRES_SOON(cert, interval) \
682 (!(cert) || (cert)->valid_until < now + (interval))
684 /* XXXX support encrypted identity keys fully */
686 /* First try to get the signing key to see how it is. */
688 char *fname =
689 options_get_datadir_fname2(options, "keys", "ed25519_signing");
690 sign = ed_key_init_from_file(
691 fname,
692 INIT_ED_KEY_NEEDCERT|
693 INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT,
694 LOG_INFO,
695 NULL, 0, 0, CERT_TYPE_ID_SIGNING, &sign_cert);
696 tor_free(fname);
697 check_signing_cert = sign_cert;
698 use_signing = sign;
701 if (!use_signing && master_signing_key) {
702 check_signing_cert = signing_key_cert;
703 use_signing = master_signing_key;
706 const int offline_master =
707 options->OfflineMasterKey && options->command != CMD_KEYGEN;
708 const int need_new_signing_key =
709 NULL == use_signing ||
710 EXPIRES_SOON(check_signing_cert, 0) ||
711 (options->command == CMD_KEYGEN && ! options->change_key_passphrase);
712 const int want_new_signing_key =
713 need_new_signing_key ||
714 EXPIRES_SOON(check_signing_cert, options->TestingSigningKeySlop);
716 /* We can only create a master key if we haven't been told that the
717 * master key will always be offline. Also, if we have a signing key,
718 * then we shouldn't make a new master ID key. */
719 const int can_make_master_id_key = !offline_master &&
720 NULL == use_signing;
722 if (need_new_signing_key) {
723 log_notice(LD_OR, "It looks like I need to generate and sign a new "
724 "medium-term signing key, because %s. To do that, I need to "
725 "load%s the permanent master identity key.",
726 (NULL == use_signing) ? "I don't have one" :
727 EXPIRES_SOON(check_signing_cert, 0) ? "the one I have is expired" :
728 "you asked me to make one with --keygen",
729 can_make_master_id_key ? " (or create)" : "");
730 } else if (want_new_signing_key && !offline_master) {
731 log_notice(LD_OR, "It looks like I should try to generate and sign a "
732 "new medium-term signing key, because the one I have is "
733 "going to expire soon. To do that, I'm going to have to try to "
734 "load the permanent master identity key.");
735 } else if (want_new_signing_key) {
736 log_notice(LD_OR, "It looks like I should try to generate and sign a "
737 "new medium-term signing key, because the one I have is "
738 "going to expire soon. But OfflineMasterKey is set, so I "
739 "won't try to load a permanent master identity key is set. "
740 "You will need to use 'tor --keygen' make a new signing key "
741 "and certificate.");
745 uint32_t flags =
746 (INIT_ED_KEY_SPLIT|
747 INIT_ED_KEY_EXTRA_STRONG|INIT_ED_KEY_NO_REPAIR);
748 if (can_make_master_id_key)
749 flags |= INIT_ED_KEY_CREATE;
750 if (! need_new_signing_key)
751 flags |= INIT_ED_KEY_MISSING_SECRET_OK;
752 if (! want_new_signing_key || offline_master)
753 flags |= INIT_ED_KEY_OMIT_SECRET;
754 if (offline_master)
755 flags |= INIT_ED_KEY_OFFLINE_SECRET;
756 if (options->command == CMD_KEYGEN)
757 flags |= INIT_ED_KEY_TRY_ENCRYPTED;
759 /* Check the key directory */
760 if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
761 log_err(LD_OR, "Can't create/check datadirectory %s",
762 options->DataDirectory);
763 goto err;
765 char *fname = get_datadir_fname("keys");
766 if (check_private_dir(fname, CPD_CREATE, options->User) < 0) {
767 log_err(LD_OR, "Problem creating/checking key directory %s", fname);
768 tor_free(fname);
769 goto err;
771 tor_free(fname);
772 if (options->master_key_fname) {
773 fname = tor_strdup(options->master_key_fname);
774 flags |= INIT_ED_KEY_EXPLICIT_FNAME;
775 } else {
776 fname = options_get_datadir_fname2(options, "keys", "ed25519_master_id");
778 id = ed_key_init_from_file(
779 fname,
780 flags,
781 LOG_WARN, NULL, 0, 0, 0, NULL);
782 tor_free(fname);
783 if (!id) {
784 if (need_new_signing_key) {
785 if (offline_master)
786 FAIL("Can't load master identity key; OfflineMasterKey is set.");
787 else
788 FAIL("Missing identity key");
789 } else {
790 log_warn(LD_OR, "Master public key was absent; inferring from "
791 "public key in signing certificate and saving to disk.");
792 tor_assert(check_signing_cert);
793 id = tor_malloc_zero(sizeof(*id));
794 memcpy(&id->pubkey, &check_signing_cert->signing_key,
795 sizeof(ed25519_public_key_t));
796 fname = options_get_datadir_fname2(options, "keys",
797 "ed25519_master_id_public_key");
798 if (ed25519_pubkey_write_to_file(&id->pubkey, fname, "type0") < 0) {
799 log_warn(LD_OR, "Error while attempting to write master public key "
800 "to disk");
801 tor_free(fname);
802 goto err;
804 tor_free(fname);
807 if (tor_mem_is_zero((char*)id->seckey.seckey, sizeof(id->seckey)))
808 sign_signing_key_with_id = NULL;
809 else
810 sign_signing_key_with_id = id;
813 if (master_identity_key &&
814 !ed25519_pubkey_eq(&id->pubkey, &master_identity_key->pubkey)) {
815 FAIL("Identity key on disk does not match key we loaded earlier!");
818 if (need_new_signing_key && NULL == sign_signing_key_with_id)
819 FAIL("Can't load master key make a new signing key.");
821 if (sign_cert) {
822 if (! sign_cert->signing_key_included)
823 FAIL("Loaded a signing cert with no key included!");
824 if (! ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey))
825 FAIL("The signing cert we have was not signed with the master key "
826 "we loaded!");
827 if (tor_cert_checksig(sign_cert, &id->pubkey, 0) < 0)
828 FAIL("The signing cert we loaded was not signed correctly!");
831 if (want_new_signing_key && sign_signing_key_with_id) {
832 uint32_t flags = (INIT_ED_KEY_CREATE|
833 INIT_ED_KEY_REPLACE|
834 INIT_ED_KEY_EXTRA_STRONG|
835 INIT_ED_KEY_NEEDCERT|
836 INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT);
837 char *fname =
838 options_get_datadir_fname2(options, "keys", "ed25519_signing");
839 sign = ed_key_init_from_file(fname,
840 flags, LOG_WARN,
841 sign_signing_key_with_id, now,
842 options->SigningKeyLifetime,
843 CERT_TYPE_ID_SIGNING, &sign_cert);
844 tor_free(fname);
845 if (!sign)
846 FAIL("Missing signing key");
847 use_signing = sign;
849 tor_assert(sign_cert->signing_key_included);
850 tor_assert(ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey));
851 tor_assert(ed25519_pubkey_eq(&sign_cert->signed_key, &sign->pubkey));
852 } else if (want_new_signing_key) {
853 static ratelim_t missing_master = RATELIM_INIT(3600);
854 log_fn_ratelim(&missing_master, LOG_WARN, LD_OR,
855 "Signing key will expire soon, but I can't load the "
856 "master key to sign a new one!");
859 tor_assert(use_signing);
861 /* At this point we no longer need our secret identity key. So wipe
862 * it, if we loaded it in the first place. */
863 memwipe(id->seckey.seckey, 0, sizeof(id->seckey));
865 if (options->command == CMD_KEYGEN)
866 goto end;
868 if (!rsa_ed_crosscert && server_mode(options)) {
869 uint8_t *crosscert;
870 ssize_t crosscert_len = tor_make_rsa_ed25519_crosscert(&id->pubkey,
871 get_server_identity_key(),
872 now+10*365*86400,/*XXXX*/
873 &crosscert);
874 rsa_ed_crosscert_len = crosscert_len;
875 rsa_ed_crosscert = crosscert;
878 if (!current_auth_key ||
879 EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop)) {
880 auth = ed_key_new(use_signing, INIT_ED_KEY_NEEDCERT,
881 now,
882 options->TestingAuthKeyLifetime,
883 CERT_TYPE_SIGNING_AUTH, &auth_cert);
885 if (!auth)
886 FAIL("Can't create auth key");
889 /* We've generated or loaded everything. Put them in memory. */
891 end:
892 if (! master_identity_key) {
893 SET_KEY(master_identity_key, id);
894 } else {
895 tor_free(id);
897 if (sign) {
898 SET_KEY(master_signing_key, sign);
899 SET_CERT(signing_key_cert, sign_cert);
901 if (auth) {
902 SET_KEY(current_auth_key, auth);
903 SET_CERT(auth_key_cert, auth_cert);
906 return 0;
907 err:
908 ed25519_keypair_free(id);
909 ed25519_keypair_free(sign);
910 ed25519_keypair_free(auth);
911 tor_cert_free(sign_cert);
912 tor_cert_free(auth_cert);
913 return -1;
916 /**DOCDOC*/
918 generate_ed_link_cert(const or_options_t *options, time_t now)
920 const tor_x509_cert_t *link = NULL, *id = NULL;
921 tor_cert_t *link_cert = NULL;
923 if (tor_tls_get_my_certs(1, &link, &id) < 0 || link == NULL) {
924 log_warn(LD_OR, "Can't get my x509 link cert.");
925 return -1;
928 const digests_t *digests = tor_x509_cert_get_cert_digests(link);
930 if (link_cert_cert &&
931 ! EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop) &&
932 fast_memeq(digests->d[DIGEST_SHA256], link_cert_cert->signed_key.pubkey,
933 DIGEST256_LEN)) {
934 return 0;
937 ed25519_public_key_t dummy_key;
938 memcpy(dummy_key.pubkey, digests->d[DIGEST_SHA256], DIGEST256_LEN);
940 link_cert = tor_cert_create(get_master_signing_keypair(),
941 CERT_TYPE_SIGNING_LINK,
942 &dummy_key,
943 now,
944 options->TestingLinkCertLifetime, 0);
946 if (link_cert) {
947 SET_CERT(link_cert_cert, link_cert);
949 return 0;
952 #undef FAIL
953 #undef SET_KEY
954 #undef SET_CERT
957 should_make_new_ed_keys(const or_options_t *options, const time_t now)
959 if (!master_identity_key ||
960 !master_signing_key ||
961 !current_auth_key ||
962 !link_cert_cert ||
963 EXPIRES_SOON(signing_key_cert, options->TestingSigningKeySlop) ||
964 EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop) ||
965 EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop))
966 return 1;
968 const tor_x509_cert_t *link = NULL, *id = NULL;
970 if (tor_tls_get_my_certs(1, &link, &id) < 0 || link == NULL)
971 return 1;
973 const digests_t *digests = tor_x509_cert_get_cert_digests(link);
975 if (!fast_memeq(digests->d[DIGEST_SHA256],
976 link_cert_cert->signed_key.pubkey,
977 DIGEST256_LEN)) {
978 return 1;
981 return 0;
984 #undef EXPIRES_SOON
986 const ed25519_public_key_t *
987 get_master_identity_key(void)
989 if (!master_identity_key)
990 return NULL;
991 return &master_identity_key->pubkey;
994 const ed25519_keypair_t *
995 get_master_signing_keypair(void)
997 return master_signing_key;
1000 const struct tor_cert_st *
1001 get_master_signing_key_cert(void)
1003 return signing_key_cert;
1006 const ed25519_keypair_t *
1007 get_current_auth_keypair(void)
1009 return current_auth_key;
1012 const tor_cert_t *
1013 get_current_link_cert_cert(void)
1015 return link_cert_cert;
1018 const tor_cert_t *
1019 get_current_auth_key_cert(void)
1021 return auth_key_cert;
1024 void
1025 get_master_rsa_crosscert(const uint8_t **cert_out,
1026 size_t *size_out)
1028 *cert_out = rsa_ed_crosscert;
1029 *size_out = rsa_ed_crosscert_len;
1032 /** Construct cross-certification for the master identity key with
1033 * the ntor onion key. Store the sign of the corresponding ed25519 public key
1034 * in *<b>sign_out</b>. */
1035 tor_cert_t *
1036 make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key,
1037 const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime,
1038 int *sign_out)
1040 tor_cert_t *cert = NULL;
1041 ed25519_keypair_t ed_onion_key;
1043 if (ed25519_keypair_from_curve25519_keypair(&ed_onion_key, sign_out,
1044 onion_key) < 0)
1045 goto end;
1047 cert = tor_cert_create(&ed_onion_key, CERT_TYPE_ONION_ID, master_id_key,
1048 now, lifetime, 0);
1050 end:
1051 memwipe(&ed_onion_key, 0, sizeof(ed_onion_key));
1052 return cert;
1055 /** Construct and return an RSA signature for the TAP onion key to
1056 * cross-certify the RSA and Ed25519 identity keys. Set <b>len_out</b> to its
1057 * length. */
1058 uint8_t *
1059 make_tap_onion_key_crosscert(const crypto_pk_t *onion_key,
1060 const ed25519_public_key_t *master_id_key,
1061 const crypto_pk_t *rsa_id_key,
1062 int *len_out)
1064 uint8_t signature[PK_BYTES];
1065 uint8_t signed_data[DIGEST_LEN + ED25519_PUBKEY_LEN];
1067 *len_out = 0;
1068 crypto_pk_get_digest(rsa_id_key, (char*)signed_data);
1069 memcpy(signed_data + DIGEST_LEN, master_id_key->pubkey, ED25519_PUBKEY_LEN);
1071 int r = crypto_pk_private_sign(onion_key,
1072 (char*)signature, sizeof(signature),
1073 (const char*)signed_data, sizeof(signed_data));
1074 if (r < 0)
1075 return NULL;
1077 *len_out = r;
1079 return tor_memdup(signature, r);
1082 /** Check whether an RSA-TAP cross-certification is correct. Return 0 if it
1083 * is, -1 if it isn't. */
1085 check_tap_onion_key_crosscert(const uint8_t *crosscert,
1086 int crosscert_len,
1087 const crypto_pk_t *onion_pkey,
1088 const ed25519_public_key_t *master_id_pkey,
1089 const uint8_t *rsa_id_digest)
1091 uint8_t *cc = tor_malloc(crypto_pk_keysize(onion_pkey));
1092 int cc_len =
1093 crypto_pk_public_checksig(onion_pkey,
1094 (char*)cc,
1095 crypto_pk_keysize(onion_pkey),
1096 (const char*)crosscert,
1097 crosscert_len);
1098 if (cc_len < 0) {
1099 goto err;
1101 if (cc_len < DIGEST_LEN + ED25519_PUBKEY_LEN) {
1102 log_warn(LD_DIR, "Short signature on cross-certification with TAP key");
1103 goto err;
1105 if (tor_memneq(cc, rsa_id_digest, DIGEST_LEN) ||
1106 tor_memneq(cc + DIGEST_LEN, master_id_pkey->pubkey,
1107 ED25519_PUBKEY_LEN)) {
1108 log_warn(LD_DIR, "Incorrect cross-certification with TAP key");
1109 goto err;
1112 tor_free(cc);
1113 return 0;
1114 err:
1115 tor_free(cc);
1116 return -1;
1119 void
1120 routerkeys_free_all(void)
1122 ed25519_keypair_free(master_identity_key);
1123 ed25519_keypair_free(master_signing_key);
1124 ed25519_keypair_free(current_auth_key);
1125 tor_cert_free(signing_key_cert);
1126 tor_cert_free(link_cert_cert);
1127 tor_cert_free(auth_key_cert);
1129 master_identity_key = master_signing_key = NULL;
1130 current_auth_key = NULL;
1131 signing_key_cert = link_cert_cert = auth_key_cert = NULL;