crypto.c 14 KB

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