Merge remote-tracking branch 'karsten/task-18460-2' into maint-0.2.8
[tor.git] / src / or / routerkeys.c
blobefb3cbb571daa1f6da4edda287a168b3315ba036
1 /* Copyright (c) 2014-2016, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file routerkeys.c
7 * \brief Functions and structures to handle generating and maintaining the
8 * set of keypairs necessary to be an OR. (Some of the code in router.c
9 * belongs here.)
12 #include "or.h"
13 #include "config.h"
14 #include "router.h"
15 #include "crypto_pwbox.h"
16 #include "routerkeys.h"
17 #include "torcert.h"
19 #define ENC_KEY_HEADER "Boxed Ed25519 key"
20 #define ENC_KEY_TAG "master"
22 static ssize_t
23 do_getpass(const char *prompt, char *buf, size_t buflen,
24 int twice, const or_options_t *options)
26 if (options->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
27 tor_assert(buflen);
28 buf[0] = 0;
29 return 0;
32 char *prompt2 = NULL;
33 char *buf2 = NULL;
34 int fd = -1;
35 ssize_t length = -1;
37 if (options->use_keygen_passphrase_fd) {
38 twice = 0;
39 fd = options->keygen_passphrase_fd;
40 length = read_all(fd, buf, buflen-1, 0);
41 if (length >= 0)
42 buf[length] = 0;
43 goto done_reading;
46 if (twice) {
47 const char msg[] = "One more time:";
48 size_t p2len = strlen(prompt) + 1;
49 if (p2len < sizeof(msg))
50 p2len = sizeof(msg);
51 prompt2 = tor_malloc(strlen(prompt)+1);
52 memset(prompt2, ' ', p2len);
53 memcpy(prompt2 + p2len - sizeof(msg), msg, sizeof(msg));
55 buf2 = tor_malloc_zero(buflen);
58 while (1) {
59 length = tor_getpass(prompt, buf, buflen);
60 if (length < 0)
61 goto done_reading;
63 if (! twice)
64 break;
66 ssize_t length2 = tor_getpass(prompt2, buf2, buflen);
68 if (length != length2 || tor_memneq(buf, buf2, length)) {
69 fprintf(stderr, "That didn't match.\n");
70 } else {
71 break;
75 done_reading:
76 if (twice) {
77 tor_free(prompt2);
78 memwipe(buf2, 0, buflen);
79 tor_free(buf2);
82 if (options->keygen_force_passphrase == FORCE_PASSPHRASE_ON && length == 0)
83 return -1;
85 return length;
88 int
89 read_encrypted_secret_key(ed25519_secret_key_t *out,
90 const char *fname)
92 int r = -1;
93 uint8_t *secret = NULL;
94 size_t secret_len = 0;
95 char pwbuf[256];
96 uint8_t encrypted_key[256];
97 char *tag = NULL;
98 int saved_errno = 0;
100 ssize_t encrypted_len = crypto_read_tagged_contents_from_file(fname,
101 ENC_KEY_HEADER,
102 &tag,
103 encrypted_key,
104 sizeof(encrypted_key));
105 if (encrypted_len < 0) {
106 saved_errno = errno;
107 log_info(LD_OR, "%s is missing", fname);
108 r = 0;
109 goto done;
111 if (strcmp(tag, ENC_KEY_TAG)) {
112 saved_errno = EINVAL;
113 goto done;
116 while (1) {
117 ssize_t pwlen =
118 do_getpass("Enter pasphrase for master key:", pwbuf, sizeof(pwbuf), 0,
119 get_options());
120 if (pwlen < 0) {
121 saved_errno = EINVAL;
122 goto done;
124 const int r = crypto_unpwbox(&secret, &secret_len,
125 encrypted_key, encrypted_len,
126 pwbuf, pwlen);
127 if (r == UNPWBOX_CORRUPTED) {
128 log_err(LD_OR, "%s is corrupted.", fname);
129 saved_errno = EINVAL;
130 goto done;
131 } else if (r == UNPWBOX_OKAY) {
132 break;
135 /* Otherwise, passphrase is bad, so try again till user does ctrl-c or gets
136 * it right. */
139 if (secret_len != ED25519_SECKEY_LEN) {
140 log_err(LD_OR, "%s is corrupted.", fname);
141 saved_errno = EINVAL;
142 goto done;
144 memcpy(out->seckey, secret, ED25519_SECKEY_LEN);
145 r = 1;
147 done:
148 memwipe(encrypted_key, 0, sizeof(encrypted_key));
149 memwipe(pwbuf, 0, sizeof(pwbuf));
150 tor_free(tag);
151 if (secret) {
152 memwipe(secret, 0, secret_len);
153 tor_free(secret);
155 if (saved_errno)
156 errno = saved_errno;
157 return r;
161 write_encrypted_secret_key(const ed25519_secret_key_t *key,
162 const char *fname)
164 int r = -1;
165 char pwbuf0[256];
166 uint8_t *encrypted_key = NULL;
167 size_t encrypted_len = 0;
169 if (do_getpass("Enter new passphrase:", pwbuf0, sizeof(pwbuf0), 1,
170 get_options()) < 0) {
171 log_warn(LD_OR, "NO/failed passphrase");
172 return -1;
175 if (strlen(pwbuf0) == 0) {
176 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_ON)
177 return -1;
178 else
179 return 0;
182 if (crypto_pwbox(&encrypted_key, &encrypted_len,
183 key->seckey, sizeof(key->seckey),
184 pwbuf0, strlen(pwbuf0), 0) < 0) {
185 log_warn(LD_OR, "crypto_pwbox failed!?");
186 goto done;
188 if (crypto_write_tagged_contents_to_file(fname,
189 ENC_KEY_HEADER,
190 ENC_KEY_TAG,
191 encrypted_key, encrypted_len) < 0)
192 goto done;
193 r = 1;
194 done:
195 if (encrypted_key) {
196 memwipe(encrypted_key, 0, encrypted_len);
197 tor_free(encrypted_key);
199 memwipe(pwbuf0, 0, sizeof(pwbuf0));
200 return r;
203 static int
204 write_secret_key(const ed25519_secret_key_t *key, int encrypted,
205 const char *fname,
206 const char *fname_tag,
207 const char *encrypted_fname)
209 if (encrypted) {
210 int r = write_encrypted_secret_key(key, encrypted_fname);
211 if (r == 1) {
212 /* Success! */
214 /* Try to unlink the unencrypted key, if any existed before */
215 if (strcmp(fname, encrypted_fname))
216 unlink(fname);
217 return r;
218 } else if (r != 0) {
219 /* Unrecoverable failure! */
220 return r;
223 fprintf(stderr, "Not encrypting the secret key.\n");
225 return ed25519_seckey_write_to_file(key, fname, fname_tag);
229 * Read an ed25519 key and associated certificates from files beginning with
230 * <b>fname</b>, with certificate type <b>cert_type</b>. On failure, return
231 * NULL; on success return the keypair.
233 * If INIT_ED_KEY_CREATE is set in <b>flags</b>, then create the key (and
234 * certificate if requested) if it doesn't exist, and save it to disk.
236 * If INIT_ED_KEY_NEEDCERT is set in <b>flags</b>, load/create a certificate
237 * too and store it in *<b>cert_out</b>. Fail if the cert can't be
238 * found/created. To create a certificate, <b>signing_key</b> must be set to
239 * the key that should sign it; <b>now</b> to the current time, and
240 * <b>lifetime</b> to the lifetime of the key.
242 * If INIT_ED_KEY_REPLACE is set in <b>flags</b>, then create and save new key
243 * whether we can read the old one or not.
245 * If INIT_ED_KEY_EXTRA_STRONG is set in <b>flags</b>, set the extra_strong
246 * flag when creating the secret key.
248 * If INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT is set in <b>flags</b>, and
249 * we create a new certificate, create it with the signing key embedded.
251 * If INIT_ED_KEY_SPLIT is set in <b>flags</b>, and we create a new key,
252 * store the public key in a separate file from the secret key.
254 * If INIT_ED_KEY_MISSING_SECRET_OK is set in <b>flags</b>, and we find a
255 * public key file but no secret key file, return successfully anyway.
257 * If INIT_ED_KEY_OMIT_SECRET is set in <b>flags</b>, do not try to load a
258 * secret key unless no public key is found. Do not return a secret key. (but
259 * create and save one if needed).
261 * If INIT_ED_KEY_NO_LOAD_SECRET is set in <b>flags</b>, don't try to load
262 * a secret key, no matter what.
264 * If INIT_ED_KEY_TRY_ENCRYPTED is set, we look for an encrypted secret key
265 * and consider encrypting any new secret key.
267 * If INIT_ED_KEY_NO_REPAIR is set, and there is any issue loading the keys
268 * from disk _other than their absence_ (full or partial), we do not try to
269 * replace them.
271 * If INIT_ED_KEY_SUGGEST_KEYGEN is set, have log messages about failures
272 * refer to the --keygen option.
274 * If INIT_ED_KEY_EXPLICIT_FNAME is set, use the provided file name for the
275 * secret key file, encrypted or not.
277 ed25519_keypair_t *
278 ed_key_init_from_file(const char *fname, uint32_t flags,
279 int severity,
280 const ed25519_keypair_t *signing_key,
281 time_t now,
282 time_t lifetime,
283 uint8_t cert_type,
284 struct tor_cert_st **cert_out)
286 char *secret_fname = NULL;
287 char *encrypted_secret_fname = NULL;
288 char *public_fname = NULL;
289 char *cert_fname = NULL;
290 const char *loaded_secret_fname = NULL;
291 int created_pk = 0, created_sk = 0, created_cert = 0;
292 const int try_to_load = ! (flags & INIT_ED_KEY_REPLACE);
293 const int encrypt_key = !! (flags & INIT_ED_KEY_TRY_ENCRYPTED);
294 const int norepair = !! (flags & INIT_ED_KEY_NO_REPAIR);
295 const int split = !! (flags & INIT_ED_KEY_SPLIT);
296 const int omit_secret = !! (flags & INIT_ED_KEY_OMIT_SECRET);
297 const int offline_secret = !! (flags & INIT_ED_KEY_OFFLINE_SECRET);
298 const int explicit_fname = !! (flags & INIT_ED_KEY_EXPLICIT_FNAME);
300 /* we don't support setting both of these flags at once. */
301 tor_assert((flags & (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT)) !=
302 (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT));
304 char tag[8];
305 tor_snprintf(tag, sizeof(tag), "type%d", (int)cert_type);
307 tor_cert_t *cert = NULL;
308 char *got_tag = NULL;
309 ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
311 if (explicit_fname) {
312 secret_fname = tor_strdup(fname);
313 encrypted_secret_fname = tor_strdup(fname);
314 } else {
315 tor_asprintf(&secret_fname, "%s_secret_key", fname);
316 tor_asprintf(&encrypted_secret_fname, "%s_secret_key_encrypted", fname);
318 tor_asprintf(&public_fname, "%s_public_key", fname);
319 tor_asprintf(&cert_fname, "%s_cert", fname);
321 /* Try to read the secret key. */
322 int have_secret = 0;
323 int load_secret = try_to_load &&
324 !offline_secret &&
325 (!omit_secret || file_status(public_fname)==FN_NOENT);
326 if (load_secret) {
327 int rv = ed25519_seckey_read_from_file(&keypair->seckey,
328 &got_tag, secret_fname);
329 if (rv == 0) {
330 have_secret = 1;
331 loaded_secret_fname = secret_fname;
332 tor_assert(got_tag);
333 } else {
334 if (errno != ENOENT && norepair) {
335 tor_log(severity, LD_OR, "Unable to read %s: %s", secret_fname,
336 strerror(errno));
337 goto err;
342 /* Should we try for an encrypted key? */
343 int have_encrypted_secret_file = 0;
344 if (!have_secret && try_to_load && encrypt_key) {
345 int r = read_encrypted_secret_key(&keypair->seckey,
346 encrypted_secret_fname);
347 if (r > 0) {
348 have_secret = 1;
349 have_encrypted_secret_file = 1;
350 tor_free(got_tag); /* convince coverity we aren't leaking */
351 got_tag = tor_strdup(tag);
352 loaded_secret_fname = encrypted_secret_fname;
353 } else if (errno != ENOENT && norepair) {
354 tor_log(severity, LD_OR, "Unable to read %s: %s",
355 encrypted_secret_fname, strerror(errno));
356 goto err;
358 } else {
359 if (try_to_load) {
360 /* Check if it's there anyway, so we don't replace it. */
361 if (file_status(encrypted_secret_fname) != FN_NOENT)
362 have_encrypted_secret_file = 1;
366 if (have_secret) {
367 if (strcmp(got_tag, tag)) {
368 tor_log(severity, LD_OR, "%s has wrong tag", loaded_secret_fname);
369 goto err;
371 /* Derive the public key */
372 if (ed25519_public_key_generate(&keypair->pubkey, &keypair->seckey)<0) {
373 tor_log(severity, LD_OR, "%s can't produce a public key",
374 loaded_secret_fname);
375 goto err;
379 /* If we do split keys here, try to read the pubkey. */
380 int found_public = 0;
381 if (try_to_load && (!have_secret || split)) {
382 ed25519_public_key_t pubkey_tmp;
383 tor_free(got_tag);
384 found_public = ed25519_pubkey_read_from_file(&pubkey_tmp,
385 &got_tag, public_fname) == 0;
386 if (!found_public && errno != ENOENT && norepair) {
387 tor_log(severity, LD_OR, "Unable to read %s: %s", public_fname,
388 strerror(errno));
389 goto err;
391 if (found_public && strcmp(got_tag, tag)) {
392 tor_log(severity, LD_OR, "%s has wrong tag", public_fname);
393 goto err;
395 if (found_public) {
396 if (have_secret) {
397 /* If we have a secret key and we're reloading the public key,
398 * the key must match! */
399 if (! ed25519_pubkey_eq(&keypair->pubkey, &pubkey_tmp)) {
400 tor_log(severity, LD_OR, "%s does not match %s! If you are trying "
401 "to restore from backup, make sure you didn't mix up the "
402 "key files. If you are absolutely sure that %s is the right "
403 "key for this relay, delete %s or move it out of the way.",
404 public_fname, loaded_secret_fname,
405 loaded_secret_fname, public_fname);
406 goto err;
408 } else {
409 /* We only have the public key; better use that. */
410 tor_assert(split);
411 memcpy(&keypair->pubkey, &pubkey_tmp, sizeof(pubkey_tmp));
413 } else {
414 /* We have no public key file, but we do have a secret key, make the
415 * public key file! */
416 if (have_secret) {
417 if (ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag)
418 < 0) {
419 tor_log(severity, LD_OR, "Couldn't repair %s", public_fname);
420 goto err;
421 } else {
422 tor_log(LOG_NOTICE, LD_OR,
423 "Found secret key but not %s. Regenerating.",
424 public_fname);
430 /* If the secret key is absent and it's not allowed to be, fail. */
431 if (!have_secret && found_public &&
432 !(flags & INIT_ED_KEY_MISSING_SECRET_OK)) {
433 if (have_encrypted_secret_file) {
434 tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
435 "but it was encrypted. Try 'tor --keygen' instead, so you "
436 "can enter the passphrase.",
437 secret_fname);
438 } else {
439 tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
440 "but couldn't find it. %s", secret_fname,
441 (flags & INIT_ED_KEY_SUGGEST_KEYGEN) ?
442 "If you're keeping your master secret key offline, you will "
443 "need to run 'tor --keygen' to generate new signing keys." :
444 "Did you forget to copy it over when you copied the rest of the "
445 "signing key material?");
447 goto err;
450 /* If it's absent, and we're not supposed to make a new keypair, fail. */
451 if (!have_secret && !found_public && !(flags & INIT_ED_KEY_CREATE)) {
452 if (split) {
453 tor_log(severity, LD_OR, "No key found in %s or %s.",
454 secret_fname, public_fname);
455 } else {
456 tor_log(severity, LD_OR, "No key found in %s.", secret_fname);
458 goto err;
461 /* If the secret key is absent, but the encrypted key would be present,
462 * that's an error */
463 if (!have_secret && !found_public && have_encrypted_secret_file) {
464 tor_assert(!encrypt_key);
465 tor_log(severity, LD_OR, "Found an encrypted secret key, "
466 "but not public key file %s!", public_fname);
467 goto err;
470 /* if it's absent, make a new keypair... */
471 if (!have_secret && !found_public) {
472 tor_free(keypair);
473 keypair = ed_key_new(signing_key, flags, now, lifetime,
474 cert_type, &cert);
475 if (!keypair) {
476 tor_log(severity, LD_OR, "Couldn't create keypair");
477 goto err;
479 created_pk = created_sk = created_cert = 1;
482 /* Write it to disk if we're supposed to do with a new passphrase, or if
483 * we just created it. */
484 if (created_sk || (have_secret && get_options()->change_key_passphrase)) {
485 if (write_secret_key(&keypair->seckey,
486 encrypt_key,
487 secret_fname, tag, encrypted_secret_fname) < 0
489 (split &&
490 ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag) < 0)
492 (cert &&
493 crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
494 tag, cert->encoded, cert->encoded_len) < 0)) {
495 tor_log(severity, LD_OR, "Couldn't write keys or cert to file.");
496 goto err;
498 goto done;
501 /* If we're not supposed to get a cert, we're done. */
502 if (! (flags & INIT_ED_KEY_NEEDCERT))
503 goto done;
505 /* Read a cert. */
506 tor_free(got_tag);
507 uint8_t certbuf[256];
508 ssize_t cert_body_len = crypto_read_tagged_contents_from_file(
509 cert_fname, "ed25519v1-cert",
510 &got_tag, certbuf, sizeof(certbuf));
511 if (cert_body_len >= 0 && !strcmp(got_tag, tag))
512 cert = tor_cert_parse(certbuf, cert_body_len);
514 /* If we got it, check it to the extent we can. */
515 int bad_cert = 0;
517 if (! cert) {
518 tor_log(severity, LD_OR, "Cert was unparseable");
519 bad_cert = 1;
520 } else if (!tor_memeq(cert->signed_key.pubkey, keypair->pubkey.pubkey,
521 ED25519_PUBKEY_LEN)) {
522 tor_log(severity, LD_OR, "Cert was for wrong key");
523 bad_cert = 1;
524 } else if (signing_key &&
525 tor_cert_checksig(cert, &signing_key->pubkey, now) < 0) {
526 tor_log(severity, LD_OR, "Can't check certificate");
527 bad_cert = 1;
528 } else if (cert->cert_expired) {
529 tor_log(severity, LD_OR, "Certificate is expired");
530 bad_cert = 1;
531 } else if (signing_key && cert->signing_key_included &&
532 ! ed25519_pubkey_eq(&signing_key->pubkey, &cert->signing_key)) {
533 tor_log(severity, LD_OR, "Certificate signed by unexpectd key!");
534 bad_cert = 1;
537 if (bad_cert) {
538 tor_cert_free(cert);
539 cert = NULL;
542 /* If we got a cert, we're done. */
543 if (cert)
544 goto done;
546 /* If we didn't get a cert, and we're not supposed to make one, fail. */
547 if (!signing_key || !(flags & INIT_ED_KEY_CREATE)) {
548 tor_log(severity, LD_OR, "Without signing key, can't create certificate");
549 goto err;
552 /* We have keys but not a certificate, so make one. */
553 uint32_t cert_flags = 0;
554 if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
555 cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
556 cert = tor_cert_create(signing_key, cert_type,
557 &keypair->pubkey,
558 now, lifetime,
559 cert_flags);
561 if (! cert) {
562 tor_log(severity, LD_OR, "Couldn't create certificate");
563 goto err;
566 /* Write it to disk. */
567 created_cert = 1;
568 if (crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
569 tag, cert->encoded, cert->encoded_len) < 0) {
570 tor_log(severity, LD_OR, "Couldn't write cert to disk.");
571 goto err;
574 done:
575 if (cert_out)
576 *cert_out = cert;
577 else
578 tor_cert_free(cert);
580 goto cleanup;
582 err:
583 if (keypair)
584 memwipe(keypair, 0, sizeof(*keypair));
585 tor_free(keypair);
586 tor_cert_free(cert);
587 if (cert_out)
588 *cert_out = NULL;
589 if (created_sk)
590 unlink(secret_fname);
591 if (created_pk)
592 unlink(public_fname);
593 if (created_cert)
594 unlink(cert_fname);
596 cleanup:
597 tor_free(encrypted_secret_fname);
598 tor_free(secret_fname);
599 tor_free(public_fname);
600 tor_free(cert_fname);
601 tor_free(got_tag);
603 return keypair;
607 * Create a new signing key and (optionally) certficiate; do not read or write
608 * from disk. See ed_key_init_from_file() for more information.
610 ed25519_keypair_t *
611 ed_key_new(const ed25519_keypair_t *signing_key,
612 uint32_t flags,
613 time_t now,
614 time_t lifetime,
615 uint8_t cert_type,
616 struct tor_cert_st **cert_out)
618 if (cert_out)
619 *cert_out = NULL;
621 const int extra_strong = !! (flags & INIT_ED_KEY_EXTRA_STRONG);
622 ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
623 if (ed25519_keypair_generate(keypair, extra_strong) < 0)
624 goto err;
626 if (! (flags & INIT_ED_KEY_NEEDCERT))
627 return keypair;
629 tor_assert(signing_key);
630 tor_assert(cert_out);
631 uint32_t cert_flags = 0;
632 if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
633 cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
634 tor_cert_t *cert = tor_cert_create(signing_key, cert_type,
635 &keypair->pubkey,
636 now, lifetime,
637 cert_flags);
638 if (! cert)
639 goto err;
641 *cert_out = cert;
642 return keypair;
644 err:
645 tor_free(keypair);
646 return NULL;
649 static ed25519_keypair_t *master_identity_key = NULL;
650 static ed25519_keypair_t *master_signing_key = NULL;
651 static ed25519_keypair_t *current_auth_key = NULL;
652 static tor_cert_t *signing_key_cert = NULL;
653 static tor_cert_t *link_cert_cert = NULL;
654 static tor_cert_t *auth_key_cert = NULL;
656 static uint8_t *rsa_ed_crosscert = NULL;
657 static size_t rsa_ed_crosscert_len = 0;
660 * Running as a server: load, reload, or refresh our ed25519 keys and
661 * certificates, creating and saving new ones as needed.
664 load_ed_keys(const or_options_t *options, time_t now)
666 ed25519_keypair_t *id = NULL;
667 ed25519_keypair_t *sign = NULL;
668 ed25519_keypair_t *auth = NULL;
669 const ed25519_keypair_t *sign_signing_key_with_id = NULL;
670 const ed25519_keypair_t *use_signing = NULL;
671 const tor_cert_t *check_signing_cert = NULL;
672 tor_cert_t *sign_cert = NULL;
673 tor_cert_t *auth_cert = NULL;
675 #define FAIL(msg) do { \
676 log_warn(LD_OR, (msg)); \
677 goto err; \
678 } while (0)
679 #define SET_KEY(key, newval) do { \
680 if ((key) != (newval)) \
681 ed25519_keypair_free(key); \
682 key = (newval); \
683 } while (0)
684 #define SET_CERT(cert, newval) do { \
685 if ((cert) != (newval)) \
686 tor_cert_free(cert); \
687 cert = (newval); \
688 } while (0)
689 #define EXPIRES_SOON(cert, interval) \
690 (!(cert) || (cert)->valid_until < now + (interval))
692 /* XXXX support encrypted identity keys fully */
694 /* First try to get the signing key to see how it is. */
696 char *fname =
697 options_get_datadir_fname2(options, "keys", "ed25519_signing");
698 sign = ed_key_init_from_file(
699 fname,
700 INIT_ED_KEY_NEEDCERT|
701 INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT,
702 LOG_INFO,
703 NULL, 0, 0, CERT_TYPE_ID_SIGNING, &sign_cert);
704 tor_free(fname);
705 check_signing_cert = sign_cert;
706 use_signing = sign;
709 if (!use_signing && master_signing_key) {
710 check_signing_cert = signing_key_cert;
711 use_signing = master_signing_key;
714 const int offline_master =
715 options->OfflineMasterKey && options->command != CMD_KEYGEN;
716 const int need_new_signing_key =
717 NULL == use_signing ||
718 EXPIRES_SOON(check_signing_cert, 0) ||
719 (options->command == CMD_KEYGEN && ! options->change_key_passphrase);
720 const int want_new_signing_key =
721 need_new_signing_key ||
722 EXPIRES_SOON(check_signing_cert, options->TestingSigningKeySlop);
724 /* We can only create a master key if we haven't been told that the
725 * master key will always be offline. Also, if we have a signing key,
726 * then we shouldn't make a new master ID key. */
727 const int can_make_master_id_key = !offline_master &&
728 NULL == use_signing;
730 if (need_new_signing_key) {
731 log_notice(LD_OR, "It looks like I need to generate and sign a new "
732 "medium-term signing key, because %s. To do that, I need to "
733 "load%s the permanent master identity key.",
734 (NULL == use_signing) ? "I don't have one" :
735 EXPIRES_SOON(check_signing_cert, 0) ? "the one I have is expired" :
736 "you asked me to make one with --keygen",
737 can_make_master_id_key ? " (or create)" : "");
738 } else if (want_new_signing_key && !offline_master) {
739 log_notice(LD_OR, "It looks like I should try to generate and sign a "
740 "new medium-term signing key, because the one I have is "
741 "going to expire soon. To do that, I'm going to have to try to "
742 "load the permanent master identity key.");
743 } else if (want_new_signing_key) {
744 log_notice(LD_OR, "It looks like I should try to generate and sign a "
745 "new medium-term signing key, because the one I have is "
746 "going to expire soon. But OfflineMasterKey is set, so I "
747 "won't try to load a permanent master identity key is set. "
748 "You will need to use 'tor --keygen' make a new signing key "
749 "and certificate.");
753 uint32_t flags =
754 (INIT_ED_KEY_SPLIT|
755 INIT_ED_KEY_EXTRA_STRONG|INIT_ED_KEY_NO_REPAIR);
756 if (can_make_master_id_key)
757 flags |= INIT_ED_KEY_CREATE;
758 if (! need_new_signing_key)
759 flags |= INIT_ED_KEY_MISSING_SECRET_OK;
760 if (! want_new_signing_key || offline_master)
761 flags |= INIT_ED_KEY_OMIT_SECRET;
762 if (offline_master)
763 flags |= INIT_ED_KEY_OFFLINE_SECRET;
764 if (options->command == CMD_KEYGEN)
765 flags |= INIT_ED_KEY_TRY_ENCRYPTED;
767 /* Check the key directory */
768 if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
769 log_err(LD_OR, "Can't create/check datadirectory %s",
770 options->DataDirectory);
771 goto err;
773 char *fname = get_datadir_fname("keys");
774 if (check_private_dir(fname, CPD_CREATE, options->User) < 0) {
775 log_err(LD_OR, "Problem creating/checking key directory %s", fname);
776 tor_free(fname);
777 goto err;
779 tor_free(fname);
780 if (options->master_key_fname) {
781 fname = tor_strdup(options->master_key_fname);
782 flags |= INIT_ED_KEY_EXPLICIT_FNAME;
783 } else {
784 fname = options_get_datadir_fname2(options, "keys", "ed25519_master_id");
786 id = ed_key_init_from_file(
787 fname,
788 flags,
789 LOG_WARN, NULL, 0, 0, 0, NULL);
790 tor_free(fname);
791 if (!id) {
792 if (need_new_signing_key) {
793 if (offline_master)
794 FAIL("Can't load master identity key; OfflineMasterKey is set.");
795 else
796 FAIL("Missing identity key");
797 } else {
798 log_warn(LD_OR, "Master public key was absent; inferring from "
799 "public key in signing certificate and saving to disk.");
800 tor_assert(check_signing_cert);
801 id = tor_malloc_zero(sizeof(*id));
802 memcpy(&id->pubkey, &check_signing_cert->signing_key,
803 sizeof(ed25519_public_key_t));
804 fname = options_get_datadir_fname2(options, "keys",
805 "ed25519_master_id_public_key");
806 if (ed25519_pubkey_write_to_file(&id->pubkey, fname, "type0") < 0) {
807 log_warn(LD_OR, "Error while attempting to write master public key "
808 "to disk");
809 tor_free(fname);
810 goto err;
812 tor_free(fname);
815 if (tor_mem_is_zero((char*)id->seckey.seckey, sizeof(id->seckey)))
816 sign_signing_key_with_id = NULL;
817 else
818 sign_signing_key_with_id = id;
821 if (master_identity_key &&
822 !ed25519_pubkey_eq(&id->pubkey, &master_identity_key->pubkey)) {
823 FAIL("Identity key on disk does not match key we loaded earlier!");
826 if (need_new_signing_key && NULL == sign_signing_key_with_id)
827 FAIL("Can't load master key make a new signing key.");
829 if (sign_cert) {
830 if (! sign_cert->signing_key_included)
831 FAIL("Loaded a signing cert with no key included!");
832 if (! ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey))
833 FAIL("The signing cert we have was not signed with the master key "
834 "we loaded!");
835 if (tor_cert_checksig(sign_cert, &id->pubkey, 0) < 0)
836 FAIL("The signing cert we loaded was not signed correctly!");
839 if (want_new_signing_key && sign_signing_key_with_id) {
840 uint32_t flags = (INIT_ED_KEY_CREATE|
841 INIT_ED_KEY_REPLACE|
842 INIT_ED_KEY_EXTRA_STRONG|
843 INIT_ED_KEY_NEEDCERT|
844 INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT);
845 char *fname =
846 options_get_datadir_fname2(options, "keys", "ed25519_signing");
847 ed25519_keypair_free(sign);
848 tor_cert_free(sign_cert);
849 sign = ed_key_init_from_file(fname,
850 flags, LOG_WARN,
851 sign_signing_key_with_id, now,
852 options->SigningKeyLifetime,
853 CERT_TYPE_ID_SIGNING, &sign_cert);
854 tor_free(fname);
855 if (!sign)
856 FAIL("Missing signing key");
857 use_signing = sign;
859 tor_assert(sign_cert->signing_key_included);
860 tor_assert(ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey));
861 tor_assert(ed25519_pubkey_eq(&sign_cert->signed_key, &sign->pubkey));
862 } else if (want_new_signing_key) {
863 static ratelim_t missing_master = RATELIM_INIT(3600);
864 log_fn_ratelim(&missing_master, LOG_WARN, LD_OR,
865 "Signing key will expire soon, but I can't load the "
866 "master key to sign a new one!");
869 tor_assert(use_signing);
871 /* At this point we no longer need our secret identity key. So wipe
872 * it, if we loaded it in the first place. */
873 memwipe(id->seckey.seckey, 0, sizeof(id->seckey));
875 if (options->command == CMD_KEYGEN)
876 goto end;
878 if (!rsa_ed_crosscert && server_mode(options)) {
879 uint8_t *crosscert;
880 ssize_t crosscert_len = tor_make_rsa_ed25519_crosscert(&id->pubkey,
881 get_server_identity_key(),
882 now+10*365*86400,/*XXXX*/
883 &crosscert);
884 rsa_ed_crosscert_len = crosscert_len;
885 rsa_ed_crosscert = crosscert;
888 if (!current_auth_key ||
889 EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop)) {
890 auth = ed_key_new(use_signing, INIT_ED_KEY_NEEDCERT,
891 now,
892 options->TestingAuthKeyLifetime,
893 CERT_TYPE_SIGNING_AUTH, &auth_cert);
895 if (!auth)
896 FAIL("Can't create auth key");
899 /* We've generated or loaded everything. Put them in memory. */
901 end:
902 if (! master_identity_key) {
903 SET_KEY(master_identity_key, id);
904 } else {
905 tor_free(id);
907 if (sign) {
908 SET_KEY(master_signing_key, sign);
909 SET_CERT(signing_key_cert, sign_cert);
911 if (auth) {
912 SET_KEY(current_auth_key, auth);
913 SET_CERT(auth_key_cert, auth_cert);
916 return 0;
917 err:
918 ed25519_keypair_free(id);
919 ed25519_keypair_free(sign);
920 ed25519_keypair_free(auth);
921 tor_cert_free(sign_cert);
922 tor_cert_free(auth_cert);
923 return -1;
926 /* DOCDOC */
928 generate_ed_link_cert(const or_options_t *options, time_t now)
930 const tor_x509_cert_t *link = NULL, *id = NULL;
931 tor_cert_t *link_cert = NULL;
933 if (tor_tls_get_my_certs(1, &link, &id) < 0 || link == NULL) {
934 log_warn(LD_OR, "Can't get my x509 link cert.");
935 return -1;
938 const common_digests_t *digests = tor_x509_cert_get_cert_digests(link);
940 if (link_cert_cert &&
941 ! EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop) &&
942 fast_memeq(digests->d[DIGEST_SHA256], link_cert_cert->signed_key.pubkey,
943 DIGEST256_LEN)) {
944 return 0;
947 ed25519_public_key_t dummy_key;
948 memcpy(dummy_key.pubkey, digests->d[DIGEST_SHA256], DIGEST256_LEN);
950 link_cert = tor_cert_create(get_master_signing_keypair(),
951 CERT_TYPE_SIGNING_LINK,
952 &dummy_key,
953 now,
954 options->TestingLinkCertLifetime, 0);
956 if (link_cert) {
957 SET_CERT(link_cert_cert, link_cert);
959 return 0;
962 #undef FAIL
963 #undef SET_KEY
964 #undef SET_CERT
967 should_make_new_ed_keys(const or_options_t *options, const time_t now)
969 if (!master_identity_key ||
970 !master_signing_key ||
971 !current_auth_key ||
972 !link_cert_cert ||
973 EXPIRES_SOON(signing_key_cert, options->TestingSigningKeySlop) ||
974 EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop) ||
975 EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop))
976 return 1;
978 const tor_x509_cert_t *link = NULL, *id = NULL;
980 if (tor_tls_get_my_certs(1, &link, &id) < 0 || link == NULL)
981 return 1;
983 const common_digests_t *digests = tor_x509_cert_get_cert_digests(link);
985 if (!fast_memeq(digests->d[DIGEST_SHA256],
986 link_cert_cert->signed_key.pubkey,
987 DIGEST256_LEN)) {
988 return 1;
991 return 0;
994 #undef EXPIRES_SOON
996 const ed25519_public_key_t *
997 get_master_identity_key(void)
999 if (!master_identity_key)
1000 return NULL;
1001 return &master_identity_key->pubkey;
1004 const ed25519_keypair_t *
1005 get_master_signing_keypair(void)
1007 return master_signing_key;
1010 const struct tor_cert_st *
1011 get_master_signing_key_cert(void)
1013 return signing_key_cert;
1016 const ed25519_keypair_t *
1017 get_current_auth_keypair(void)
1019 return current_auth_key;
1022 const tor_cert_t *
1023 get_current_link_cert_cert(void)
1025 return link_cert_cert;
1028 const tor_cert_t *
1029 get_current_auth_key_cert(void)
1031 return auth_key_cert;
1034 void
1035 get_master_rsa_crosscert(const uint8_t **cert_out,
1036 size_t *size_out)
1038 *cert_out = rsa_ed_crosscert;
1039 *size_out = rsa_ed_crosscert_len;
1042 /** Construct cross-certification for the master identity key with
1043 * the ntor onion key. Store the sign of the corresponding ed25519 public key
1044 * in *<b>sign_out</b>. */
1045 tor_cert_t *
1046 make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key,
1047 const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime,
1048 int *sign_out)
1050 tor_cert_t *cert = NULL;
1051 ed25519_keypair_t ed_onion_key;
1053 if (ed25519_keypair_from_curve25519_keypair(&ed_onion_key, sign_out,
1054 onion_key) < 0)
1055 goto end;
1057 cert = tor_cert_create(&ed_onion_key, CERT_TYPE_ONION_ID, master_id_key,
1058 now, lifetime, 0);
1060 end:
1061 memwipe(&ed_onion_key, 0, sizeof(ed_onion_key));
1062 return cert;
1065 /** Construct and return an RSA signature for the TAP onion key to
1066 * cross-certify the RSA and Ed25519 identity keys. Set <b>len_out</b> to its
1067 * length. */
1068 uint8_t *
1069 make_tap_onion_key_crosscert(const crypto_pk_t *onion_key,
1070 const ed25519_public_key_t *master_id_key,
1071 const crypto_pk_t *rsa_id_key,
1072 int *len_out)
1074 uint8_t signature[PK_BYTES];
1075 uint8_t signed_data[DIGEST_LEN + ED25519_PUBKEY_LEN];
1077 *len_out = 0;
1078 crypto_pk_get_digest(rsa_id_key, (char*)signed_data);
1079 memcpy(signed_data + DIGEST_LEN, master_id_key->pubkey, ED25519_PUBKEY_LEN);
1081 int r = crypto_pk_private_sign(onion_key,
1082 (char*)signature, sizeof(signature),
1083 (const char*)signed_data, sizeof(signed_data));
1084 if (r < 0)
1085 return NULL;
1087 *len_out = r;
1089 return tor_memdup(signature, r);
1092 /** Check whether an RSA-TAP cross-certification is correct. Return 0 if it
1093 * is, -1 if it isn't. */
1095 check_tap_onion_key_crosscert(const uint8_t *crosscert,
1096 int crosscert_len,
1097 const crypto_pk_t *onion_pkey,
1098 const ed25519_public_key_t *master_id_pkey,
1099 const uint8_t *rsa_id_digest)
1101 uint8_t *cc = tor_malloc(crypto_pk_keysize(onion_pkey));
1102 int cc_len =
1103 crypto_pk_public_checksig(onion_pkey,
1104 (char*)cc,
1105 crypto_pk_keysize(onion_pkey),
1106 (const char*)crosscert,
1107 crosscert_len);
1108 if (cc_len < 0) {
1109 goto err;
1111 if (cc_len < DIGEST_LEN + ED25519_PUBKEY_LEN) {
1112 log_warn(LD_DIR, "Short signature on cross-certification with TAP key");
1113 goto err;
1115 if (tor_memneq(cc, rsa_id_digest, DIGEST_LEN) ||
1116 tor_memneq(cc + DIGEST_LEN, master_id_pkey->pubkey,
1117 ED25519_PUBKEY_LEN)) {
1118 log_warn(LD_DIR, "Incorrect cross-certification with TAP key");
1119 goto err;
1122 tor_free(cc);
1123 return 0;
1124 err:
1125 tor_free(cc);
1126 return -1;
1129 void
1130 routerkeys_free_all(void)
1132 ed25519_keypair_free(master_identity_key);
1133 ed25519_keypair_free(master_signing_key);
1134 ed25519_keypair_free(current_auth_key);
1135 tor_cert_free(signing_key_cert);
1136 tor_cert_free(link_cert_cert);
1137 tor_cert_free(auth_key_cert);
1139 master_identity_key = master_signing_key = NULL;
1140 current_auth_key = NULL;
1141 signing_key_cert = link_cert_cert = auth_key_cert = NULL;