crypto_ed25519.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. /* Copyright (c) 2013-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file crypto_ed25519.c
  5. *
  6. * \brief Wrapper code for an ed25519 implementation.
  7. *
  8. * Ed25519 is a Schnorr signature on a Twisted Edwards curve, defined
  9. * by Dan Bernstein. For more information, see https://ed25519.cr.yp.to/
  10. *
  11. * This module wraps our choice of Ed25519 backend, and provides a few
  12. * convenience functions for checking and generating signatures. It also
  13. * provides Tor-specific tools for key blinding and for converting Ed25519
  14. * keys to and from the corresponding Curve25519 keys.
  15. */
  16. #define CRYPTO_ED25519_PRIVATE
  17. #include "orconfig.h"
  18. #ifdef HAVE_SYS_STAT_H
  19. #include <sys/stat.h>
  20. #endif
  21. #include "lib/ctime/di_ops.h"
  22. #include "lib/crypt_ops/crypto_curve25519.h"
  23. #include "lib/crypt_ops/crypto_digest.h"
  24. #include "lib/crypt_ops/crypto_ed25519.h"
  25. #include "lib/crypt_ops/crypto_format.h"
  26. #include "lib/crypt_ops/crypto_rand.h"
  27. #include "lib/crypt_ops/crypto_util.h"
  28. #include "lib/log/log.h"
  29. #include "lib/log/util_bug.h"
  30. #include "lib/encoding/binascii.h"
  31. #include "lib/string/util_string.h"
  32. #include "ed25519/ref10/ed25519_ref10.h"
  33. #include "ed25519/donna/ed25519_donna_tor.h"
  34. #include <string.h>
  35. #include <errno.h>
  36. static void pick_ed25519_impl(void);
  37. /** An Ed25519 implementation, as a set of function pointers. */
  38. typedef struct {
  39. int (*selftest)(void);
  40. int (*seckey)(unsigned char *);
  41. int (*seckey_expand)(unsigned char *, const unsigned char *);
  42. int (*pubkey)(unsigned char *, const unsigned char *);
  43. int (*keygen)(unsigned char *, unsigned char *);
  44. int (*open)(const unsigned char *, const unsigned char *, size_t, const
  45. unsigned char *);
  46. int (*sign)(unsigned char *, const unsigned char *, size_t,
  47. const unsigned char *, const unsigned char *);
  48. int (*open_batch)(const unsigned char **, size_t *, const unsigned char **,
  49. const unsigned char **, size_t, int *);
  50. int (*blind_secret_key)(unsigned char *, const unsigned char *,
  51. const unsigned char *);
  52. int (*blind_public_key)(unsigned char *, const unsigned char *,
  53. const unsigned char *);
  54. int (*pubkey_from_curve25519_pubkey)(unsigned char *, const unsigned char *,
  55. int);
  56. int (*ed25519_scalarmult_with_group_order)(unsigned char *,
  57. const unsigned char *);
  58. } ed25519_impl_t;
  59. /** The Ref10 Ed25519 implementation. This one is pure C and lightly
  60. * optimized. */
  61. static const ed25519_impl_t impl_ref10 = {
  62. NULL,
  63. ed25519_ref10_seckey,
  64. ed25519_ref10_seckey_expand,
  65. ed25519_ref10_pubkey,
  66. ed25519_ref10_keygen,
  67. ed25519_ref10_open,
  68. ed25519_ref10_sign,
  69. NULL,
  70. ed25519_ref10_blind_secret_key,
  71. ed25519_ref10_blind_public_key,
  72. ed25519_ref10_pubkey_from_curve25519_pubkey,
  73. ed25519_ref10_scalarmult_with_group_order,
  74. };
  75. /** The Ref10 Ed25519 implementation. This one is heavily optimized, but still
  76. * mostly C. The C still tends to be heavily platform-specific. */
  77. static const ed25519_impl_t impl_donna = {
  78. ed25519_donna_selftest,
  79. ed25519_donna_seckey,
  80. ed25519_donna_seckey_expand,
  81. ed25519_donna_pubkey,
  82. ed25519_donna_keygen,
  83. ed25519_donna_open,
  84. ed25519_donna_sign,
  85. ed25519_sign_open_batch_donna,
  86. ed25519_donna_blind_secret_key,
  87. ed25519_donna_blind_public_key,
  88. ed25519_donna_pubkey_from_curve25519_pubkey,
  89. ed25519_donna_scalarmult_with_group_order,
  90. };
  91. /** Which Ed25519 implementation are we using? NULL if we haven't decided
  92. * yet. */
  93. static const ed25519_impl_t *ed25519_impl = NULL;
  94. /** Helper: Return our chosen Ed25519 implementation.
  95. *
  96. * This should only be called after we've picked an implementation, but
  97. * it _does_ recover if you forget this.
  98. **/
  99. static inline const ed25519_impl_t *
  100. get_ed_impl(void)
  101. {
  102. if (BUG(ed25519_impl == NULL)) {
  103. pick_ed25519_impl(); // LCOV_EXCL_LINE - We always call ed25519_init().
  104. }
  105. return ed25519_impl;
  106. }
  107. #ifdef TOR_UNIT_TESTS
  108. /** For testing: used to remember our actual choice of Ed25519
  109. * implementation */
  110. static const ed25519_impl_t *saved_ed25519_impl = NULL;
  111. /** For testing: Use the Ed25519 implementation called <b>name</b> until
  112. * crypto_ed25519_testing_restore_impl is called. Recognized names are
  113. * "donna" and "ref10". */
  114. void
  115. crypto_ed25519_testing_force_impl(const char *name)
  116. {
  117. tor_assert(saved_ed25519_impl == NULL);
  118. saved_ed25519_impl = ed25519_impl;
  119. if (! strcmp(name, "donna")) {
  120. ed25519_impl = &impl_donna;
  121. } else {
  122. tor_assert(!strcmp(name, "ref10"));
  123. ed25519_impl = &impl_ref10;
  124. }
  125. }
  126. /** For testing: go back to whatever Ed25519 implementation we had picked
  127. * before crypto_ed25519_testing_force_impl was called.
  128. */
  129. void
  130. crypto_ed25519_testing_restore_impl(void)
  131. {
  132. ed25519_impl = saved_ed25519_impl;
  133. saved_ed25519_impl = NULL;
  134. }
  135. #endif /* defined(TOR_UNIT_TESTS) */
  136. /**
  137. * Initialize a new ed25519 secret key in <b>seckey_out</b>. If
  138. * <b>extra_strong</b>, take the RNG inputs directly from the operating
  139. * system. Return 0 on success, -1 on failure.
  140. */
  141. int
  142. ed25519_secret_key_generate(ed25519_secret_key_t *seckey_out,
  143. int extra_strong)
  144. {
  145. int r;
  146. uint8_t seed[32];
  147. if (extra_strong)
  148. crypto_strongest_rand(seed, sizeof(seed));
  149. else
  150. crypto_rand((char*)seed, sizeof(seed));
  151. r = get_ed_impl()->seckey_expand(seckey_out->seckey, seed);
  152. memwipe(seed, 0, sizeof(seed));
  153. return r < 0 ? -1 : 0;
  154. }
  155. /**
  156. * Given a 32-byte random seed in <b>seed</b>, expand it into an ed25519
  157. * secret key in <b>seckey_out</b>. Return 0 on success, -1 on failure.
  158. */
  159. int
  160. ed25519_secret_key_from_seed(ed25519_secret_key_t *seckey_out,
  161. const uint8_t *seed)
  162. {
  163. if (get_ed_impl()->seckey_expand(seckey_out->seckey, seed) < 0)
  164. return -1;
  165. return 0;
  166. }
  167. /**
  168. * Given a secret key in <b>seckey</b>, expand it into an
  169. * ed25519 public key. Return 0 on success, -1 on failure.
  170. */
  171. int
  172. ed25519_public_key_generate(ed25519_public_key_t *pubkey_out,
  173. const ed25519_secret_key_t *seckey)
  174. {
  175. if (get_ed_impl()->pubkey(pubkey_out->pubkey, seckey->seckey) < 0)
  176. return -1;
  177. return 0;
  178. }
  179. /** Generate a new ed25519 keypair in <b>keypair_out</b>. If
  180. * <b>extra_strong</b> is set, try to mix some system entropy into the key
  181. * generation process. Return 0 on success, -1 on failure. */
  182. int
  183. ed25519_keypair_generate(ed25519_keypair_t *keypair_out, int extra_strong)
  184. {
  185. if (ed25519_secret_key_generate(&keypair_out->seckey, extra_strong) < 0)
  186. return -1;
  187. if (ed25519_public_key_generate(&keypair_out->pubkey,
  188. &keypair_out->seckey)<0)
  189. return -1;
  190. return 0;
  191. }
  192. /** Return true iff 'pubkey' is set to zero (eg to indicate that it is not
  193. * set). */
  194. int
  195. ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
  196. {
  197. return safe_mem_is_zero((char*)pubkey->pubkey, ED25519_PUBKEY_LEN);
  198. }
  199. /* Return a heap-allocated array that contains <b>msg</b> prefixed by the
  200. * string <b>prefix_str</b>. Set <b>final_msg_len_out</b> to the size of the
  201. * final array. If an error occurred, return NULL. It's the responsibility of
  202. * the caller to free the returned array. */
  203. static uint8_t *
  204. get_prefixed_msg(const uint8_t *msg, size_t msg_len,
  205. const char *prefix_str,
  206. size_t *final_msg_len_out)
  207. {
  208. size_t prefixed_msg_len, prefix_len;
  209. uint8_t *prefixed_msg;
  210. tor_assert(prefix_str);
  211. tor_assert(final_msg_len_out);
  212. prefix_len = strlen(prefix_str);
  213. /* msg_len + strlen(prefix_str) must not overflow. */
  214. if (msg_len > SIZE_T_CEILING - prefix_len) {
  215. return NULL;
  216. }
  217. prefixed_msg_len = msg_len + prefix_len;
  218. prefixed_msg = tor_malloc_zero(prefixed_msg_len);
  219. memcpy(prefixed_msg, prefix_str, prefix_len);
  220. memcpy(prefixed_msg + prefix_len, msg, msg_len);
  221. *final_msg_len_out = prefixed_msg_len;
  222. return prefixed_msg;
  223. }
  224. /**
  225. * Set <b>signature_out</b> to a signature of the <b>len</b>-byte message
  226. * <b>msg</b>, using the secret and public key in <b>keypair</b>.
  227. *
  228. * Return 0 if we successfully signed the message, otherwise return -1.
  229. */
  230. int
  231. ed25519_sign(ed25519_signature_t *signature_out,
  232. const uint8_t *msg, size_t len,
  233. const ed25519_keypair_t *keypair)
  234. {
  235. if (get_ed_impl()->sign(signature_out->sig, msg, len,
  236. keypair->seckey.seckey,
  237. keypair->pubkey.pubkey) < 0) {
  238. return -1;
  239. }
  240. return 0;
  241. }
  242. /**
  243. * Like ed25519_sign(), but also prefix <b>msg</b> with <b>prefix_str</b>
  244. * before signing. <b>prefix_str</b> must be a NUL-terminated string.
  245. */
  246. MOCK_IMPL(int,
  247. ed25519_sign_prefixed,(ed25519_signature_t *signature_out,
  248. const uint8_t *msg, size_t msg_len,
  249. const char *prefix_str,
  250. const ed25519_keypair_t *keypair))
  251. {
  252. int retval;
  253. size_t prefixed_msg_len;
  254. uint8_t *prefixed_msg;
  255. tor_assert(prefix_str);
  256. prefixed_msg = get_prefixed_msg(msg, msg_len, prefix_str,
  257. &prefixed_msg_len);
  258. if (BUG(!prefixed_msg)) {
  259. /* LCOV_EXCL_START -- only possible when the message and prefix are
  260. * ridiculously huge */
  261. log_warn(LD_GENERAL, "Failed to get prefixed msg.");
  262. return -1;
  263. /* LCOV_EXCL_STOP */
  264. }
  265. retval = ed25519_sign(signature_out,
  266. prefixed_msg, prefixed_msg_len,
  267. keypair);
  268. tor_free(prefixed_msg);
  269. return retval;
  270. }
  271. /**
  272. * Check whether if <b>signature</b> is a valid signature for the
  273. * <b>len</b>-byte message in <b>msg</b> made with the key <b>pubkey</b>.
  274. *
  275. * Return 0 if the signature is valid; -1 if it isn't.
  276. */
  277. MOCK_IMPL(int,
  278. ed25519_checksig,(const ed25519_signature_t *signature,
  279. const uint8_t *msg, size_t len,
  280. const ed25519_public_key_t *pubkey))
  281. {
  282. return
  283. get_ed_impl()->open(signature->sig, msg, len, pubkey->pubkey) < 0 ? -1 : 0;
  284. }
  285. /**
  286. * Like ed2519_checksig(), but also prefix <b>msg</b> with <b>prefix_str</b>
  287. * before verifying signature. <b>prefix_str</b> must be a NUL-terminated
  288. * string.
  289. */
  290. int
  291. ed25519_checksig_prefixed(const ed25519_signature_t *signature,
  292. const uint8_t *msg, size_t msg_len,
  293. const char *prefix_str,
  294. const ed25519_public_key_t *pubkey)
  295. {
  296. int retval;
  297. size_t prefixed_msg_len;
  298. uint8_t *prefixed_msg;
  299. prefixed_msg = get_prefixed_msg(msg, msg_len, prefix_str,
  300. &prefixed_msg_len);
  301. if (BUG(!prefixed_msg)) {
  302. /* LCOV_EXCL_START -- only possible when the message and prefix are
  303. * ridiculously huge */
  304. log_warn(LD_GENERAL, "Failed to get prefixed msg.");
  305. return -1;
  306. /* LCOV_EXCL_STOP */
  307. }
  308. retval = ed25519_checksig(signature,
  309. prefixed_msg, prefixed_msg_len,
  310. pubkey);
  311. tor_free(prefixed_msg);
  312. return retval;
  313. }
  314. /** Validate every signature among those in <b>checkable</b>, which contains
  315. * exactly <b>n_checkable</b> elements. If <b>okay_out</b> is non-NULL, set
  316. * the i'th element of <b>okay_out</b> to 1 if the i'th element of
  317. * <b>checkable</b> is valid, and to 0 otherwise. Return 0 if every signature
  318. * was valid. Otherwise return -N, where N is the number of invalid
  319. * signatures.
  320. */
  321. MOCK_IMPL(int,
  322. ed25519_checksig_batch,(int *okay_out,
  323. const ed25519_checkable_t *checkable,
  324. int n_checkable))
  325. {
  326. int i, res;
  327. const ed25519_impl_t *impl = get_ed_impl();
  328. if (impl->open_batch == NULL) {
  329. /* No batch verification implementation available, fake it by checking the
  330. * each signature individually.
  331. */
  332. res = 0;
  333. for (i = 0; i < n_checkable; ++i) {
  334. const ed25519_checkable_t *ch = &checkable[i];
  335. int r = ed25519_checksig(&ch->signature, ch->msg, ch->len, ch->pubkey);
  336. if (r < 0)
  337. --res;
  338. if (okay_out)
  339. okay_out[i] = (r == 0);
  340. }
  341. } else {
  342. /* ed25519-donna style batch verification available.
  343. *
  344. * Theoretically, this should only be called if n_checkable >= 3, since
  345. * that's the threshold where the batch verification actually kicks in,
  346. * but the only difference is a few mallocs/frees.
  347. */
  348. const uint8_t **ms;
  349. size_t *lens;
  350. const uint8_t **pks;
  351. const uint8_t **sigs;
  352. int *oks;
  353. int all_ok;
  354. ms = tor_calloc(n_checkable, sizeof(uint8_t*));
  355. lens = tor_calloc(n_checkable, sizeof(size_t));
  356. pks = tor_calloc(n_checkable, sizeof(uint8_t*));
  357. sigs = tor_calloc(n_checkable, sizeof(uint8_t*));
  358. oks = okay_out ? okay_out : tor_calloc(n_checkable, sizeof(int));
  359. for (i = 0; i < n_checkable; ++i) {
  360. ms[i] = checkable[i].msg;
  361. lens[i] = checkable[i].len;
  362. pks[i] = checkable[i].pubkey->pubkey;
  363. sigs[i] = checkable[i].signature.sig;
  364. oks[i] = 0;
  365. }
  366. res = 0;
  367. all_ok = impl->open_batch(ms, lens, pks, sigs, n_checkable, oks);
  368. for (i = 0; i < n_checkable; ++i) {
  369. if (!oks[i])
  370. --res;
  371. }
  372. /* XXX: For now sanity check oks with the return value. Once we have
  373. * more confidence in the code, if `all_ok == 0` we can skip iterating
  374. * over oks since all the signatures were found to be valid.
  375. */
  376. tor_assert(((res == 0) && !all_ok) || ((res < 0) && all_ok));
  377. tor_free(ms);
  378. tor_free(lens);
  379. tor_free(pks);
  380. tor_free(sigs);
  381. if (! okay_out)
  382. tor_free(oks);
  383. }
  384. return res;
  385. }
  386. /**
  387. * Given a curve25519 keypair in <b>inp</b>, generate a corresponding
  388. * ed25519 keypair in <b>out</b>, and set <b>signbit_out</b> to the
  389. * sign bit of the X coordinate of the ed25519 key.
  390. *
  391. * NOTE THAT IT IS PROBABLY NOT SAFE TO USE THE GENERATED KEY FOR ANYTHING
  392. * OUTSIDE OF WHAT'S PRESENTED IN PROPOSAL 228. In particular, it's probably
  393. * not a great idea to use it to sign attacker-supplied anything.
  394. */
  395. int
  396. ed25519_keypair_from_curve25519_keypair(ed25519_keypair_t *out,
  397. int *signbit_out,
  398. const curve25519_keypair_t *inp)
  399. {
  400. const char string[] = "Derive high part of ed25519 key from curve25519 key";
  401. ed25519_public_key_t pubkey_check;
  402. crypto_digest_t *ctx;
  403. uint8_t sha512_output[DIGEST512_LEN];
  404. memcpy(out->seckey.seckey, inp->seckey.secret_key, 32);
  405. ctx = crypto_digest512_new(DIGEST_SHA512);
  406. crypto_digest_add_bytes(ctx, (const char*)out->seckey.seckey, 32);
  407. crypto_digest_add_bytes(ctx, (const char*)string, sizeof(string));
  408. crypto_digest_get_digest(ctx, (char *)sha512_output, sizeof(sha512_output));
  409. crypto_digest_free(ctx);
  410. memcpy(out->seckey.seckey + 32, sha512_output, 32);
  411. ed25519_public_key_generate(&out->pubkey, &out->seckey);
  412. *signbit_out = out->pubkey.pubkey[31] >> 7;
  413. ed25519_public_key_from_curve25519_public_key(&pubkey_check, &inp->pubkey,
  414. *signbit_out);
  415. tor_assert(fast_memeq(pubkey_check.pubkey, out->pubkey.pubkey, 32));
  416. memwipe(&pubkey_check, 0, sizeof(pubkey_check));
  417. memwipe(sha512_output, 0, sizeof(sha512_output));
  418. return 0;
  419. }
  420. /**
  421. * Given a curve25519 public key and sign bit of X coordinate of the ed25519
  422. * public key, generate the corresponding ed25519 public key.
  423. */
  424. int
  425. ed25519_public_key_from_curve25519_public_key(ed25519_public_key_t *pubkey,
  426. const curve25519_public_key_t *pubkey_in,
  427. int signbit)
  428. {
  429. return get_ed_impl()->pubkey_from_curve25519_pubkey(pubkey->pubkey,
  430. pubkey_in->public_key,
  431. signbit);
  432. }
  433. /**
  434. * Given an ed25519 keypair in <b>inp</b>, generate a corresponding
  435. * ed25519 keypair in <b>out</b>, blinded by the corresponding 32-byte input
  436. * in 'param'.
  437. *
  438. * Tor uses key blinding for the "next-generation" hidden services design:
  439. * service descriptors are encrypted with a key derived from the service's
  440. * long-term public key, and then signed with (and stored at a position
  441. * indexed by) a short-term key derived by blinding the long-term keys.
  442. *
  443. * Return 0 if blinding was successful, else return -1. */
  444. int
  445. ed25519_keypair_blind(ed25519_keypair_t *out,
  446. const ed25519_keypair_t *inp,
  447. const uint8_t *param)
  448. {
  449. ed25519_public_key_t pubkey_check;
  450. get_ed_impl()->blind_secret_key(out->seckey.seckey,
  451. inp->seckey.seckey, param);
  452. if (ed25519_public_blind(&pubkey_check, &inp->pubkey, param) < 0) {
  453. return -1;
  454. }
  455. ed25519_public_key_generate(&out->pubkey, &out->seckey);
  456. tor_assert(fast_memeq(pubkey_check.pubkey, out->pubkey.pubkey, 32));
  457. memwipe(&pubkey_check, 0, sizeof(pubkey_check));
  458. return 0;
  459. }
  460. /**
  461. * Given an ed25519 public key in <b>inp</b>, generate a corresponding blinded
  462. * public key in <b>out</b>, blinded with the 32-byte parameter in
  463. * <b>param</b>. Return 0 on success, -1 on railure.
  464. */
  465. int
  466. ed25519_public_blind(ed25519_public_key_t *out,
  467. const ed25519_public_key_t *inp,
  468. const uint8_t *param)
  469. {
  470. return get_ed_impl()->blind_public_key(out->pubkey, inp->pubkey, param);
  471. }
  472. /**
  473. * Store seckey unencrypted to <b>filename</b>, marking it with <b>tag</b>.
  474. * Return 0 on success, -1 on failure.
  475. */
  476. int
  477. ed25519_seckey_write_to_file(const ed25519_secret_key_t *seckey,
  478. const char *filename,
  479. const char *tag)
  480. {
  481. return crypto_write_tagged_contents_to_file(filename,
  482. "ed25519v1-secret",
  483. tag,
  484. seckey->seckey,
  485. sizeof(seckey->seckey));
  486. }
  487. /**
  488. * Read seckey unencrypted from <b>filename</b>, storing it into
  489. * <b>seckey_out</b>. Set *<b>tag_out</b> to the tag it was marked with.
  490. * Return 0 on success, -1 on failure.
  491. */
  492. int
  493. ed25519_seckey_read_from_file(ed25519_secret_key_t *seckey_out,
  494. char **tag_out,
  495. const char *filename)
  496. {
  497. ssize_t len;
  498. len = crypto_read_tagged_contents_from_file(filename, "ed25519v1-secret",
  499. tag_out, seckey_out->seckey,
  500. sizeof(seckey_out->seckey));
  501. if (len == sizeof(seckey_out->seckey)) {
  502. return 0;
  503. } else if (len >= 0) {
  504. errno = EINVAL;
  505. }
  506. tor_free(*tag_out);
  507. return -1;
  508. }
  509. /**
  510. * Store pubkey unencrypted to <b>filename</b>, marking it with <b>tag</b>.
  511. * Return 0 on success, -1 on failure.
  512. */
  513. int
  514. ed25519_pubkey_write_to_file(const ed25519_public_key_t *pubkey,
  515. const char *filename,
  516. const char *tag)
  517. {
  518. return crypto_write_tagged_contents_to_file(filename,
  519. "ed25519v1-public",
  520. tag,
  521. pubkey->pubkey,
  522. sizeof(pubkey->pubkey));
  523. }
  524. /**
  525. * Store pubkey unencrypted to <b>filename</b>, marking it with <b>tag</b>.
  526. * Return 0 on success, -1 on failure.
  527. */
  528. int
  529. ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
  530. char **tag_out,
  531. const char *filename)
  532. {
  533. ssize_t len;
  534. len = crypto_read_tagged_contents_from_file(filename, "ed25519v1-public",
  535. tag_out, pubkey_out->pubkey,
  536. sizeof(pubkey_out->pubkey));
  537. if (len == sizeof(pubkey_out->pubkey)) {
  538. return 0;
  539. } else if (len >= 0) {
  540. errno = EINVAL;
  541. }
  542. tor_free(*tag_out);
  543. return -1;
  544. }
  545. /** Release all storage held for <b>kp</b>. */
  546. void
  547. ed25519_keypair_free_(ed25519_keypair_t *kp)
  548. {
  549. if (! kp)
  550. return;
  551. memwipe(kp, 0, sizeof(*kp));
  552. tor_free(kp);
  553. }
  554. /** Return true iff <b>key1</b> and <b>key2</b> are the same public key. */
  555. int
  556. ed25519_pubkey_eq(const ed25519_public_key_t *key1,
  557. const ed25519_public_key_t *key2)
  558. {
  559. tor_assert(key1);
  560. tor_assert(key2);
  561. return tor_memeq(key1->pubkey, key2->pubkey, ED25519_PUBKEY_LEN);
  562. }
  563. /**
  564. * Set <b>dest</b> to contain the same key as <b>src</b>.
  565. */
  566. void
  567. ed25519_pubkey_copy(ed25519_public_key_t *dest,
  568. const ed25519_public_key_t *src)
  569. {
  570. tor_assert(dest);
  571. tor_assert(src);
  572. memcpy(dest, src, sizeof(ed25519_public_key_t));
  573. }
  574. /** Check whether the given Ed25519 implementation seems to be working.
  575. * If so, return 0; otherwise return -1. */
  576. MOCK_IMPL(STATIC int,
  577. ed25519_impl_spot_check,(void))
  578. {
  579. static const uint8_t alicesk[32] = {
  580. 0xc5,0xaa,0x8d,0xf4,0x3f,0x9f,0x83,0x7b,
  581. 0xed,0xb7,0x44,0x2f,0x31,0xdc,0xb7,0xb1,
  582. 0x66,0xd3,0x85,0x35,0x07,0x6f,0x09,0x4b,
  583. 0x85,0xce,0x3a,0x2e,0x0b,0x44,0x58,0xf7
  584. };
  585. static const uint8_t alicepk[32] = {
  586. 0xfc,0x51,0xcd,0x8e,0x62,0x18,0xa1,0xa3,
  587. 0x8d,0xa4,0x7e,0xd0,0x02,0x30,0xf0,0x58,
  588. 0x08,0x16,0xed,0x13,0xba,0x33,0x03,0xac,
  589. 0x5d,0xeb,0x91,0x15,0x48,0x90,0x80,0x25
  590. };
  591. static const uint8_t alicemsg[2] = { 0xaf, 0x82 };
  592. static const uint8_t alicesig[64] = {
  593. 0x62,0x91,0xd6,0x57,0xde,0xec,0x24,0x02,
  594. 0x48,0x27,0xe6,0x9c,0x3a,0xbe,0x01,0xa3,
  595. 0x0c,0xe5,0x48,0xa2,0x84,0x74,0x3a,0x44,
  596. 0x5e,0x36,0x80,0xd7,0xdb,0x5a,0xc3,0xac,
  597. 0x18,0xff,0x9b,0x53,0x8d,0x16,0xf2,0x90,
  598. 0xae,0x67,0xf7,0x60,0x98,0x4d,0xc6,0x59,
  599. 0x4a,0x7c,0x15,0xe9,0x71,0x6e,0xd2,0x8d,
  600. 0xc0,0x27,0xbe,0xce,0xea,0x1e,0xc4,0x0a
  601. };
  602. const ed25519_impl_t *impl = get_ed_impl();
  603. uint8_t sk[ED25519_SECKEY_LEN];
  604. uint8_t pk[ED25519_PUBKEY_LEN];
  605. uint8_t sig[ED25519_SIG_LEN];
  606. int r = 0;
  607. /* Some implementations (eg: The modified Ed25519-donna) have handy self-test
  608. * code that sanity-checks the internals. If present, use that to screen out
  609. * catastrophic errors like massive compiler failure.
  610. */
  611. if (impl->selftest && impl->selftest() != 0)
  612. goto fail;
  613. /* Validate results versus known answer tests. People really should be
  614. * running "make test" instead of relying on this, but it's better than
  615. * nothing.
  616. *
  617. * Test vectors taken from "EdDSA & Ed25519 - 6. Test Vectors for Ed25519
  618. * (TEST3)" (draft-josefsson-eddsa-ed25519-03).
  619. */
  620. /* Key expansion, public key derivation. */
  621. if (impl->seckey_expand(sk, alicesk) < 0)
  622. goto fail;
  623. if (impl->pubkey(pk, sk) < 0)
  624. goto fail;
  625. if (fast_memneq(pk, alicepk, ED25519_PUBKEY_LEN))
  626. goto fail;
  627. /* Signing, verification. */
  628. if (impl->sign(sig, alicemsg, sizeof(alicemsg), sk, pk) < 0)
  629. return -1;
  630. if (fast_memneq(sig, alicesig, ED25519_SIG_LEN))
  631. return -1;
  632. if (impl->open(sig, alicemsg, sizeof(alicemsg), pk) < 0)
  633. return -1;
  634. /* XXX/yawning: Someone that's more paranoid than I am, can write "Assume
  635. * ref0 is canonical, and fuzz impl against it" if they want, but I doubt
  636. * that will catch anything that the known answer tests won't.
  637. */
  638. goto end;
  639. // LCOV_EXCL_START -- We can only reach this if our ed25519 implementation is
  640. // broken.
  641. fail:
  642. r = -1;
  643. // LCOV_EXCL_STOP
  644. end:
  645. return r;
  646. }
  647. /** Force the Ed25519 implementation to a given one, without sanity checking
  648. * the output. Used for testing.
  649. */
  650. void
  651. ed25519_set_impl_params(int use_donna)
  652. {
  653. if (use_donna)
  654. ed25519_impl = &impl_donna;
  655. else
  656. ed25519_impl = &impl_ref10;
  657. }
  658. /** Choose whether to use the Ed25519-donna implementation. */
  659. static void
  660. pick_ed25519_impl(void)
  661. {
  662. ed25519_impl = &impl_donna;
  663. if (ed25519_impl_spot_check() == 0)
  664. return;
  665. /* LCOV_EXCL_START
  666. * unreachable unless ed25519_donna is broken */
  667. log_warn(LD_CRYPTO, "The Ed25519-donna implementation seems broken; using "
  668. "the ref10 implementation.");
  669. ed25519_impl = &impl_ref10;
  670. /* LCOV_EXCL_STOP */
  671. }
  672. /* Initialize the Ed25519 implementation. This is necessary if you're
  673. * going to use them in a multithreaded setting, and not otherwise. */
  674. void
  675. ed25519_init(void)
  676. {
  677. pick_ed25519_impl();
  678. }
  679. /* Return true if <b>point</b> is the identity element of the ed25519 group. */
  680. static int
  681. ed25519_point_is_identity_element(const uint8_t *point)
  682. {
  683. /* The identity element in ed25159 is the point with coordinates (0,1). */
  684. static const uint8_t ed25519_identity[32] = {
  685. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  686. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  687. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  688. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  689. tor_assert(sizeof(ed25519_identity) == ED25519_PUBKEY_LEN);
  690. return tor_memeq(point, ed25519_identity, sizeof(ed25519_identity));
  691. }
  692. /** Validate <b>pubkey</b> to ensure that it has no torsion component.
  693. * Return 0 if <b>pubkey</b> is valid, else return -1. */
  694. int
  695. ed25519_validate_pubkey(const ed25519_public_key_t *pubkey)
  696. {
  697. uint8_t result[32] = {9};
  698. /* First check that we were not given the identity element */
  699. if (ed25519_point_is_identity_element(pubkey->pubkey)) {
  700. log_warn(LD_CRYPTO, "ed25519 pubkey is the identity");
  701. return -1;
  702. }
  703. /* For any point on the curve, doing l*point should give the identity element
  704. * (where l is the group order). Do the computation and check that the
  705. * identity element is returned. */
  706. if (get_ed_impl()->ed25519_scalarmult_with_group_order(result,
  707. pubkey->pubkey) < 0) {
  708. log_warn(LD_CRYPTO, "ed25519 group order scalarmult failed");
  709. return -1;
  710. }
  711. if (!ed25519_point_is_identity_element(result)) {
  712. log_warn(LD_CRYPTO, "ed25519 validation failed");
  713. return -1;
  714. }
  715. return 0;
  716. }