crypto.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 crypto.c
  8. * \brief Wrapper functions to present a consistent interface to
  9. * public-key and symmetric cryptography operations from OpenSSL and
  10. * other places.
  11. **/
  12. #include "orconfig.h"
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #include <windows.h>
  16. #include <wincrypt.h>
  17. /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
  18. * use either definition. */
  19. #undef OCSP_RESPONSE
  20. #endif /* defined(_WIN32) */
  21. #define CRYPTO_PRIVATE
  22. #include "lib/crypt_ops/compat_openssl.h"
  23. #include "lib/crypt_ops/crypto.h"
  24. #include "lib/crypt_ops/crypto_curve25519.h"
  25. #include "lib/crypt_ops/crypto_digest.h"
  26. #include "lib/crypt_ops/crypto_dh.h"
  27. #include "lib/crypt_ops/crypto_ed25519.h"
  28. #include "lib/crypt_ops/crypto_format.h"
  29. #include "lib/crypt_ops/crypto_rand.h"
  30. #include "lib/crypt_ops/crypto_rsa.h"
  31. #include "lib/crypt_ops/crypto_util.h"
  32. DISABLE_GCC_WARNING(redundant-decls)
  33. #include <openssl/err.h>
  34. #include <openssl/evp.h>
  35. #include <openssl/engine.h>
  36. #include <openssl/bn.h>
  37. #include <openssl/dh.h>
  38. #include <openssl/conf.h>
  39. #include <openssl/hmac.h>
  40. #include <openssl/ssl.h>
  41. ENABLE_GCC_WARNING(redundant-decls)
  42. #if __GNUC__ && GCC_VERSION >= 402
  43. #if GCC_VERSION >= 406
  44. #pragma GCC diagnostic pop
  45. #else
  46. #pragma GCC diagnostic warning "-Wredundant-decls"
  47. #endif
  48. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  49. #ifdef HAVE_CTYPE_H
  50. #include <ctype.h>
  51. #endif
  52. #ifdef HAVE_UNISTD_H
  53. #include <unistd.h>
  54. #endif
  55. #include "lib/log/torlog.h"
  56. #include "lib/cc/torint.h"
  57. #include "lib/crypt_ops/aes.h"
  58. #include "common/util.h"
  59. #include "common/compat.h"
  60. #include "lib/encoding/binascii.h"
  61. #include "keccak-tiny/keccak-tiny.h"
  62. #include "siphash.h"
  63. /** Boolean: has OpenSSL's crypto been initialized? */
  64. static int crypto_early_initialized_ = 0;
  65. /** Boolean: has OpenSSL's crypto been initialized? */
  66. static int crypto_global_initialized_ = 0;
  67. #ifndef DISABLE_ENGINES
  68. /** Log any OpenSSL engines we're using at NOTICE. */
  69. static void
  70. log_engine(const char *fn, ENGINE *e)
  71. {
  72. if (e) {
  73. const char *name, *id;
  74. name = ENGINE_get_name(e);
  75. id = ENGINE_get_id(e);
  76. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  77. fn, name?name:"?", id?id:"?");
  78. } else {
  79. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  80. }
  81. }
  82. #endif /* !defined(DISABLE_ENGINES) */
  83. #ifndef DISABLE_ENGINES
  84. /** Try to load an engine in a shared library via fully qualified path.
  85. */
  86. static ENGINE *
  87. try_load_engine(const char *path, const char *engine)
  88. {
  89. ENGINE *e = ENGINE_by_id("dynamic");
  90. if (e) {
  91. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  92. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  93. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  94. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  95. ENGINE_free(e);
  96. e = NULL;
  97. }
  98. }
  99. return e;
  100. }
  101. #endif /* !defined(DISABLE_ENGINES) */
  102. static int have_seeded_siphash = 0;
  103. /** Set up the siphash key if we haven't already done so. */
  104. int
  105. crypto_init_siphash_key(void)
  106. {
  107. struct sipkey key;
  108. if (have_seeded_siphash)
  109. return 0;
  110. crypto_rand((char*) &key, sizeof(key));
  111. siphash_set_global_key(&key);
  112. have_seeded_siphash = 1;
  113. return 0;
  114. }
  115. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  116. */
  117. int
  118. crypto_early_init(void)
  119. {
  120. if (!crypto_early_initialized_) {
  121. crypto_early_initialized_ = 1;
  122. #ifdef OPENSSL_1_1_API
  123. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  124. OPENSSL_INIT_LOAD_CRYPTO_STRINGS |
  125. OPENSSL_INIT_ADD_ALL_CIPHERS |
  126. OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
  127. #else
  128. ERR_load_crypto_strings();
  129. OpenSSL_add_all_algorithms();
  130. #endif
  131. setup_openssl_threading();
  132. unsigned long version_num = OpenSSL_version_num();
  133. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  134. if (version_num == OPENSSL_VERSION_NUMBER &&
  135. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  136. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  137. "(%lx: %s).", version_num, version_str);
  138. } else {
  139. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  140. "version we're running with. If you get weird crashes, that "
  141. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  142. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  143. version_num, version_str);
  144. }
  145. crypto_force_rand_ssleay();
  146. if (crypto_seed_rng() < 0)
  147. return -1;
  148. if (crypto_init_siphash_key() < 0)
  149. return -1;
  150. curve25519_init();
  151. ed25519_init();
  152. }
  153. return 0;
  154. }
  155. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  156. */
  157. int
  158. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  159. {
  160. if (!crypto_global_initialized_) {
  161. if (crypto_early_init() < 0)
  162. return -1;
  163. crypto_global_initialized_ = 1;
  164. if (useAccel > 0) {
  165. #ifdef DISABLE_ENGINES
  166. (void)accelName;
  167. (void)accelDir;
  168. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  169. #else
  170. ENGINE *e = NULL;
  171. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  172. ENGINE_load_builtin_engines();
  173. ENGINE_register_all_complete();
  174. if (accelName) {
  175. if (accelDir) {
  176. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  177. " via path \"%s\".", accelName, accelDir);
  178. e = try_load_engine(accelName, accelDir);
  179. } else {
  180. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  181. " acceleration support.", accelName);
  182. e = ENGINE_by_id(accelName);
  183. }
  184. if (!e) {
  185. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  186. accelName);
  187. } else {
  188. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  189. accelName);
  190. }
  191. }
  192. if (e) {
  193. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  194. " setting default ciphers.");
  195. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  196. }
  197. /* Log, if available, the intersection of the set of algorithms
  198. used by Tor and the set of algorithms available in the engine */
  199. log_engine("RSA", ENGINE_get_default_RSA());
  200. log_engine("DH", ENGINE_get_default_DH());
  201. #ifdef OPENSSL_1_1_API
  202. log_engine("EC", ENGINE_get_default_EC());
  203. #else
  204. log_engine("ECDH", ENGINE_get_default_ECDH());
  205. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  206. #endif /* defined(OPENSSL_1_1_API) */
  207. log_engine("RAND", ENGINE_get_default_RAND());
  208. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  209. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  210. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  211. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  212. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  213. #ifdef NID_aes_128_ctr
  214. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  215. #endif
  216. #ifdef NID_aes_128_gcm
  217. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  218. #endif
  219. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  220. #ifdef NID_aes_256_gcm
  221. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  222. #endif
  223. #endif /* defined(DISABLE_ENGINES) */
  224. } else {
  225. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  226. }
  227. if (crypto_force_rand_ssleay()) {
  228. if (crypto_seed_rng() < 0)
  229. return -1;
  230. }
  231. evaluate_evp_for_aes(-1);
  232. evaluate_ctr_for_aes();
  233. }
  234. return 0;
  235. }
  236. /** Free crypto resources held by this thread. */
  237. void
  238. crypto_thread_cleanup(void)
  239. {
  240. #ifndef NEW_THREAD_API
  241. ERR_remove_thread_state(NULL);
  242. #endif
  243. }
  244. /** Allocate and return a new symmetric cipher using the provided key and iv.
  245. * The key is <b>bits</b> bits long; the IV is CIPHER_IV_LEN bytes. Both
  246. * must be provided. Key length must be 128, 192, or 256 */
  247. crypto_cipher_t *
  248. crypto_cipher_new_with_iv_and_bits(const uint8_t *key,
  249. const uint8_t *iv,
  250. int bits)
  251. {
  252. tor_assert(key);
  253. tor_assert(iv);
  254. return aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, bits);
  255. }
  256. /** Allocate and return a new symmetric cipher using the provided key and iv.
  257. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  258. * must be provided.
  259. */
  260. crypto_cipher_t *
  261. crypto_cipher_new_with_iv(const char *key, const char *iv)
  262. {
  263. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)iv,
  264. 128);
  265. }
  266. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  267. * zero bytes and key length <b>bits</b>. Key length must be 128, 192, or
  268. * 256. */
  269. crypto_cipher_t *
  270. crypto_cipher_new_with_bits(const char *key, int bits)
  271. {
  272. char zeroiv[CIPHER_IV_LEN];
  273. memset(zeroiv, 0, sizeof(zeroiv));
  274. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)zeroiv,
  275. bits);
  276. }
  277. /** Return a new crypto_cipher_t with the provided <b>key</b> (of
  278. * CIPHER_KEY_LEN bytes) and an IV of all zero bytes. */
  279. crypto_cipher_t *
  280. crypto_cipher_new(const char *key)
  281. {
  282. return crypto_cipher_new_with_bits(key, 128);
  283. }
  284. /** Free a symmetric cipher.
  285. */
  286. void
  287. crypto_cipher_free_(crypto_cipher_t *env)
  288. {
  289. if (!env)
  290. return;
  291. aes_cipher_free(env);
  292. }
  293. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  294. * every four characters. */
  295. void
  296. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  297. {
  298. int n = 0;
  299. char *end = out+outlen;
  300. tor_assert(outlen < SIZE_T_CEILING);
  301. while (*in && out<end) {
  302. *out++ = *in++;
  303. if (++n == 4 && *in && out<end) {
  304. n = 0;
  305. *out++ = ' ';
  306. }
  307. }
  308. tor_assert(out<end);
  309. *out = '\0';
  310. }
  311. /* symmetric crypto */
  312. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  313. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  314. * Does not check for failure.
  315. */
  316. int
  317. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  318. const char *from, size_t fromlen)
  319. {
  320. tor_assert(env);
  321. tor_assert(env);
  322. tor_assert(from);
  323. tor_assert(fromlen);
  324. tor_assert(to);
  325. tor_assert(fromlen < SIZE_T_CEILING);
  326. memcpy(to, from, fromlen);
  327. aes_crypt_inplace(env, to, fromlen);
  328. return 0;
  329. }
  330. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  331. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  332. * Does not check for failure.
  333. */
  334. int
  335. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  336. const char *from, size_t fromlen)
  337. {
  338. tor_assert(env);
  339. tor_assert(from);
  340. tor_assert(to);
  341. tor_assert(fromlen < SIZE_T_CEILING);
  342. memcpy(to, from, fromlen);
  343. aes_crypt_inplace(env, to, fromlen);
  344. return 0;
  345. }
  346. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  347. * on success. Does not check for failure.
  348. */
  349. void
  350. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  351. {
  352. tor_assert(len < SIZE_T_CEILING);
  353. aes_crypt_inplace(env, buf, len);
  354. }
  355. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  356. * <b>key</b> to the buffer in <b>to</b> of length
  357. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  358. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  359. * number of bytes written, on failure, return -1.
  360. */
  361. int
  362. crypto_cipher_encrypt_with_iv(const char *key,
  363. char *to, size_t tolen,
  364. const char *from, size_t fromlen)
  365. {
  366. crypto_cipher_t *cipher;
  367. tor_assert(from);
  368. tor_assert(to);
  369. tor_assert(fromlen < INT_MAX);
  370. if (fromlen < 1)
  371. return -1;
  372. if (tolen < fromlen + CIPHER_IV_LEN)
  373. return -1;
  374. char iv[CIPHER_IV_LEN];
  375. crypto_rand(iv, sizeof(iv));
  376. cipher = crypto_cipher_new_with_iv(key, iv);
  377. memcpy(to, iv, CIPHER_IV_LEN);
  378. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  379. crypto_cipher_free(cipher);
  380. memwipe(iv, 0, sizeof(iv));
  381. return (int)(fromlen + CIPHER_IV_LEN);
  382. }
  383. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  384. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  385. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  386. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  387. * number of bytes written, on failure, return -1.
  388. */
  389. int
  390. crypto_cipher_decrypt_with_iv(const char *key,
  391. char *to, size_t tolen,
  392. const char *from, size_t fromlen)
  393. {
  394. crypto_cipher_t *cipher;
  395. tor_assert(key);
  396. tor_assert(from);
  397. tor_assert(to);
  398. tor_assert(fromlen < INT_MAX);
  399. if (fromlen <= CIPHER_IV_LEN)
  400. return -1;
  401. if (tolen < fromlen - CIPHER_IV_LEN)
  402. return -1;
  403. cipher = crypto_cipher_new_with_iv(key, from);
  404. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  405. crypto_cipher_free(cipher);
  406. return (int)(fromlen - CIPHER_IV_LEN);
  407. }
  408. /** @{ */
  409. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  410. * failure.
  411. */
  412. int
  413. crypto_global_cleanup(void)
  414. {
  415. #ifndef OPENSSL_1_1_API
  416. EVP_cleanup();
  417. #endif
  418. #ifndef NEW_THREAD_API
  419. ERR_remove_thread_state(NULL);
  420. #endif
  421. #ifndef OPENSSL_1_1_API
  422. ERR_free_strings();
  423. #endif
  424. crypto_dh_free_all();
  425. #ifndef DISABLE_ENGINES
  426. #ifndef OPENSSL_1_1_API
  427. ENGINE_cleanup();
  428. #endif
  429. #endif
  430. CONF_modules_unload(1);
  431. #ifndef OPENSSL_1_1_API
  432. CRYPTO_cleanup_all_ex_data();
  433. #endif
  434. crypto_openssl_free_all();
  435. crypto_early_initialized_ = 0;
  436. crypto_global_initialized_ = 0;
  437. have_seeded_siphash = 0;
  438. siphash_unset_global_key();
  439. return 0;
  440. }
  441. /** @} */