tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

routerkeys.c (35246B)


      1 /* Copyright (c) 2014-2021, The Tor Project, Inc. */
      2 /* See LICENSE for licensing information */
      3 
      4 /**
      5 * \file routerkeys.c
      6 *
      7 * \brief Functions and structures to handle generating and maintaining the
      8 *  set of keypairs necessary to be an OR.
      9 *
     10 * The keys handled here now are the Ed25519 keys that Tor relays use to sign
     11 * descriptors, authenticate themselves on links, and identify one another
     12 * uniquely.  Other keys are maintained in router.c and rendservice.c.
     13 *
     14 * (TODO: The keys in router.c should go here too.)
     15 */
     16 
     17 #define ROUTERKEYS_PRIVATE
     18 
     19 #include "core/or/or.h"
     20 #include "app/config/config.h"
     21 #include "feature/relay/router.h"
     22 #include "feature/relay/routerkeys.h"
     23 #include "feature/relay/routermode.h"
     24 #include "feature/keymgt/loadkey.h"
     25 #include "feature/nodelist/torcert.h"
     26 #include "feature/nodelist/networkstatus_st.h"
     27 #include "feature/dirauth/dirvote.h"
     28 
     29 #include "lib/crypt_ops/crypto_util.h"
     30 #include "lib/crypt_ops/crypto_format.h"
     31 #include "lib/tls/tortls.h"
     32 #include "lib/tls/x509.h"
     33 
     34 #define ENC_KEY_HEADER "Boxed Ed25519 key"
     35 #define ENC_KEY_TAG "master"
     36 
     37 #ifdef HAVE_UNISTD_H
     38 #include <unistd.h>
     39 #endif
     40 
     41 static ed25519_keypair_t *master_identity_key = NULL;
     42 static ed25519_keypair_t *master_signing_key = NULL;
     43 static ed25519_keypair_t *current_auth_key = NULL;
     44 static tor_cert_t *signing_key_cert = NULL;
     45 static tor_cert_t *link_cert_cert = NULL;
     46 static tor_cert_t *auth_key_cert = NULL;
     47 
     48 static uint8_t *rsa_ed_crosscert = NULL;
     49 static size_t rsa_ed_crosscert_len = 0;
     50 static time_t rsa_ed_crosscert_expiration = 0;
     51 
     52 // list of ed25519_keypair_t
     53 static smartlist_t *family_id_keys = NULL;
     54 
     55 /**
     56 * Running as a server: load, reload, or refresh our ed25519 keys and
     57 * certificates, creating and saving new ones as needed.
     58 *
     59 * Return -1 on failure; 0 on success if the signing key was not replaced;
     60 * and 1 on success if the signing key was replaced.
     61 */
     62 int
     63 load_ed_keys(const or_options_t *options, time_t now)
     64 {
     65  ed25519_keypair_t *id = NULL;
     66  ed25519_keypair_t *sign = NULL;
     67  ed25519_keypair_t *auth = NULL;
     68  const ed25519_keypair_t *sign_signing_key_with_id = NULL;
     69  const ed25519_keypair_t *use_signing = NULL;
     70  const tor_cert_t *check_signing_cert = NULL;
     71  tor_cert_t *sign_cert = NULL;
     72  tor_cert_t *auth_cert = NULL;
     73  int signing_key_changed = 0;
     74 
     75  // It is later than 1972, since otherwise there would be no C compilers.
     76  // (Try to diagnose #22466.)
     77  tor_assert_nonfatal(now >= 2 * 365 * 86400);
     78 
     79 #define FAIL(msg) do {                          \
     80    log_warn(LD_OR, (msg));                     \
     81    goto err;                                   \
     82  } while (0)
     83 #define SET_KEY(key, newval) do {               \
     84    if ((key) != (newval))                      \
     85      ed25519_keypair_free(key);                \
     86    key = (newval);                             \
     87  } while (0)
     88 #define SET_CERT(cert, newval) do {             \
     89    if ((cert) != (newval))                     \
     90      tor_cert_free(cert);                      \
     91    cert = (newval);                            \
     92  } while (0)
     93 #define HAPPENS_SOON(when, interval)            \
     94  ((when) < now + (interval))
     95 #define EXPIRES_SOON(cert, interval)            \
     96  (!(cert) || HAPPENS_SOON((cert)->valid_until, (interval)))
     97 
     98  /* XXXX support encrypted identity keys fully */
     99 
    100  /* First try to get the signing key to see how it is. */
    101  {
    102    char *fname =
    103      options_get_keydir_fname(options, "ed25519_signing");
    104    sign = ed_key_init_from_file(
    105               fname,
    106               INIT_ED_KEY_NEEDCERT|
    107               INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT,
    108               LOG_INFO,
    109               NULL, 0, 0, CERT_TYPE_ID_SIGNING, &sign_cert, options);
    110    tor_free(fname);
    111    check_signing_cert = sign_cert;
    112    use_signing = sign;
    113  }
    114 
    115  if (use_signing) {
    116    /* We loaded a signing key with its certificate.  */
    117    if (! master_signing_key) {
    118      /* We didn't know one before! */
    119      signing_key_changed = 1;
    120    } else if (! ed25519_pubkey_eq(&use_signing->pubkey,
    121                                   &master_signing_key->pubkey) ||
    122               ! tor_memeq(use_signing->seckey.seckey,
    123                           master_signing_key->seckey.seckey,
    124                           ED25519_SECKEY_LEN)) {
    125      /* We loaded a different signing key than the one we knew before. */
    126      signing_key_changed = 1;
    127    }
    128  }
    129 
    130  if (!use_signing && master_signing_key) {
    131    /* We couldn't load a signing key, but we already had one loaded */
    132    check_signing_cert = signing_key_cert;
    133    use_signing = master_signing_key;
    134  }
    135 
    136  const int offline_master =
    137    options->OfflineMasterKey && options->command != CMD_KEYGEN;
    138  const int need_new_signing_key =
    139    NULL == use_signing ||
    140    EXPIRES_SOON(check_signing_cert, 0) ||
    141    (options->command == CMD_KEYGEN && ! options->change_key_passphrase);
    142  const int want_new_signing_key =
    143    need_new_signing_key ||
    144    EXPIRES_SOON(check_signing_cert, options->TestingSigningKeySlop);
    145 
    146  /* We can only create a master key if we haven't been told that the
    147   * master key will always be offline.  Also, if we have a signing key,
    148   * then we shouldn't make a new master ID key. */
    149  const int can_make_master_id_key = !offline_master &&
    150    NULL == use_signing;
    151 
    152  if (need_new_signing_key) {
    153    log_notice(LD_OR, "It looks like I need to generate and sign a new "
    154               "medium-term signing key, because %s. To do that, I "
    155               "need to load%s the permanent master identity key. "
    156               "If the master identity key was not moved or encrypted "
    157               "with a passphrase, this will be done automatically and "
    158               "no further action is required. Otherwise, provide the "
    159               "necessary data using 'tor --keygen' to do it manually.",
    160            (NULL == use_signing) ? "I don't have one" :
    161            EXPIRES_SOON(check_signing_cert, 0) ? "the one I have is expired" :
    162               "you asked me to make one with --keygen",
    163            can_make_master_id_key ? " (or create)" : "");
    164  } else if (want_new_signing_key && !offline_master) {
    165    log_notice(LD_OR, "It looks like I should try to generate and sign a "
    166               "new medium-term signing key, because the one I have is "
    167               "going to expire soon. To do that, I'm going to have to "
    168               "try to load the permanent master identity key. "
    169               "If the master identity key was not moved or encrypted "
    170               "with a passphrase, this will be done automatically and "
    171               "no further action is required. Otherwise, provide the "
    172               "necessary data using 'tor --keygen' to do it manually.");
    173  } else if (want_new_signing_key) {
    174    log_notice(LD_OR, "It looks like I should try to generate and sign a "
    175               "new medium-term signing key, because the one I have is "
    176               "going to expire soon. But OfflineMasterKey is set, so I "
    177               "won't try to load a permanent master identity key. You "
    178               "will need to use 'tor --keygen' to make a new signing "
    179               "key and certificate.");
    180  }
    181 
    182  {
    183    uint32_t flags =
    184      (INIT_ED_KEY_SPLIT|
    185       INIT_ED_KEY_EXTRA_STRONG|INIT_ED_KEY_NO_REPAIR);
    186    if (can_make_master_id_key)
    187      flags |= INIT_ED_KEY_CREATE;
    188    if (! need_new_signing_key)
    189      flags |= INIT_ED_KEY_MISSING_SECRET_OK;
    190    if (! want_new_signing_key || offline_master)
    191      flags |= INIT_ED_KEY_OMIT_SECRET;
    192    if (offline_master)
    193      flags |= INIT_ED_KEY_OFFLINE_SECRET;
    194    if (options->command == CMD_KEYGEN)
    195      flags |= INIT_ED_KEY_TRY_ENCRYPTED;
    196 
    197    /* Check/Create the key directory */
    198    if (create_keys_directory(options) < 0)
    199      goto err;
    200 
    201    char *fname;
    202    if (options->master_key_fname) {
    203      fname = tor_strdup(options->master_key_fname);
    204      flags |= INIT_ED_KEY_EXPLICIT_FNAME;
    205    } else {
    206      fname = options_get_keydir_fname(options, "ed25519_master_id");
    207    }
    208    id = ed_key_init_from_file(
    209             fname,
    210             flags,
    211             LOG_WARN, NULL, 0, 0, 0, NULL, options);
    212    tor_free(fname);
    213    if (!id) {
    214      if (need_new_signing_key) {
    215        if (offline_master)
    216          FAIL("Can't load master identity key; OfflineMasterKey is set.");
    217        else
    218          FAIL("Missing identity key");
    219      } else {
    220        log_warn(LD_OR, "Master public key was absent; inferring from "
    221                 "public key in signing certificate and saving to disk.");
    222        tor_assert(check_signing_cert);
    223        id = tor_malloc_zero(sizeof(*id));
    224        memcpy(&id->pubkey, &check_signing_cert->signing_key,
    225               sizeof(ed25519_public_key_t));
    226        fname = options_get_keydir_fname(options,
    227                                         "ed25519_master_id_public_key");
    228        if (ed25519_pubkey_write_to_file(&id->pubkey, fname, "type0") < 0) {
    229          log_warn(LD_OR, "Error while attempting to write master public key "
    230                   "to disk");
    231          tor_free(fname);
    232          goto err;
    233        }
    234        tor_free(fname);
    235      }
    236    }
    237    if (safe_mem_is_zero((char*)id->seckey.seckey, sizeof(id->seckey)))
    238      sign_signing_key_with_id = NULL;
    239    else
    240      sign_signing_key_with_id = id;
    241  }
    242 
    243  if (master_identity_key &&
    244      !ed25519_pubkey_eq(&id->pubkey, &master_identity_key->pubkey)) {
    245    FAIL("Identity key on disk does not match key we loaded earlier!");
    246  }
    247 
    248  if (need_new_signing_key && NULL == sign_signing_key_with_id)
    249    FAIL("Can't load master key make a new signing key.");
    250 
    251  if (sign_cert) {
    252    if (! sign_cert->signing_key_included)
    253      FAIL("Loaded a signing cert with no key included!");
    254    if (! ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey))
    255      FAIL("The signing cert we have was not signed with the master key "
    256           "we loaded!");
    257    if (tor_cert_checksig(sign_cert, &id->pubkey, 0) < 0) {
    258      log_warn(LD_OR, "The signing cert we loaded was not signed "
    259               "correctly: %s!",
    260               tor_cert_describe_signature_status(sign_cert));
    261      goto err;
    262    }
    263  }
    264 
    265  if (want_new_signing_key && sign_signing_key_with_id) {
    266    uint32_t flags = (INIT_ED_KEY_CREATE|
    267                      INIT_ED_KEY_REPLACE|
    268                      INIT_ED_KEY_EXTRA_STRONG|
    269                      INIT_ED_KEY_NEEDCERT|
    270                      INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT);
    271    char *fname =
    272      options_get_keydir_fname(options, "ed25519_signing");
    273    ed25519_keypair_free(sign);
    274    tor_cert_free(sign_cert);
    275    sign = ed_key_init_from_file(fname,
    276                                 flags, LOG_WARN,
    277                                 sign_signing_key_with_id, now,
    278                                 options->SigningKeyLifetime,
    279                                 CERT_TYPE_ID_SIGNING, &sign_cert, options);
    280    tor_free(fname);
    281    if (!sign)
    282      FAIL("Missing signing key");
    283    use_signing = sign;
    284    signing_key_changed = 1;
    285 
    286    tor_assert(sign_cert->signing_key_included);
    287    tor_assert(ed25519_pubkey_eq(&sign_cert->signing_key, &id->pubkey));
    288    tor_assert(ed25519_pubkey_eq(&sign_cert->signed_key, &sign->pubkey));
    289  } else if (want_new_signing_key) {
    290    static ratelim_t missing_master = RATELIM_INIT(3600);
    291    log_fn_ratelim(&missing_master, LOG_WARN, LD_OR,
    292                   "Signing key will expire soon, but I can't load the "
    293                   "master key to sign a new one!");
    294  }
    295 
    296  tor_assert(use_signing);
    297 
    298  /* At this point we no longer need our secret identity key.  So wipe
    299   * it, if we loaded it in the first place. */
    300  memwipe(id->seckey.seckey, 0, sizeof(id->seckey));
    301 
    302  if (options->command == CMD_KEYGEN)
    303    goto end;
    304 
    305  if (server_mode(options) &&
    306      (!rsa_ed_crosscert ||
    307       HAPPENS_SOON(rsa_ed_crosscert_expiration, 30*86400))) {
    308    uint8_t *crosscert;
    309    time_t expiration = now+6*30*86400; /* 6 months in the future. */
    310    ssize_t crosscert_len = tor_make_rsa_ed25519_crosscert(&id->pubkey,
    311                                                   get_server_identity_key(),
    312                                                   expiration,
    313                                                   &crosscert);
    314    tor_free(rsa_ed_crosscert);
    315    rsa_ed_crosscert_len = crosscert_len;
    316    rsa_ed_crosscert = crosscert;
    317    rsa_ed_crosscert_expiration = expiration;
    318  }
    319 
    320  if (!current_auth_key ||
    321      signing_key_changed ||
    322      EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop)) {
    323    auth = ed_key_new(use_signing, INIT_ED_KEY_NEEDCERT,
    324                      now,
    325                      options->TestingAuthKeyLifetime,
    326                      CERT_TYPE_SIGNING_AUTH, &auth_cert);
    327 
    328    if (!auth)
    329      FAIL("Can't create auth key");
    330  }
    331 
    332  /* We've generated or loaded everything.  Put them in memory. */
    333 
    334 end:
    335  if (! master_identity_key) {
    336    SET_KEY(master_identity_key, id);
    337  } else {
    338    tor_free(id);
    339  }
    340  if (sign) {
    341    SET_KEY(master_signing_key, sign);
    342    SET_CERT(signing_key_cert, sign_cert);
    343  }
    344  if (auth) {
    345    SET_KEY(current_auth_key, auth);
    346    SET_CERT(auth_key_cert, auth_cert);
    347  }
    348 
    349  return signing_key_changed;
    350 err:
    351  ed25519_keypair_free(id);
    352  ed25519_keypair_free(sign);
    353  ed25519_keypair_free(auth);
    354  tor_cert_free(sign_cert);
    355  tor_cert_free(auth_cert);
    356  return -1;
    357 }
    358 
    359 /**
    360 * Retrieve our currently-in-use Ed25519 link certificate and id certificate,
    361 * and, if they would expire soon (based on the time <b>now</b>, generate new
    362 * certificates (without embedding the public part of the signing key inside).
    363 * If <b>force</b> is true, always generate a new certificate.
    364 *
    365 * The signed_key from the current id->signing certificate will be used to
    366 * sign the new key within newly generated X509 certificate.
    367 *
    368 * Returns -1 upon error.  Otherwise, returns 0 upon success (either when the
    369 * current certificate is still valid, or when a new certificate was
    370 * successfully generated, or no certificate was needed).
    371 */
    372 int
    373 generate_ed_link_cert(const or_options_t *options, time_t now,
    374                      int force)
    375 {
    376  const tor_x509_cert_t *link_ = NULL, *id = NULL;
    377  tor_cert_t *link_cert = NULL;
    378 
    379  if (tor_tls_get_my_certs(1, &link_, &id) < 0 || link_ == NULL) {
    380    if (!server_mode(options)) {
    381        /* No need to make an Ed25519->Link cert: we are a client */
    382      return 0;
    383    }
    384    log_warn(LD_OR, "Can't get my x509 link cert.");
    385    return -1;
    386  }
    387 
    388  const common_digests_t *digests = tor_x509_cert_get_cert_digests(link_);
    389 
    390  if (force == 0 &&
    391      link_cert_cert &&
    392      ! EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop) &&
    393      fast_memeq(digests->d[DIGEST_SHA256], link_cert_cert->signed_key.pubkey,
    394                 DIGEST256_LEN)) {
    395    return 0;
    396  }
    397 
    398  link_cert = tor_cert_create_raw(get_master_signing_keypair(),
    399                              CERT_TYPE_SIGNING_LINK,
    400                              SIGNED_KEY_TYPE_SHA256_OF_X509,
    401                              (const uint8_t*)digests->d[DIGEST_SHA256],
    402                              now,
    403                              options->TestingLinkCertLifetime, 0);
    404 
    405  if (link_cert) {
    406    SET_CERT(link_cert_cert, link_cert);
    407  }
    408  return 0;
    409 }
    410 
    411 #undef FAIL
    412 #undef SET_KEY
    413 #undef SET_CERT
    414 
    415 /**
    416 * Return 1 if any of the following are true:
    417 *
    418 *   - if one of our Ed25519 signing, auth, or link certificates would expire
    419 *     soon w.r.t. the time <b>now</b>,
    420 *   - if we do not currently have a link certificate, or
    421 *   - if our cached Ed25519 link certificate is not same as the one we're
    422 *     currently using.
    423 *
    424 * Otherwise, returns 0.
    425 */
    426 int
    427 should_make_new_ed_keys(const or_options_t *options, const time_t now)
    428 {
    429  if (!master_identity_key ||
    430      !master_signing_key ||
    431      !current_auth_key ||
    432      !link_cert_cert ||
    433      EXPIRES_SOON(signing_key_cert, options->TestingSigningKeySlop) ||
    434      EXPIRES_SOON(auth_key_cert, options->TestingAuthKeySlop) ||
    435      EXPIRES_SOON(link_cert_cert, options->TestingLinkKeySlop))
    436    return 1;
    437 
    438  const tor_x509_cert_t *link_ = NULL, *id = NULL;
    439 
    440  if (tor_tls_get_my_certs(1, &link_, &id) < 0 || link_ == NULL)
    441    return 1;
    442 
    443  const common_digests_t *digests = tor_x509_cert_get_cert_digests(link_);
    444 
    445  if (!fast_memeq(digests->d[DIGEST_SHA256],
    446                  link_cert_cert->signed_key.pubkey,
    447                  DIGEST256_LEN)) {
    448    return 1;
    449  }
    450 
    451  return 0;
    452 }
    453 
    454 #undef EXPIRES_SOON
    455 #undef HAPPENS_SOON
    456 
    457 #ifdef TOR_UNIT_TESTS
    458 /* Helper for unit tests: populate the ed25519 keys without saving or
    459 * loading */
    460 void
    461 init_mock_ed_keys(const crypto_pk_t *rsa_identity_key)
    462 {
    463  routerkeys_free_all();
    464 
    465 #define MAKEKEY(k)                                      \
    466  k = tor_malloc_zero(sizeof(*k));                      \
    467  if (ed25519_keypair_generate(k, 0) < 0) {             \
    468    log_warn(LD_BUG, "Couldn't make a keypair");        \
    469    goto err;                                           \
    470  }
    471  MAKEKEY(master_identity_key);
    472  MAKEKEY(master_signing_key);
    473  MAKEKEY(current_auth_key);
    474 #define MAKECERT(cert, signing, signed_, type, flags)            \
    475  cert = tor_cert_create_ed25519(signing,                        \
    476                         type,                                   \
    477                         &signed_->pubkey,                       \
    478                         time(NULL), 86400,                      \
    479                         flags);                                 \
    480  if (!cert) {                                                   \
    481    log_warn(LD_BUG, "Couldn't make a %s certificate!", #cert);  \
    482    goto err;                                                    \
    483  }
    484 
    485  MAKECERT(signing_key_cert,
    486           master_identity_key, master_signing_key, CERT_TYPE_ID_SIGNING,
    487           CERT_FLAG_INCLUDE_SIGNING_KEY);
    488  MAKECERT(auth_key_cert,
    489           master_signing_key, current_auth_key, CERT_TYPE_SIGNING_AUTH, 0);
    490 
    491  if (generate_ed_link_cert(get_options(), time(NULL), 0) < 0) {
    492    log_warn(LD_BUG, "Couldn't make link certificate");
    493    goto err;
    494  }
    495 
    496  rsa_ed_crosscert_len = tor_make_rsa_ed25519_crosscert(
    497                                     &master_identity_key->pubkey,
    498                                     rsa_identity_key,
    499                                     time(NULL)+86400,
    500                                     &rsa_ed_crosscert);
    501 
    502  return;
    503 
    504 err:
    505  routerkeys_free_all();
    506  tor_assert_nonfatal_unreached();
    507 }
    508 #undef MAKEKEY
    509 #undef MAKECERT
    510 #endif /* defined(TOR_UNIT_TESTS) */
    511 
    512 /**
    513 * Print the ISO8601-formated <b>expiration</b> for a certificate with
    514 * some <b>description</b> to stdout.
    515 *
    516 * For example, for a signing certificate, this might print out:
    517 * signing-cert-expiry: 2017-07-25 08:30:15 UTC
    518 */
    519 static void
    520 print_cert_expiration(const char *expiration,
    521                      const char *description)
    522 {
    523  fprintf(stderr, "%s-cert-expiry: %s\n", description, expiration);
    524 }
    525 
    526 /**
    527 * Log when a certificate, <b>cert</b>, with some <b>description</b> and
    528 * stored in a file named <b>fname</b>, is going to expire. Formats the expire
    529 * time according to <b>time_format</b>.
    530 */
    531 static void
    532 log_ed_cert_expiration(const tor_cert_t *cert,
    533                       const char *description,
    534                       const char *fname,
    535                       key_expiration_format_t time_format) {
    536  if (BUG(!cert)) { /* If the specified key hasn't been loaded */
    537    log_warn(LD_OR, "No %s key loaded; can't get certificate expiration.",
    538             description);
    539  } else {
    540    char expiration[ISO_TIME_LEN+1];
    541    switch (time_format) {
    542      case KEY_EXPIRATION_FORMAT_ISO8601:
    543        format_local_iso_time(expiration, cert->valid_until);
    544        break;
    545 
    546      case KEY_EXPIRATION_FORMAT_TIMESTAMP:
    547        tor_snprintf(expiration, sizeof(expiration), "%"PRId64,
    548                     (int64_t) cert->valid_until);
    549        break;
    550 
    551      default:
    552        log_err(LD_BUG, "Unknown time format value: %d.", time_format);
    553        return;
    554    }
    555    log_notice(LD_OR, "The %s certificate stored in %s is valid until %s.",
    556               description, fname, expiration);
    557    print_cert_expiration(expiration, description);
    558  }
    559 }
    560 
    561 /**
    562 * Log when our master signing key certificate expires.  Used when tor is given
    563 * the --key-expiration command-line option.
    564 *
    565 * Returns 0 on success and 1 on failure.
    566 */
    567 static int
    568 log_master_signing_key_cert_expiration(const or_options_t *options)
    569 {
    570  const tor_cert_t *signing_key;
    571  char *fn = NULL;
    572  int failed = 0;
    573  time_t now = approx_time();
    574 
    575  fn = options_get_keydir_fname(options, "ed25519_signing_cert");
    576 
    577  /* Try to grab our cached copy of the key. */
    578  signing_key = get_master_signing_key_cert();
    579 
    580  tor_assert(server_identity_key_is_set());
    581 
    582  /* Load our keys from disk, if necessary. */
    583  if (!signing_key) {
    584    failed = load_ed_keys(options, now) < 0;
    585    signing_key = get_master_signing_key_cert();
    586  }
    587 
    588  /* If we do have a signing key, log the expiration time. */
    589  if (signing_key) {
    590    key_expiration_format_t time_format = options->key_expiration_format;
    591    log_ed_cert_expiration(signing_key, "signing", fn, time_format);
    592  } else {
    593    log_warn(LD_OR, "Could not load signing key certificate from %s, so " \
    594             "we couldn't learn anything about certificate expiration.", fn);
    595  }
    596 
    597  tor_free(fn);
    598 
    599  return failed;
    600 }
    601 
    602 /**
    603 * Log when a key certificate expires.  Used when tor is given the
    604 * --key-expiration command-line option.
    605 *
    606 * If an command argument is given, which should specify the type of
    607 * key to get expiry information about (currently supported arguments
    608 * are "sign"), get info about that type of certificate.  Otherwise,
    609 * print info about the supported arguments.
    610 *
    611 * Returns 0 on success and -1 on failure.
    612 */
    613 int
    614 log_cert_expiration(void)
    615 {
    616  const or_options_t *options = get_options();
    617  const char *arg = options->command_arg;
    618 
    619  if (!strcmp(arg, "sign")) {
    620    return log_master_signing_key_cert_expiration(options);
    621  } else {
    622    fprintf(stderr, "No valid argument to --key-expiration found!\n");
    623    fprintf(stderr, "Currently recognised arguments are: 'sign'\n");
    624 
    625    return -1;
    626  }
    627 }
    628 
    629 const ed25519_public_key_t *
    630 get_master_identity_key(void)
    631 {
    632  if (!master_identity_key)
    633    return NULL;
    634  return &master_identity_key->pubkey;
    635 }
    636 
    637 /** Return true iff <b>id</b> is our Ed25519 master identity key. */
    638 int
    639 router_ed25519_id_is_me(const ed25519_public_key_t *id)
    640 {
    641  return id && master_identity_key &&
    642    ed25519_pubkey_eq(id, &master_identity_key->pubkey);
    643 }
    644 
    645 #ifdef TOR_UNIT_TESTS
    646 /* only exists for the unit tests, since otherwise the identity key
    647 * should be used to sign nothing but the signing key. */
    648 const ed25519_keypair_t *
    649 get_master_identity_keypair(void)
    650 {
    651  return master_identity_key;
    652 }
    653 #endif /* defined(TOR_UNIT_TESTS) */
    654 
    655 MOCK_IMPL(const ed25519_keypair_t *,
    656 get_master_signing_keypair,(void))
    657 {
    658  return master_signing_key;
    659 }
    660 
    661 MOCK_IMPL(const struct tor_cert_st *,
    662 get_master_signing_key_cert,(void))
    663 {
    664  return signing_key_cert;
    665 }
    666 
    667 const ed25519_keypair_t *
    668 get_current_auth_keypair(void)
    669 {
    670  return current_auth_key;
    671 }
    672 
    673 const tor_cert_t *
    674 get_current_link_cert_cert(void)
    675 {
    676  return link_cert_cert;
    677 }
    678 
    679 const tor_cert_t *
    680 get_current_auth_key_cert(void)
    681 {
    682  return auth_key_cert;
    683 }
    684 
    685 /**
    686 * Suffix for the filenames in which we expect to find a family ID key.
    687 */
    688 #define FAMILY_KEY_SUFFIX ".secret_family_key"
    689 
    690 /**
    691 * Return true if `fname` is a possible filename of a family ID key.
    692 *
    693 * Family ID key filenames are FAMILY_KEY_FNAME, followed optionally
    694 * by "." and a positive integer.
    695 */
    696 STATIC bool
    697 is_family_key_fname(const char *fname)
    698 {
    699  return 0 == strcmpend(fname, FAMILY_KEY_SUFFIX);
    700 }
    701 
    702 /** Return true if `id` is configured in `options`. */
    703 static bool
    704 family_key_id_is_expected(const or_options_t *options,
    705                          const ed25519_public_key_t *id)
    706 {
    707  if (options->AllFamilyIdsExpected)
    708    return true;
    709 
    710  SMARTLIST_FOREACH(options->FamilyIds, const ed25519_public_key_t *, k, {
    711      if (ed25519_pubkey_eq(k, id))
    712        return true;
    713    });
    714  return false;
    715 }
    716 
    717 /** Return true if the key for `id` has been loaded. */
    718 static bool
    719 family_key_is_present(const ed25519_public_key_t *id)
    720 {
    721  if (!family_id_keys)
    722    return false;
    723 
    724  SMARTLIST_FOREACH(family_id_keys, const ed25519_keypair_t *, kp, {
    725      if (ed25519_pubkey_eq(&kp->pubkey, id))
    726        return true;
    727    });
    728  return false;
    729 }
    730 
    731 /**
    732 * Tag to use on family key files.
    733 */
    734 #define FAMILY_KEY_FILE_TAG "fmly-id"
    735 
    736 /** Return a list of all the possible family-key files in `keydir`.
    737 * Return NULL on error.
    738 *
    739 * (Unlike list_family_key_files, this function does not use a cached
    740 * list when the seccomp2 sandbox is enabled.) */
    741 static smartlist_t *
    742 list_family_key_files_impl(const char *keydir)
    743 {
    744  smartlist_t *files = tor_listdir(keydir);
    745  smartlist_t *result = smartlist_new();
    746 
    747  if (!files) {
    748    log_warn(LD_OR, "Unable to list contents of directory %s", keydir);
    749    goto err;
    750  }
    751 
    752  SMARTLIST_FOREACH_BEGIN(files, const char *, fn) {
    753    if (!is_family_key_fname(fn))
    754      continue;
    755 
    756    smartlist_add_asprintf(result, "%s%s%s", keydir, PATH_SEPARATOR, fn);
    757  } SMARTLIST_FOREACH_END(fn);
    758 
    759  goto done;
    760 err:
    761  SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
    762  smartlist_free(result); // sets result to NULL.
    763 done:
    764  if (files) {
    765    SMARTLIST_FOREACH(files, char *, cp, tor_free(cp));
    766    smartlist_free(files);
    767  }
    768 
    769  return result;
    770 }
    771 
    772 /**
    773 * A list of files returned by list_family_key_files_impl.
    774 * Used when the seccomp2 sandbox is enabled.
    775 */
    776 static smartlist_t *cached_family_key_file_list = NULL;
    777 
    778 /** Return a list of all the possible family-key files in `keydir`.
    779 * Return NULL on error.
    780 */
    781 smartlist_t *
    782 list_family_key_files(const or_options_t *options,
    783                      const char *keydir)
    784 {
    785  if (options->Sandbox) {
    786    if (!cached_family_key_file_list)
    787      cached_family_key_file_list = list_family_key_files_impl(keydir);
    788    if (!cached_family_key_file_list)
    789      return NULL;
    790 
    791    smartlist_t *result = smartlist_new();
    792    SMARTLIST_FOREACH(cached_family_key_file_list, char *, fn,
    793                      smartlist_add_strdup(result, fn));
    794    return result;
    795  }
    796 
    797  return list_family_key_files_impl(keydir);
    798 }
    799 
    800 /**
    801 * Look for all the family keys in `keydir`, load them into
    802 * family_id_keys.
    803 */
    804 STATIC int
    805 load_family_id_keys_impl(const or_options_t *options,
    806                         const char *keydir)
    807 {
    808  if (BUG(!options) || BUG(!keydir))
    809    return -1;
    810 
    811  smartlist_t *key_files = list_family_key_files(options, keydir);
    812  smartlist_t *new_keys = NULL;
    813  ed25519_keypair_t *kp_tmp = NULL;
    814  char *tag_tmp = NULL;
    815  int r = -1;
    816 
    817  if (key_files == NULL) {
    818    goto end; // already warned.
    819  }
    820 
    821  new_keys = smartlist_new();
    822  SMARTLIST_FOREACH_BEGIN(key_files, const char *, fn) {
    823    kp_tmp = tor_malloc_zero(sizeof(*kp_tmp));
    824    // TODO: If we ever allow cert provisioning here,
    825    // use ed_key_init_from_file() instead.
    826    if (ed25519_seckey_read_from_file(&kp_tmp->seckey, &tag_tmp, fn) < 0) {
    827      log_warn(LD_OR, "%s was not an ed25519 secret key.", fn);
    828      goto end;
    829    }
    830    if (0 != strcmp(tag_tmp, FAMILY_KEY_FILE_TAG)) {
    831      log_warn(LD_OR, "%s was not a family ID key.", fn);
    832      goto end;
    833    }
    834    if (ed25519_public_key_generate(&kp_tmp->pubkey, &kp_tmp->seckey) < 0) {
    835      log_warn(LD_OR, "Unable to generate public key for %s", fn);
    836      goto end;
    837    }
    838 
    839    if (family_key_id_is_expected(options, &kp_tmp->pubkey)) {
    840      smartlist_add(new_keys, kp_tmp);
    841      kp_tmp = NULL; // prevent double-free
    842    } else {
    843      log_warn(LD_OR, "Found secret family key in %s "
    844               "with unexpected FamilyID %s",
    845               fn, ed25519_fmt(&kp_tmp->pubkey));
    846    }
    847 
    848    ed25519_keypair_free(kp_tmp);
    849    tor_free(tag_tmp);
    850  } SMARTLIST_FOREACH_END(fn);
    851 
    852  set_family_id_keys(new_keys);
    853  new_keys = NULL; // prevent double-free
    854  r = 0;
    855 end:
    856  if (key_files) {
    857    SMARTLIST_FOREACH(key_files, char *, cp, tor_free(cp));
    858    smartlist_free(key_files);
    859  }
    860  if (new_keys) {
    861    SMARTLIST_FOREACH(new_keys, ed25519_keypair_t *, kp,
    862                      ed25519_keypair_free(kp));
    863    smartlist_free(new_keys);
    864  }
    865  tor_free(tag_tmp);
    866  ed25519_keypair_free(kp_tmp);
    867  return r;
    868 }
    869 
    870 /**
    871 * Create a new family ID key, and store it in `fname`.
    872 *
    873 * If pk_out is provided, set it to the generated public key.
    874 **/
    875 int
    876 create_family_id_key(const char *fname, ed25519_public_key_t *pk_out)
    877 {
    878  int r = -1;
    879  ed25519_keypair_t *kp = tor_malloc_zero(sizeof(ed25519_keypair_t));
    880 
    881  /* Refuse to overwrite an existing family key */
    882  if (file_status(fname) == FN_FILE) {
    883    log_warn(LD_GENERAL,
    884             "Family key file '%s' already exists. "
    885             "Refusing to overwrite existing family key.",
    886             fname);
    887    goto done;
    888  }
    889 
    890  if (ed25519_keypair_generate(kp, 1) < 0) {
    891    log_warn(LD_BUG, "Can't generate ed25519 key!");
    892    goto done;
    893  }
    894 
    895  if (ed25519_seckey_write_to_file(&kp->seckey,
    896                                   fname, FAMILY_KEY_FILE_TAG)<0) {
    897    log_warn(LD_BUG, "Can't write key to file.");
    898    goto done;
    899  }
    900 
    901  if (pk_out) {
    902    ed25519_pubkey_copy(pk_out, &kp->pubkey);
    903  }
    904 
    905  r = 0;
    906 
    907 done:
    908  ed25519_keypair_free(kp);
    909  return r;
    910 }
    911 
    912 /**
    913 * If configured to do so, load our family keys from the key directory.
    914 * Otherwise, clear the family keys.
    915 *
    916 * Additionally, warn about inconsistencies between family options.
    917 * If `ns` is provided, provide additional warnings.
    918 *
    919 * `options` is required; `ns` may be NULL.
    920 */
    921 int
    922 load_family_id_keys(const or_options_t *options,
    923                    const networkstatus_t *ns)
    924 {
    925  if (options->FamilyIds) {
    926    if (load_family_id_keys_impl(options, options->FamilyKeyDirectory) < 0)
    927      return -1;
    928 
    929    bool any_missing = false;
    930    SMARTLIST_FOREACH_BEGIN(options->FamilyIds,
    931                            const ed25519_public_key_t *, id) {
    932        if (!family_key_is_present(id)) {
    933          log_err(LD_OR, "No key was found for listed FamilyID %s",
    934                  ed25519_fmt(id));
    935          any_missing = true;
    936        }
    937    } SMARTLIST_FOREACH_END(id);
    938    if (any_missing)
    939      return -1;
    940 
    941    log_info(LD_OR, "Found %d family ID keys",
    942             smartlist_len(get_current_family_id_keys()));
    943  } else {
    944    set_family_id_keys(NULL);
    945  }
    946  warn_about_family_id_config(options, ns);
    947  return 0;
    948 }
    949 
    950 #define FAMILY_INFO_URL \
    951  "https://community.torproject.org/relay/setup/post-install/family-ids/"
    952 
    953 /** Generate warnings as appropriate about our family ID configuration.
    954 *
    955 * `options` is required; `ns` may be NULL.
    956 */
    957 void
    958 warn_about_family_id_config(const or_options_t *options,
    959                            const networkstatus_t *ns)
    960 {
    961  static int have_warned_absent_myfamily = 0;
    962  static int have_warned_absent_familykeys = 0;
    963 
    964  if (options->FamilyIds) {
    965    if (!have_warned_absent_myfamily &&
    966        !options->MyFamily && ns && should_publish_family_list(ns)) {
    967      log_warn(LD_OR,
    968               "FamilyId was configured, but MyFamily was not. "
    969               "FamilyId is good, but the Tor network still requires "
    970               "MyFamily while clients are migrating to use family "
    971               "keys instead.");
    972      have_warned_absent_myfamily = 1;
    973    }
    974  } else {
    975    if (!have_warned_absent_familykeys &&
    976        options->MyFamily &&
    977        ns && ns->consensus_method >= MIN_METHOD_FOR_FAMILY_IDS) {
    978      log_notice(LD_OR,
    979                 "MyFamily was configured, but FamilyId was not. "
    980                 "It's a good time to start migrating your relays "
    981                 "to use family keys. "
    982                 "See "FAMILY_INFO_URL " for instructions.");
    983      have_warned_absent_familykeys = 1;
    984    }
    985  }
    986 }
    987 
    988 /**
    989 * Return a list of our current family id keypairs,
    990 * as a list of `ed25519_keypair_t`.
    991 *
    992 * Never returns NULL.
    993 *
    994 * TODO PROP321: Right now this is only used in testing;
    995 * when we add relay support we'll need a way to actually
    996 * read these keys from disk.
    997 **/
    998 const smartlist_t *
    999 get_current_family_id_keys(void)
   1000 {
   1001  if (family_id_keys == NULL)
   1002    family_id_keys = smartlist_new();
   1003  return family_id_keys;
   1004 }
   1005 
   1006 /**
   1007 * Replace our list of family ID keys with `family_id_keys`,
   1008 * which must be a list of `ed25519_keypair_t`.
   1009 *
   1010 * Takes ownership of its input.
   1011 */
   1012 STATIC void
   1013 set_family_id_keys(smartlist_t *keys)
   1014 {
   1015  if (family_id_keys) {
   1016    SMARTLIST_FOREACH(family_id_keys, ed25519_keypair_t *, kp,
   1017                      ed25519_keypair_free(kp));
   1018    smartlist_free(family_id_keys);
   1019  }
   1020  family_id_keys = keys;
   1021 }
   1022 
   1023 void
   1024 get_master_rsa_crosscert(const uint8_t **cert_out,
   1025                         size_t *size_out)
   1026 {
   1027  *cert_out = rsa_ed_crosscert;
   1028  *size_out = rsa_ed_crosscert_len;
   1029 }
   1030 
   1031 /** Construct cross-certification for the master identity key with
   1032 * the ntor onion key. Store the sign of the corresponding ed25519 public key
   1033 * in *<b>sign_out</b>. */
   1034 tor_cert_t *
   1035 make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key,
   1036      const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime,
   1037      int *sign_out)
   1038 {
   1039  tor_cert_t *cert = NULL;
   1040  ed25519_keypair_t ed_onion_key;
   1041 
   1042  if (ed25519_keypair_from_curve25519_keypair(&ed_onion_key, sign_out,
   1043                                              onion_key) < 0)
   1044    goto end;
   1045 
   1046  cert = tor_cert_create_ed25519(&ed_onion_key, CERT_TYPE_ONION_ID,
   1047                                  master_id_key, now, lifetime, 0);
   1048 
   1049 end:
   1050  memwipe(&ed_onion_key, 0, sizeof(ed_onion_key));
   1051  return cert;
   1052 }
   1053 
   1054 /** Construct and return an RSA signature for the TAP onion key to
   1055 * cross-certify the RSA and Ed25519 identity keys. Set <b>len_out</b> to its
   1056 * length. */
   1057 uint8_t *
   1058 make_tap_onion_key_crosscert(const crypto_pk_t *onion_key,
   1059                             const ed25519_public_key_t *master_id_key,
   1060                             const crypto_pk_t *rsa_id_key,
   1061                             int *len_out)
   1062 {
   1063  uint8_t signature[PK_BYTES];
   1064  uint8_t signed_data[DIGEST_LEN + ED25519_PUBKEY_LEN];
   1065 
   1066  *len_out = 0;
   1067  if (crypto_pk_get_digest(rsa_id_key, (char*)signed_data) < 0) {
   1068    log_info(LD_OR, "crypto_pk_get_digest failed in "
   1069                    "make_tap_onion_key_crosscert!");
   1070    return NULL;
   1071  }
   1072  memcpy(signed_data + DIGEST_LEN, master_id_key->pubkey, ED25519_PUBKEY_LEN);
   1073 
   1074  int r = crypto_pk_private_sign(onion_key,
   1075                               (char*)signature, sizeof(signature),
   1076                               (const char*)signed_data, sizeof(signed_data));
   1077  if (r < 0) {
   1078    /* It's probably missing the private key */
   1079    log_info(LD_OR, "crypto_pk_private_sign failed in "
   1080                    "make_tap_onion_key_crosscert!");
   1081    return NULL;
   1082  }
   1083 
   1084  *len_out = r;
   1085 
   1086  return tor_memdup(signature, r);
   1087 }
   1088 
   1089 void
   1090 routerkeys_free_all(void)
   1091 {
   1092  ed25519_keypair_free(master_identity_key);
   1093  ed25519_keypair_free(master_signing_key);
   1094  ed25519_keypair_free(current_auth_key);
   1095  set_family_id_keys(NULL);
   1096 
   1097  tor_cert_free(signing_key_cert);
   1098  tor_cert_free(link_cert_cert);
   1099  tor_cert_free(auth_key_cert);
   1100  tor_free(rsa_ed_crosscert);
   1101 
   1102  if (cached_family_key_file_list) {
   1103    SMARTLIST_FOREACH(cached_family_key_file_list, char *, cp, tor_free(cp));
   1104    smartlist_free(cached_family_key_file_list);
   1105  }
   1106 
   1107  master_identity_key = master_signing_key = NULL;
   1108  current_auth_key = NULL;
   1109  signing_key_cert = link_cert_cert = auth_key_cert = NULL;
   1110  rsa_ed_crosscert = NULL; // redundant
   1111  rsa_ed_crosscert_len = 0;
   1112 }