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