loadkey.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file loadkey.c
  8. * \brief Read keys from disk, creating as needed
  9. *
  10. * This code is shared by relays and onion services, which both need
  11. * this functionality.
  12. **/
  13. #include "core/or/or.h"
  14. #include "app/config/config.h"
  15. #include "app/main/main.h"
  16. #include "feature/keymgt/loadkey.h"
  17. #include "feature/nodelist/torcert.h"
  18. #include "lib/crypt_ops/crypto_pwbox.h"
  19. #include "lib/crypt_ops/crypto_util.h"
  20. #include "lib/term/getpass.h"
  21. #include "lib/crypt_ops/crypto_format.h"
  22. #define ENC_KEY_HEADER "Boxed Ed25519 key"
  23. #define ENC_KEY_TAG "master"
  24. #ifdef HAVE_UNISTD_H
  25. #include <unistd.h>
  26. #endif
  27. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  28. * and <b>generate</b> is true, create a new RSA key and save it in
  29. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  30. * errors at level <b>severity</b>. If <b>created_out/b> is non-NULL and a
  31. * new key was created, set *<b>created_out</b> to true.
  32. */
  33. crypto_pk_t *
  34. init_key_from_file(const char *fname, int generate, int severity,
  35. bool *created_out)
  36. {
  37. crypto_pk_t *prkey = NULL;
  38. if (created_out) {
  39. *created_out = false;
  40. }
  41. if (!(prkey = crypto_pk_new())) {
  42. tor_log(severity, LD_GENERAL,"Error constructing key");
  43. goto error;
  44. }
  45. switch (file_status(fname)) {
  46. case FN_DIR:
  47. case FN_ERROR:
  48. tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  49. goto error;
  50. /* treat empty key files as if the file doesn't exist, and,
  51. * if generate is set, replace the empty file in
  52. * crypto_pk_write_private_key_to_filename() */
  53. case FN_NOENT:
  54. case FN_EMPTY:
  55. if (generate) {
  56. if (!have_lockfile()) {
  57. if (try_locking(get_options(), 0)<0) {
  58. /* Make sure that --list-fingerprint only creates new keys
  59. * if there is no possibility for a deadlock. */
  60. tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
  61. "Not writing any new keys.", fname);
  62. /*XXXX The 'other process' might make a key in a second or two;
  63. * maybe we should wait for it. */
  64. goto error;
  65. }
  66. }
  67. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  68. fname);
  69. if (crypto_pk_generate_key(prkey)) {
  70. tor_log(severity, LD_GENERAL,"Error generating onion key");
  71. goto error;
  72. }
  73. if (! crypto_pk_is_valid_private_key(prkey)) {
  74. tor_log(severity, LD_GENERAL,"Generated key seems invalid");
  75. goto error;
  76. }
  77. log_info(LD_GENERAL, "Generated key seems valid");
  78. if (created_out) {
  79. *created_out = true;
  80. }
  81. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  82. tor_log(severity, LD_FS,
  83. "Couldn't write generated key to \"%s\".", fname);
  84. goto error;
  85. }
  86. } else {
  87. tor_log(severity, LD_GENERAL, "No key found in \"%s\"", fname);
  88. goto error;
  89. }
  90. return prkey;
  91. case FN_FILE:
  92. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  93. tor_log(severity, LD_GENERAL,"Error loading private key.");
  94. goto error;
  95. }
  96. return prkey;
  97. default:
  98. tor_assert(0);
  99. }
  100. error:
  101. if (prkey)
  102. crypto_pk_free(prkey);
  103. return NULL;
  104. }
  105. /* DOCDOC */
  106. static ssize_t
  107. do_getpass(const char *prompt, char *buf, size_t buflen,
  108. int twice, const or_options_t *options)
  109. {
  110. if (options->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
  111. tor_assert(buflen);
  112. buf[0] = 0;
  113. return 0;
  114. }
  115. char *prompt2 = NULL;
  116. char *buf2 = NULL;
  117. int fd = -1;
  118. ssize_t length = -1;
  119. if (options->use_keygen_passphrase_fd) {
  120. twice = 0;
  121. fd = options->keygen_passphrase_fd;
  122. length = read_all_from_fd(fd, buf, buflen-1);
  123. if (length >= 0)
  124. buf[length] = 0;
  125. goto done_reading;
  126. }
  127. if (twice) {
  128. const char msg[] = "One more time:";
  129. size_t p2len = strlen(prompt) + 1;
  130. if (p2len < sizeof(msg))
  131. p2len = sizeof(msg);
  132. prompt2 = tor_malloc(p2len);
  133. memset(prompt2, ' ', p2len);
  134. memcpy(prompt2 + p2len - sizeof(msg), msg, sizeof(msg));
  135. buf2 = tor_malloc_zero(buflen);
  136. }
  137. while (1) {
  138. length = tor_getpass(prompt, buf, buflen);
  139. if (length < 0)
  140. goto done_reading;
  141. if (! twice)
  142. break;
  143. ssize_t length2 = tor_getpass(prompt2, buf2, buflen);
  144. if (length != length2 || tor_memneq(buf, buf2, length)) {
  145. fprintf(stderr, "That didn't match.\n");
  146. } else {
  147. break;
  148. }
  149. }
  150. done_reading:
  151. if (twice) {
  152. tor_free(prompt2);
  153. memwipe(buf2, 0, buflen);
  154. tor_free(buf2);
  155. }
  156. if (options->keygen_force_passphrase == FORCE_PASSPHRASE_ON && length == 0)
  157. return -1;
  158. return length;
  159. }
  160. /* DOCDOC */
  161. int
  162. read_encrypted_secret_key(ed25519_secret_key_t *out,
  163. const char *fname)
  164. {
  165. int r = -1;
  166. uint8_t *secret = NULL;
  167. size_t secret_len = 0;
  168. char pwbuf[256];
  169. uint8_t encrypted_key[256];
  170. char *tag = NULL;
  171. int saved_errno = 0;
  172. ssize_t encrypted_len = crypto_read_tagged_contents_from_file(fname,
  173. ENC_KEY_HEADER,
  174. &tag,
  175. encrypted_key,
  176. sizeof(encrypted_key));
  177. if (encrypted_len < 0) {
  178. saved_errno = errno;
  179. log_info(LD_OR, "%s is missing", fname);
  180. r = 0;
  181. goto done;
  182. }
  183. if (strcmp(tag, ENC_KEY_TAG)) {
  184. saved_errno = EINVAL;
  185. goto done;
  186. }
  187. while (1) {
  188. ssize_t pwlen =
  189. do_getpass("Enter passphrase for master key:", pwbuf, sizeof(pwbuf), 0,
  190. get_options());
  191. if (pwlen < 0) {
  192. saved_errno = EINVAL;
  193. goto done;
  194. }
  195. const int r_unbox = crypto_unpwbox(&secret, &secret_len,
  196. encrypted_key, encrypted_len,
  197. pwbuf, pwlen);
  198. if (r_unbox == UNPWBOX_CORRUPTED) {
  199. log_err(LD_OR, "%s is corrupted.", fname);
  200. saved_errno = EINVAL;
  201. goto done;
  202. } else if (r_unbox == UNPWBOX_OKAY) {
  203. break;
  204. }
  205. /* Otherwise, passphrase is bad, so try again till user does ctrl-c or gets
  206. * it right. */
  207. }
  208. if (secret_len != ED25519_SECKEY_LEN) {
  209. log_err(LD_OR, "%s is corrupted.", fname);
  210. saved_errno = EINVAL;
  211. goto done;
  212. }
  213. memcpy(out->seckey, secret, ED25519_SECKEY_LEN);
  214. r = 1;
  215. done:
  216. memwipe(encrypted_key, 0, sizeof(encrypted_key));
  217. memwipe(pwbuf, 0, sizeof(pwbuf));
  218. tor_free(tag);
  219. if (secret) {
  220. memwipe(secret, 0, secret_len);
  221. tor_free(secret);
  222. }
  223. if (saved_errno)
  224. errno = saved_errno;
  225. return r;
  226. }
  227. /* DOCDOC */
  228. int
  229. write_encrypted_secret_key(const ed25519_secret_key_t *key,
  230. const char *fname)
  231. {
  232. int r = -1;
  233. char pwbuf0[256];
  234. uint8_t *encrypted_key = NULL;
  235. size_t encrypted_len = 0;
  236. if (do_getpass("Enter new passphrase:", pwbuf0, sizeof(pwbuf0), 1,
  237. get_options()) < 0) {
  238. log_warn(LD_OR, "NO/failed passphrase");
  239. return -1;
  240. }
  241. if (strlen(pwbuf0) == 0) {
  242. if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_ON)
  243. return -1;
  244. else
  245. return 0;
  246. }
  247. if (crypto_pwbox(&encrypted_key, &encrypted_len,
  248. key->seckey, sizeof(key->seckey),
  249. pwbuf0, strlen(pwbuf0), 0) < 0) {
  250. log_warn(LD_OR, "crypto_pwbox failed!?");
  251. goto done;
  252. }
  253. if (crypto_write_tagged_contents_to_file(fname,
  254. ENC_KEY_HEADER,
  255. ENC_KEY_TAG,
  256. encrypted_key, encrypted_len) < 0)
  257. goto done;
  258. r = 1;
  259. done:
  260. if (encrypted_key) {
  261. memwipe(encrypted_key, 0, encrypted_len);
  262. tor_free(encrypted_key);
  263. }
  264. memwipe(pwbuf0, 0, sizeof(pwbuf0));
  265. return r;
  266. }
  267. /* DOCDOC */
  268. static int
  269. write_secret_key(const ed25519_secret_key_t *key, int encrypted,
  270. const char *fname,
  271. const char *fname_tag,
  272. const char *encrypted_fname)
  273. {
  274. if (encrypted) {
  275. int r = write_encrypted_secret_key(key, encrypted_fname);
  276. if (r == 1) {
  277. /* Success! */
  278. /* Try to unlink the unencrypted key, if any existed before */
  279. if (strcmp(fname, encrypted_fname))
  280. unlink(fname);
  281. return r;
  282. } else if (r != 0) {
  283. /* Unrecoverable failure! */
  284. return r;
  285. }
  286. fprintf(stderr, "Not encrypting the secret key.\n");
  287. }
  288. return ed25519_seckey_write_to_file(key, fname, fname_tag);
  289. }
  290. /**
  291. * Read an ed25519 key and associated certificates from files beginning with
  292. * <b>fname</b>, with certificate type <b>cert_type</b>. On failure, return
  293. * NULL; on success return the keypair.
  294. *
  295. * The <b>options</b> is used to look at the change_key_passphrase value when
  296. * writing to disk a secret key. It is safe to be NULL even in that case.
  297. *
  298. * If INIT_ED_KEY_CREATE is set in <b>flags</b>, then create the key (and
  299. * certificate if requested) if it doesn't exist, and save it to disk.
  300. *
  301. * If INIT_ED_KEY_NEEDCERT is set in <b>flags</b>, load/create a certificate
  302. * too and store it in *<b>cert_out</b>. Fail if the cert can't be
  303. * found/created. To create a certificate, <b>signing_key</b> must be set to
  304. * the key that should sign it; <b>now</b> to the current time, and
  305. * <b>lifetime</b> to the lifetime of the key.
  306. *
  307. * If INIT_ED_KEY_REPLACE is set in <b>flags</b>, then create and save new key
  308. * whether we can read the old one or not.
  309. *
  310. * If INIT_ED_KEY_EXTRA_STRONG is set in <b>flags</b>, set the extra_strong
  311. * flag when creating the secret key.
  312. *
  313. * If INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT is set in <b>flags</b>, and
  314. * we create a new certificate, create it with the signing key embedded.
  315. *
  316. * If INIT_ED_KEY_SPLIT is set in <b>flags</b>, and we create a new key,
  317. * store the public key in a separate file from the secret key.
  318. *
  319. * If INIT_ED_KEY_MISSING_SECRET_OK is set in <b>flags</b>, and we find a
  320. * public key file but no secret key file, return successfully anyway.
  321. *
  322. * If INIT_ED_KEY_OMIT_SECRET is set in <b>flags</b>, do not try to load a
  323. * secret key unless no public key is found. Do not return a secret key. (but
  324. * create and save one if needed).
  325. *
  326. * If INIT_ED_KEY_TRY_ENCRYPTED is set, we look for an encrypted secret key
  327. * and consider encrypting any new secret key.
  328. *
  329. * If INIT_ED_KEY_NO_REPAIR is set, and there is any issue loading the keys
  330. * from disk _other than their absence_ (full or partial), we do not try to
  331. * replace them.
  332. *
  333. * If INIT_ED_KEY_SUGGEST_KEYGEN is set, have log messages about failures
  334. * refer to the --keygen option.
  335. *
  336. * If INIT_ED_KEY_EXPLICIT_FNAME is set, use the provided file name for the
  337. * secret key file, encrypted or not.
  338. *
  339. * If INIT_ED_KEY_OFFLINE_SECRET is set, we won't try to load the master
  340. * secret key and we log a message at <b>severity</b> that we've done so.
  341. */
  342. ed25519_keypair_t *
  343. ed_key_init_from_file(const char *fname, uint32_t flags,
  344. int severity,
  345. const ed25519_keypair_t *signing_key,
  346. time_t now,
  347. time_t lifetime,
  348. uint8_t cert_type,
  349. struct tor_cert_st **cert_out,
  350. const or_options_t *options)
  351. {
  352. char *secret_fname = NULL;
  353. char *encrypted_secret_fname = NULL;
  354. char *public_fname = NULL;
  355. char *cert_fname = NULL;
  356. const char *loaded_secret_fname = NULL;
  357. int created_pk = 0, created_sk = 0, created_cert = 0;
  358. const int try_to_load = ! (flags & INIT_ED_KEY_REPLACE);
  359. const int encrypt_key = !! (flags & INIT_ED_KEY_TRY_ENCRYPTED);
  360. const int norepair = !! (flags & INIT_ED_KEY_NO_REPAIR);
  361. const int split = !! (flags & INIT_ED_KEY_SPLIT);
  362. const int omit_secret = !! (flags & INIT_ED_KEY_OMIT_SECRET);
  363. const int offline_secret = !! (flags & INIT_ED_KEY_OFFLINE_SECRET);
  364. const int explicit_fname = !! (flags & INIT_ED_KEY_EXPLICIT_FNAME);
  365. /* we don't support setting both of these flags at once. */
  366. tor_assert((flags & (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT)) !=
  367. (INIT_ED_KEY_NO_REPAIR|INIT_ED_KEY_NEEDCERT));
  368. char tag[8];
  369. tor_snprintf(tag, sizeof(tag), "type%d", (int)cert_type);
  370. tor_cert_t *cert = NULL;
  371. char *got_tag = NULL;
  372. ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
  373. if (explicit_fname) {
  374. secret_fname = tor_strdup(fname);
  375. encrypted_secret_fname = tor_strdup(fname);
  376. } else {
  377. tor_asprintf(&secret_fname, "%s_secret_key", fname);
  378. tor_asprintf(&encrypted_secret_fname, "%s_secret_key_encrypted", fname);
  379. }
  380. tor_asprintf(&public_fname, "%s_public_key", fname);
  381. tor_asprintf(&cert_fname, "%s_cert", fname);
  382. /* Try to read the secret key. */
  383. int have_secret = 0;
  384. int load_secret = try_to_load &&
  385. !offline_secret &&
  386. (!omit_secret || file_status(public_fname)==FN_NOENT);
  387. if (load_secret) {
  388. int rv = ed25519_seckey_read_from_file(&keypair->seckey,
  389. &got_tag, secret_fname);
  390. if (rv == 0) {
  391. have_secret = 1;
  392. loaded_secret_fname = secret_fname;
  393. tor_assert(got_tag);
  394. } else {
  395. if (errno != ENOENT && norepair) {
  396. tor_log(severity, LD_OR, "Unable to read %s: %s", secret_fname,
  397. strerror(errno));
  398. goto err;
  399. }
  400. }
  401. }
  402. /* Should we try for an encrypted key? */
  403. int have_encrypted_secret_file = 0;
  404. if (!have_secret && try_to_load && encrypt_key) {
  405. int r = read_encrypted_secret_key(&keypair->seckey,
  406. encrypted_secret_fname);
  407. if (r > 0) {
  408. have_secret = 1;
  409. have_encrypted_secret_file = 1;
  410. tor_free(got_tag); /* convince coverity we aren't leaking */
  411. got_tag = tor_strdup(tag);
  412. loaded_secret_fname = encrypted_secret_fname;
  413. } else if (errno != ENOENT && norepair) {
  414. tor_log(severity, LD_OR, "Unable to read %s: %s",
  415. encrypted_secret_fname, strerror(errno));
  416. goto err;
  417. }
  418. } else {
  419. if (try_to_load) {
  420. /* Check if it's there anyway, so we don't replace it. */
  421. if (file_status(encrypted_secret_fname) != FN_NOENT)
  422. have_encrypted_secret_file = 1;
  423. }
  424. }
  425. if (have_secret) {
  426. if (strcmp(got_tag, tag)) {
  427. tor_log(severity, LD_OR, "%s has wrong tag", loaded_secret_fname);
  428. goto err;
  429. }
  430. /* Derive the public key */
  431. if (ed25519_public_key_generate(&keypair->pubkey, &keypair->seckey)<0) {
  432. tor_log(severity, LD_OR, "%s can't produce a public key",
  433. loaded_secret_fname);
  434. goto err;
  435. }
  436. }
  437. /* If we do split keys here, try to read the pubkey. */
  438. int found_public = 0;
  439. if (try_to_load && (!have_secret || split)) {
  440. ed25519_public_key_t pubkey_tmp;
  441. tor_free(got_tag);
  442. found_public = ed25519_pubkey_read_from_file(&pubkey_tmp,
  443. &got_tag, public_fname) == 0;
  444. if (!found_public && errno != ENOENT && norepair) {
  445. tor_log(severity, LD_OR, "Unable to read %s: %s", public_fname,
  446. strerror(errno));
  447. goto err;
  448. }
  449. if (found_public && strcmp(got_tag, tag)) {
  450. tor_log(severity, LD_OR, "%s has wrong tag", public_fname);
  451. goto err;
  452. }
  453. if (found_public) {
  454. if (have_secret) {
  455. /* If we have a secret key and we're reloading the public key,
  456. * the key must match! */
  457. if (! ed25519_pubkey_eq(&keypair->pubkey, &pubkey_tmp)) {
  458. tor_log(severity, LD_OR, "%s does not match %s! If you are trying "
  459. "to restore from backup, make sure you didn't mix up the "
  460. "key files. If you are absolutely sure that %s is the right "
  461. "key for this relay, delete %s or move it out of the way.",
  462. public_fname, loaded_secret_fname,
  463. loaded_secret_fname, public_fname);
  464. goto err;
  465. }
  466. } else {
  467. /* We only have the public key; better use that. */
  468. tor_assert(split);
  469. memcpy(&keypair->pubkey, &pubkey_tmp, sizeof(pubkey_tmp));
  470. }
  471. } else {
  472. /* We have no public key file, but we do have a secret key, make the
  473. * public key file! */
  474. if (have_secret) {
  475. if (ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag)
  476. < 0) {
  477. tor_log(severity, LD_OR, "Couldn't repair %s", public_fname);
  478. goto err;
  479. } else {
  480. tor_log(LOG_NOTICE, LD_OR,
  481. "Found secret key but not %s. Regenerating.",
  482. public_fname);
  483. }
  484. }
  485. }
  486. }
  487. /* If the secret key is absent and it's not allowed to be, fail. */
  488. if (!have_secret && found_public &&
  489. !(flags & INIT_ED_KEY_MISSING_SECRET_OK)) {
  490. if (have_encrypted_secret_file) {
  491. tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
  492. "but it was encrypted. Try 'tor --keygen' instead, so you "
  493. "can enter the passphrase.",
  494. secret_fname);
  495. } else if (offline_secret) {
  496. tor_log(severity, LD_OR, "We wanted to load a secret key from %s, "
  497. "but you're keeping it offline. (OfflineMasterKey is set.)",
  498. secret_fname);
  499. } else {
  500. tor_log(severity, LD_OR, "We needed to load a secret key from %s, "
  501. "but couldn't find it. %s", secret_fname,
  502. (flags & INIT_ED_KEY_SUGGEST_KEYGEN) ?
  503. "If you're keeping your master secret key offline, you will "
  504. "need to run 'tor --keygen' to generate new signing keys." :
  505. "Did you forget to copy it over when you copied the rest of the "
  506. "signing key material?");
  507. }
  508. goto err;
  509. }
  510. /* If it's absent, and we're not supposed to make a new keypair, fail. */
  511. if (!have_secret && !found_public && !(flags & INIT_ED_KEY_CREATE)) {
  512. if (split) {
  513. tor_log(severity, LD_OR, "No key found in %s or %s.",
  514. secret_fname, public_fname);
  515. } else {
  516. tor_log(severity, LD_OR, "No key found in %s.", secret_fname);
  517. }
  518. goto err;
  519. }
  520. /* If the secret key is absent, but the encrypted key would be present,
  521. * that's an error */
  522. if (!have_secret && !found_public && have_encrypted_secret_file) {
  523. tor_assert(!encrypt_key);
  524. tor_log(severity, LD_OR, "Found an encrypted secret key, "
  525. "but not public key file %s!", public_fname);
  526. goto err;
  527. }
  528. /* if it's absent, make a new keypair... */
  529. if (!have_secret && !found_public) {
  530. tor_free(keypair);
  531. keypair = ed_key_new(signing_key, flags, now, lifetime,
  532. cert_type, &cert);
  533. if (!keypair) {
  534. tor_log(severity, LD_OR, "Couldn't create keypair");
  535. goto err;
  536. }
  537. created_pk = created_sk = created_cert = 1;
  538. }
  539. /* Write it to disk if we're supposed to do with a new passphrase, or if
  540. * we just created it. */
  541. if (created_sk || (have_secret && options != NULL &&
  542. options->change_key_passphrase)) {
  543. if (write_secret_key(&keypair->seckey,
  544. encrypt_key,
  545. secret_fname, tag, encrypted_secret_fname) < 0
  546. ||
  547. (split &&
  548. ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag) < 0)
  549. ||
  550. (cert &&
  551. crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
  552. tag, cert->encoded, cert->encoded_len) < 0)) {
  553. tor_log(severity, LD_OR, "Couldn't write keys or cert to file.");
  554. goto err;
  555. }
  556. goto done;
  557. }
  558. /* If we're not supposed to get a cert, we're done. */
  559. if (! (flags & INIT_ED_KEY_NEEDCERT))
  560. goto done;
  561. /* Read a cert. */
  562. tor_free(got_tag);
  563. uint8_t certbuf[256];
  564. ssize_t cert_body_len = crypto_read_tagged_contents_from_file(
  565. cert_fname, "ed25519v1-cert",
  566. &got_tag, certbuf, sizeof(certbuf));
  567. if (cert_body_len >= 0 && !strcmp(got_tag, tag))
  568. cert = tor_cert_parse(certbuf, cert_body_len);
  569. /* If we got it, check it to the extent we can. */
  570. int bad_cert = 0;
  571. if (! cert) {
  572. tor_log(severity, LD_OR, "Cert was unparseable");
  573. bad_cert = 1;
  574. } else if (!tor_memeq(cert->signed_key.pubkey, keypair->pubkey.pubkey,
  575. ED25519_PUBKEY_LEN)) {
  576. tor_log(severity, LD_OR, "Cert was for wrong key");
  577. bad_cert = 1;
  578. } else if (signing_key &&
  579. tor_cert_checksig(cert, &signing_key->pubkey, now) < 0) {
  580. tor_log(severity, LD_OR, "Can't check certificate: %s",
  581. tor_cert_describe_signature_status(cert));
  582. bad_cert = 1;
  583. } else if (cert->cert_expired) {
  584. tor_log(severity, LD_OR, "Certificate is expired");
  585. bad_cert = 1;
  586. } else if (signing_key && cert->signing_key_included &&
  587. ! ed25519_pubkey_eq(&signing_key->pubkey, &cert->signing_key)) {
  588. tor_log(severity, LD_OR, "Certificate signed by unexpectd key!");
  589. bad_cert = 1;
  590. }
  591. if (bad_cert) {
  592. tor_cert_free(cert);
  593. cert = NULL;
  594. }
  595. /* If we got a cert, we're done. */
  596. if (cert)
  597. goto done;
  598. /* If we didn't get a cert, and we're not supposed to make one, fail. */
  599. if (!signing_key || !(flags & INIT_ED_KEY_CREATE)) {
  600. tor_log(severity, LD_OR, "Without signing key, can't create certificate");
  601. goto err;
  602. }
  603. /* We have keys but not a certificate, so make one. */
  604. uint32_t cert_flags = 0;
  605. if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
  606. cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
  607. cert = tor_cert_create(signing_key, cert_type,
  608. &keypair->pubkey,
  609. now, lifetime,
  610. cert_flags);
  611. if (! cert) {
  612. tor_log(severity, LD_OR, "Couldn't create certificate");
  613. goto err;
  614. }
  615. /* Write it to disk. */
  616. created_cert = 1;
  617. if (crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
  618. tag, cert->encoded, cert->encoded_len) < 0) {
  619. tor_log(severity, LD_OR, "Couldn't write cert to disk.");
  620. goto err;
  621. }
  622. done:
  623. if (cert_out)
  624. *cert_out = cert;
  625. else
  626. tor_cert_free(cert);
  627. goto cleanup;
  628. err:
  629. if (keypair)
  630. memwipe(keypair, 0, sizeof(*keypair));
  631. tor_free(keypair);
  632. tor_cert_free(cert);
  633. if (cert_out)
  634. *cert_out = NULL;
  635. if (created_sk)
  636. unlink(secret_fname);
  637. if (created_pk)
  638. unlink(public_fname);
  639. if (created_cert)
  640. unlink(cert_fname);
  641. cleanup:
  642. tor_free(encrypted_secret_fname);
  643. tor_free(secret_fname);
  644. tor_free(public_fname);
  645. tor_free(cert_fname);
  646. tor_free(got_tag);
  647. return keypair;
  648. }
  649. /**
  650. * Create a new signing key and (optionally) certficiate; do not read or write
  651. * from disk. See ed_key_init_from_file() for more information.
  652. */
  653. ed25519_keypair_t *
  654. ed_key_new(const ed25519_keypair_t *signing_key,
  655. uint32_t flags,
  656. time_t now,
  657. time_t lifetime,
  658. uint8_t cert_type,
  659. struct tor_cert_st **cert_out)
  660. {
  661. if (cert_out)
  662. *cert_out = NULL;
  663. const int extra_strong = !! (flags & INIT_ED_KEY_EXTRA_STRONG);
  664. ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
  665. if (ed25519_keypair_generate(keypair, extra_strong) < 0)
  666. goto err;
  667. if (! (flags & INIT_ED_KEY_NEEDCERT))
  668. return keypair;
  669. tor_assert(signing_key);
  670. tor_assert(cert_out);
  671. uint32_t cert_flags = 0;
  672. if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
  673. cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
  674. tor_cert_t *cert = tor_cert_create(signing_key, cert_type,
  675. &keypair->pubkey,
  676. now, lifetime,
  677. cert_flags);
  678. if (! cert)
  679. goto err;
  680. *cert_out = cert;
  681. return keypair;
  682. err:
  683. tor_free(keypair);
  684. return NULL;
  685. }