crypto_curve25519.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /* Copyright (c) 2012-2015, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /* Wrapper code for a curve25519 implementation. */
  4. #define CRYPTO_CURVE25519_PRIVATE
  5. #include "orconfig.h"
  6. #ifdef HAVE_SYS_STAT_H
  7. #include <sys/stat.h>
  8. #endif
  9. #include "container.h"
  10. #include "crypto.h"
  11. #include "crypto_curve25519.h"
  12. #include "util.h"
  13. #include "torlog.h"
  14. #include "ed25519/donna/ed25519_donna_tor.h"
  15. /* ==============================
  16. Part 1: wrap a suitable curve25519 implementation as curve25519_impl
  17. ============================== */
  18. #ifdef USE_CURVE25519_DONNA
  19. int curve25519_donna(uint8_t *mypublic,
  20. const uint8_t *secret, const uint8_t *basepoint);
  21. #endif
  22. #ifdef USE_CURVE25519_NACL
  23. #ifdef HAVE_CRYPTO_SCALARMULT_CURVE25519_H
  24. #include <crypto_scalarmult_curve25519.h>
  25. #elif defined(HAVE_NACL_CRYPTO_SCALARMULT_CURVE25519_H)
  26. #include <nacl/crypto_scalarmult_curve25519.h>
  27. #endif
  28. #endif
  29. static void pick_curve25519_basepoint_impl(void);
  30. static int curve25519_use_ed = -1;
  31. STATIC int
  32. curve25519_impl(uint8_t *output, const uint8_t *secret,
  33. const uint8_t *basepoint)
  34. {
  35. uint8_t bp[CURVE25519_PUBKEY_LEN];
  36. int r;
  37. memcpy(bp, basepoint, CURVE25519_PUBKEY_LEN);
  38. /* Clear the high bit, in case our backend foolishly looks at it. */
  39. bp[31] &= 0x7f;
  40. #ifdef USE_CURVE25519_DONNA
  41. r = curve25519_donna(output, secret, bp);
  42. #elif defined(USE_CURVE25519_NACL)
  43. r = crypto_scalarmult_curve25519(output, secret, bp);
  44. #else
  45. #error "No implementation of curve25519 is available."
  46. #endif
  47. memwipe(bp, 0, sizeof(bp));
  48. return r;
  49. }
  50. STATIC int
  51. curve25519_basepoint_impl(uint8_t *output, const uint8_t *secret)
  52. {
  53. int r = 0;
  54. if (PREDICT_UNLIKELY(curve25519_use_ed == -1)) {
  55. pick_curve25519_basepoint_impl();
  56. }
  57. /* TODO: Someone should benchmark curved25519_scalarmult_basepoint versus
  58. * an optimized NaCl build to see which should be used when compiled with
  59. * NaCl available. I suspected that the ed25519 optimization always wins.
  60. */
  61. if (PREDICT_LIKELY(curve25519_use_ed == 1)) {
  62. curved25519_scalarmult_basepoint_donna(output, secret);
  63. r = 0;
  64. } else {
  65. static const uint8_t basepoint[32] = {9};
  66. r = curve25519_impl(output, secret, basepoint);
  67. }
  68. return r;
  69. }
  70. void
  71. curve25519_set_impl_params(int use_ed)
  72. {
  73. curve25519_use_ed = use_ed;
  74. }
  75. /* ==============================
  76. Part 2: Wrap curve25519_impl with some convenience types and functions.
  77. ============================== */
  78. /**
  79. * Return true iff a curve25519_public_key_t seems valid. (It's not necessary
  80. * to see if the point is on the curve, since the twist is also secure, but we
  81. * do need to make sure that it isn't the point at infinity.) */
  82. int
  83. curve25519_public_key_is_ok(const curve25519_public_key_t *key)
  84. {
  85. return !safe_mem_is_zero(key->public_key, CURVE25519_PUBKEY_LEN);
  86. }
  87. /**
  88. * Generate CURVE25519_SECKEY_LEN random bytes in <b>out</b>. If
  89. * <b>extra_strong</b> is true, this key is possibly going to get used more
  90. * than once, so use a better-than-usual RNG. Return 0 on success, -1 on
  91. * failure.
  92. *
  93. * This function does not adjust the output of the RNG at all; the will caller
  94. * will need to clear or set the appropriate bits to make curve25519 work.
  95. */
  96. int
  97. curve25519_rand_seckey_bytes(uint8_t *out, int extra_strong)
  98. {
  99. uint8_t k_tmp[CURVE25519_SECKEY_LEN];
  100. if (crypto_rand((char*)out, CURVE25519_SECKEY_LEN) < 0)
  101. return -1;
  102. if (extra_strong && !crypto_strongest_rand(k_tmp, CURVE25519_SECKEY_LEN)) {
  103. /* If they asked for extra-strong entropy and we have some, use it as an
  104. * HMAC key to improve not-so-good entropy rather than using it directly,
  105. * just in case the extra-strong entropy is less amazing than we hoped. */
  106. crypto_hmac_sha256((char*) out,
  107. (const char *)k_tmp, sizeof(k_tmp),
  108. (const char *)out, CURVE25519_SECKEY_LEN);
  109. }
  110. memwipe(k_tmp, 0, sizeof(k_tmp));
  111. return 0;
  112. }
  113. /** Generate a new keypair and return the secret key. If <b>extra_strong</b>
  114. * is true, this key is possibly going to get used more than once, so
  115. * use a better-than-usual RNG. Return 0 on success, -1 on failure. */
  116. int
  117. curve25519_secret_key_generate(curve25519_secret_key_t *key_out,
  118. int extra_strong)
  119. {
  120. if (curve25519_rand_seckey_bytes(key_out->secret_key, extra_strong) < 0)
  121. return -1;
  122. key_out->secret_key[0] &= 248;
  123. key_out->secret_key[31] &= 127;
  124. key_out->secret_key[31] |= 64;
  125. return 0;
  126. }
  127. void
  128. curve25519_public_key_generate(curve25519_public_key_t *key_out,
  129. const curve25519_secret_key_t *seckey)
  130. {
  131. curve25519_basepoint_impl(key_out->public_key, seckey->secret_key);
  132. }
  133. int
  134. curve25519_keypair_generate(curve25519_keypair_t *keypair_out,
  135. int extra_strong)
  136. {
  137. if (curve25519_secret_key_generate(&keypair_out->seckey, extra_strong) < 0)
  138. return -1;
  139. curve25519_public_key_generate(&keypair_out->pubkey, &keypair_out->seckey);
  140. return 0;
  141. }
  142. /** Write the <b>datalen</b> bytes from <b>data</b> to the file named
  143. * <b>fname</b> in the tagged-data format. This format contains a
  144. * 32-byte header, followed by the data itself. The header is the
  145. * NUL-padded string "== <b>typestring</b>: <b>tag</b> ==". The length
  146. * of <b>typestring</b> and <b>tag</b> must therefore be no more than
  147. * 24.
  148. **/
  149. int
  150. crypto_write_tagged_contents_to_file(const char *fname,
  151. const char *typestring,
  152. const char *tag,
  153. const uint8_t *data,
  154. size_t datalen)
  155. {
  156. char header[32];
  157. smartlist_t *chunks = smartlist_new();
  158. sized_chunk_t ch0, ch1;
  159. int r = -1;
  160. memset(header, 0, sizeof(header));
  161. if (tor_snprintf(header, sizeof(header),
  162. "== %s: %s ==", typestring, tag) < 0)
  163. goto end;
  164. ch0.bytes = header;
  165. ch0.len = 32;
  166. ch1.bytes = (const char*) data;
  167. ch1.len = datalen;
  168. smartlist_add(chunks, &ch0);
  169. smartlist_add(chunks, &ch1);
  170. r = write_chunks_to_file(fname, chunks, 1, 0);
  171. end:
  172. smartlist_free(chunks);
  173. return r;
  174. }
  175. /** Read a tagged-data file from <b>fname</b> into the
  176. * <b>data_out_len</b>-byte buffer in <b>data_out</b>. Check that the
  177. * typestring matches <b>typestring</b>; store the tag into a newly allocated
  178. * string in <b>tag_out</b>. Return -1 on failure, and the number of bytes of
  179. * data on success. */
  180. ssize_t
  181. crypto_read_tagged_contents_from_file(const char *fname,
  182. const char *typestring,
  183. char **tag_out,
  184. uint8_t *data_out,
  185. ssize_t data_out_len)
  186. {
  187. char prefix[33];
  188. char *content = NULL;
  189. struct stat st;
  190. ssize_t r = -1;
  191. size_t st_size = 0;
  192. *tag_out = NULL;
  193. st.st_size = 0;
  194. content = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  195. if (! content)
  196. goto end;
  197. if (st.st_size < 32 || st.st_size > 32 + data_out_len)
  198. goto end;
  199. st_size = (size_t)st.st_size;
  200. memcpy(prefix, content, 32);
  201. prefix[32] = 0;
  202. /* Check type, extract tag. */
  203. if (strcmpstart(prefix, "== ") || strcmpend(prefix, " ==") ||
  204. ! tor_mem_is_zero(prefix+strlen(prefix), 32-strlen(prefix)))
  205. goto end;
  206. if (strcmpstart(prefix+3, typestring) ||
  207. 3+strlen(typestring) >= 32 ||
  208. strcmpstart(prefix+3+strlen(typestring), ": "))
  209. goto end;
  210. *tag_out = tor_strndup(prefix+5+strlen(typestring),
  211. strlen(prefix)-8-strlen(typestring));
  212. memcpy(data_out, content+32, st_size-32);
  213. r = st_size - 32;
  214. end:
  215. if (content)
  216. memwipe(content, 0, st_size);
  217. tor_free(content);
  218. return r;
  219. }
  220. /** DOCDOC */
  221. int
  222. curve25519_keypair_write_to_file(const curve25519_keypair_t *keypair,
  223. const char *fname,
  224. const char *tag)
  225. {
  226. uint8_t contents[CURVE25519_SECKEY_LEN + CURVE25519_PUBKEY_LEN];
  227. int r;
  228. memcpy(contents, keypair->seckey.secret_key, CURVE25519_SECKEY_LEN);
  229. memcpy(contents+CURVE25519_SECKEY_LEN,
  230. keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
  231. r = crypto_write_tagged_contents_to_file(fname,
  232. "c25519v1",
  233. tag,
  234. contents,
  235. sizeof(contents));
  236. memwipe(contents, 0, sizeof(contents));
  237. return r;
  238. }
  239. /** DOCDOC */
  240. int
  241. curve25519_keypair_read_from_file(curve25519_keypair_t *keypair_out,
  242. char **tag_out,
  243. const char *fname)
  244. {
  245. uint8_t content[CURVE25519_SECKEY_LEN + CURVE25519_PUBKEY_LEN];
  246. ssize_t len;
  247. int r = -1;
  248. len = crypto_read_tagged_contents_from_file(fname, "c25519v1", tag_out,
  249. content, sizeof(content));
  250. if (len != sizeof(content))
  251. goto end;
  252. memcpy(keypair_out->seckey.secret_key, content, CURVE25519_SECKEY_LEN);
  253. curve25519_public_key_generate(&keypair_out->pubkey, &keypair_out->seckey);
  254. if (tor_memneq(keypair_out->pubkey.public_key,
  255. content + CURVE25519_SECKEY_LEN,
  256. CURVE25519_PUBKEY_LEN))
  257. goto end;
  258. r = 0;
  259. end:
  260. memwipe(content, 0, sizeof(content));
  261. if (r != 0) {
  262. memset(keypair_out, 0, sizeof(*keypair_out));
  263. tor_free(*tag_out);
  264. }
  265. return r;
  266. }
  267. /** Perform the curve25519 ECDH handshake with <b>skey</b> and <b>pkey</b>,
  268. * writing CURVE25519_OUTPUT_LEN bytes of output into <b>output</b>. */
  269. void
  270. curve25519_handshake(uint8_t *output,
  271. const curve25519_secret_key_t *skey,
  272. const curve25519_public_key_t *pkey)
  273. {
  274. curve25519_impl(output, skey->secret_key, pkey->public_key);
  275. }
  276. /** Check whether the ed25519-based curve25519 basepoint optimization seems to
  277. * be working. If so, return 0; otherwise return -1. */
  278. static int
  279. curve25519_basepoint_spot_check(void)
  280. {
  281. static const uint8_t alicesk[32] = {
  282. 0x77,0x07,0x6d,0x0a,0x73,0x18,0xa5,0x7d,
  283. 0x3c,0x16,0xc1,0x72,0x51,0xb2,0x66,0x45,
  284. 0xdf,0x4c,0x2f,0x87,0xeb,0xc0,0x99,0x2a,
  285. 0xb1,0x77,0xfb,0xa5,0x1d,0xb9,0x2c,0x2a
  286. };
  287. static const uint8_t alicepk[32] = {
  288. 0x85,0x20,0xf0,0x09,0x89,0x30,0xa7,0x54,
  289. 0x74,0x8b,0x7d,0xdc,0xb4,0x3e,0xf7,0x5a,
  290. 0x0d,0xbf,0x3a,0x0d,0x26,0x38,0x1a,0xf4,
  291. 0xeb,0xa4,0xa9,0x8e,0xaa,0x9b,0x4e,0x6a
  292. };
  293. const int loop_max=200;
  294. int save_use_ed = curve25519_use_ed;
  295. unsigned char e1[32] = { 5 };
  296. unsigned char e2[32] = { 5 };
  297. unsigned char x[32],y[32];
  298. int i;
  299. int r=0;
  300. /* Check the most basic possible sanity via the test secret/public key pair
  301. * used in "Cryptography in NaCl - 2. Secret keys and public keys". This
  302. * may catch catastrophic failures on systems where Curve25519 is expensive,
  303. * without requiring a ton of key generation.
  304. */
  305. curve25519_use_ed = 1;
  306. r |= curve25519_basepoint_impl(x, alicesk);
  307. if (fast_memneq(x, alicepk, 32))
  308. goto fail;
  309. /* Ok, the optimization appears to produce passable results, try a few more
  310. * values, maybe there's something subtle wrong.
  311. */
  312. for (i = 0; i < loop_max; ++i) {
  313. curve25519_use_ed = 0;
  314. r |= curve25519_basepoint_impl(x, e1);
  315. curve25519_use_ed = 1;
  316. r |= curve25519_basepoint_impl(y, e2);
  317. if (fast_memneq(x,y,32))
  318. goto fail;
  319. memcpy(e1, x, 32);
  320. memcpy(e2, x, 32);
  321. }
  322. goto end;
  323. fail:
  324. r = -1;
  325. end:
  326. curve25519_use_ed = save_use_ed;
  327. return r;
  328. }
  329. /** Choose whether to use the ed25519-based curve25519-basepoint
  330. * implementation. */
  331. static void
  332. pick_curve25519_basepoint_impl(void)
  333. {
  334. curve25519_use_ed = 1;
  335. if (curve25519_basepoint_spot_check() == 0)
  336. return;
  337. log_warn(LD_CRYPTO, "The ed25519-based curve25519 basepoint "
  338. "multiplication seems broken; using the curve25519 "
  339. "implementation.");
  340. curve25519_use_ed = 0;
  341. }
  342. /** Initialize the curve25519 implementations. This is necessary if you're
  343. * going to use them in a multithreaded setting, and not otherwise. */
  344. void
  345. curve25519_init(void)
  346. {
  347. pick_curve25519_basepoint_impl();
  348. }