crypto_openssl_mgt.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_openssl_mgt.c
  8. *
  9. * \brief Block of functions related to operations from OpenSSL.
  10. **/
  11. #include "lib/crypt_ops/compat_openssl.h"
  12. #include "lib/crypt_ops/crypto_openssl_mgt.h"
  13. #include "lib/crypt_ops/crypto_rand.h"
  14. #include "lib/crypt_ops/aes.h"
  15. #include "lib/string/util_string.h"
  16. #include "lib/lock/compat_mutex.h"
  17. #include "lib/log/log.h"
  18. #include "lib/log/util_bug.h"
  19. #include "lib/testsupport/testsupport.h"
  20. #include "lib/thread/threads.h"
  21. DISABLE_GCC_WARNING(redundant-decls)
  22. #include <openssl/err.h>
  23. #include <openssl/rsa.h>
  24. #include <openssl/pem.h>
  25. #include <openssl/evp.h>
  26. #include <openssl/engine.h>
  27. #include <openssl/rand.h>
  28. #include <openssl/bn.h>
  29. #include <openssl/dh.h>
  30. #include <openssl/conf.h>
  31. #include <openssl/hmac.h>
  32. #include <openssl/crypto.h>
  33. #include <openssl/ssl.h>
  34. ENABLE_GCC_WARNING(redundant-decls)
  35. #include <string.h>
  36. #ifndef NEW_THREAD_API
  37. /** A number of preallocated mutexes for use by OpenSSL. */
  38. static tor_mutex_t **openssl_mutexes_ = NULL;
  39. /** How many mutexes have we allocated for use by OpenSSL? */
  40. static int n_openssl_mutexes_ = 0;
  41. #endif /* !defined(NEW_THREAD_API) */
  42. /** Declare STATIC functions */
  43. STATIC char * parse_openssl_version_str(const char *raw_version);
  44. #ifndef NEW_THREAD_API
  45. STATIC void openssl_locking_cb_(int mode, int n, const char *file, int line);
  46. STATIC void tor_set_openssl_thread_id(CRYPTO_THREADID *threadid);
  47. #endif
  48. /** Log all pending crypto errors at level <b>severity</b>. Use
  49. * <b>doing</b> to describe our current activities.
  50. */
  51. void
  52. crypto_openssl_log_errors(int severity, const char *doing)
  53. {
  54. unsigned long err;
  55. const char *msg, *lib, *func;
  56. while ((err = ERR_get_error()) != 0) {
  57. msg = (const char*)ERR_reason_error_string(err);
  58. lib = (const char*)ERR_lib_error_string(err);
  59. func = (const char*)ERR_func_error_string(err);
  60. if (!msg) msg = "(null)";
  61. if (!lib) lib = "(null)";
  62. if (!func) func = "(null)";
  63. if (BUG(!doing)) doing = "(null)";
  64. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  65. doing, msg, lib, func);
  66. }
  67. }
  68. /* Returns a trimmed and human-readable version of an openssl version string
  69. * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
  70. * May 2012' and this will parse them into a form similar to '1.0.0b' */
  71. STATIC char *
  72. parse_openssl_version_str(const char *raw_version)
  73. {
  74. const char *end_of_version = NULL;
  75. /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
  76. trim that down. */
  77. if (!strcmpstart(raw_version, "OpenSSL ")) {
  78. raw_version += strlen("OpenSSL ");
  79. end_of_version = strchr(raw_version, ' ');
  80. }
  81. if (end_of_version)
  82. return tor_strndup(raw_version,
  83. end_of_version-raw_version);
  84. else
  85. return tor_strdup(raw_version);
  86. }
  87. static char *crypto_openssl_version_str = NULL;
  88. /* Return a human-readable version of the run-time openssl version number. */
  89. const char *
  90. crypto_openssl_get_version_str(void)
  91. {
  92. if (crypto_openssl_version_str == NULL) {
  93. const char *raw_version = OpenSSL_version(OPENSSL_VERSION);
  94. crypto_openssl_version_str = parse_openssl_version_str(raw_version);
  95. }
  96. return crypto_openssl_version_str;
  97. }
  98. static char *crypto_openssl_header_version_str = NULL;
  99. /* Return a human-readable version of the compile-time openssl version
  100. * number. */
  101. const char *
  102. crypto_openssl_get_header_version_str(void)
  103. {
  104. if (crypto_openssl_header_version_str == NULL) {
  105. crypto_openssl_header_version_str =
  106. parse_openssl_version_str(OPENSSL_VERSION_TEXT);
  107. }
  108. return crypto_openssl_header_version_str;
  109. }
  110. #ifndef OPENSSL_THREADS
  111. #error OpenSSL has been built without thread support. Tor requires an \
  112. OpenSSL library with thread support enabled.
  113. #endif
  114. #ifndef NEW_THREAD_API
  115. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  116. STATIC void
  117. openssl_locking_cb_(int mode, int n, const char *file, int line)
  118. {
  119. (void)file;
  120. (void)line;
  121. if (!openssl_mutexes_)
  122. /* This is not a really good fix for the
  123. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  124. * it can't hurt. */
  125. return;
  126. if (mode & CRYPTO_LOCK)
  127. tor_mutex_acquire(openssl_mutexes_[n]);
  128. else
  129. tor_mutex_release(openssl_mutexes_[n]);
  130. }
  131. STATIC void
  132. tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
  133. {
  134. CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
  135. }
  136. #endif /* !defined(NEW_THREAD_API) */
  137. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  138. * multithreaded. Returns 0. */
  139. static int
  140. setup_openssl_threading(void)
  141. {
  142. #ifndef NEW_THREAD_API
  143. int i;
  144. int n = CRYPTO_num_locks();
  145. n_openssl_mutexes_ = n;
  146. openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
  147. for (i=0; i < n; ++i)
  148. openssl_mutexes_[i] = tor_mutex_new();
  149. CRYPTO_set_locking_callback(openssl_locking_cb_);
  150. CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
  151. #endif /* !defined(NEW_THREAD_API) */
  152. return 0;
  153. }
  154. /** free OpenSSL variables */
  155. static void
  156. crypto_openssl_free_all(void)
  157. {
  158. tor_free(crypto_openssl_version_str);
  159. tor_free(crypto_openssl_header_version_str);
  160. /* Destroying a locked mutex is undefined behaviour. This mutex may be
  161. * locked, because multiple threads can access it. But we need to destroy
  162. * it, otherwise re-initialisation will trigger undefined behaviour.
  163. * See #31735 for details. */
  164. #ifndef NEW_THREAD_API
  165. if (n_openssl_mutexes_) {
  166. int n = n_openssl_mutexes_;
  167. tor_mutex_t **ms = openssl_mutexes_;
  168. int i;
  169. openssl_mutexes_ = NULL;
  170. n_openssl_mutexes_ = 0;
  171. for (i=0;i<n;++i) {
  172. tor_mutex_free(ms[i]);
  173. }
  174. tor_free(ms);
  175. }
  176. #endif /* !defined(NEW_THREAD_API) */
  177. }
  178. /** Perform early (pre-configuration) initialization tasks for OpenSSL. */
  179. void
  180. crypto_openssl_early_init(void)
  181. {
  182. #ifdef OPENSSL_1_1_API
  183. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  184. OPENSSL_INIT_LOAD_CRYPTO_STRINGS |
  185. OPENSSL_INIT_ADD_ALL_CIPHERS |
  186. OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
  187. #else /* !defined(OPENSSL_1_1_API) */
  188. ERR_load_crypto_strings();
  189. OpenSSL_add_all_algorithms();
  190. #endif /* defined(OPENSSL_1_1_API) */
  191. setup_openssl_threading();
  192. unsigned long version_num = OpenSSL_version_num();
  193. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  194. if (version_num == OPENSSL_VERSION_NUMBER &&
  195. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  196. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  197. "(%lx: %s).", version_num, version_str);
  198. } else if ((version_num & 0xffff0000) ==
  199. (OPENSSL_VERSION_NUMBER & 0xffff0000)) {
  200. log_notice(LD_CRYPTO,
  201. "We compiled with OpenSSL %lx: %s and we "
  202. "are running with OpenSSL %lx: %s. "
  203. "These two versions should be binary compatible.",
  204. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  205. version_num, version_str);
  206. } else {
  207. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  208. "version we're running with. If you get weird crashes, that "
  209. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  210. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  211. version_num, version_str);
  212. }
  213. crypto_force_rand_ssleay();
  214. }
  215. #ifndef DISABLE_ENGINES
  216. /** Try to load an engine in a shared library via fully qualified path.
  217. */
  218. static ENGINE *
  219. try_load_engine(const char *path, const char *engine)
  220. {
  221. ENGINE *e = ENGINE_by_id("dynamic");
  222. if (e) {
  223. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  224. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  225. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  226. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  227. ENGINE_free(e);
  228. e = NULL;
  229. }
  230. }
  231. return e;
  232. }
  233. #endif /* !defined(DISABLE_ENGINES) */
  234. #ifndef DISABLE_ENGINES
  235. /** Log any OpenSSL engines we're using at NOTICE. */
  236. static void
  237. log_engine(const char *fn, ENGINE *e)
  238. {
  239. if (e) {
  240. const char *name, *id;
  241. name = ENGINE_get_name(e);
  242. id = ENGINE_get_id(e);
  243. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  244. fn, name?name:"?", id?id:"?");
  245. } else {
  246. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  247. }
  248. }
  249. #endif /* !defined(DISABLE_ENGINES) */
  250. /** Initialize engines for openssl (if enabled). */
  251. static void
  252. crypto_openssl_init_engines(const char *accelName,
  253. const char *accelDir)
  254. {
  255. #ifdef DISABLE_ENGINES
  256. (void)accelName;
  257. (void)accelDir;
  258. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  259. #else
  260. ENGINE *e = NULL;
  261. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  262. ENGINE_load_builtin_engines();
  263. ENGINE_register_all_complete();
  264. if (accelName) {
  265. if (accelDir) {
  266. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  267. " via path \"%s\".", accelName, accelDir);
  268. e = try_load_engine(accelName, accelDir);
  269. } else {
  270. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  271. " acceleration support.", accelName);
  272. e = ENGINE_by_id(accelName);
  273. }
  274. if (!e) {
  275. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  276. accelName);
  277. } else {
  278. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  279. accelName);
  280. }
  281. }
  282. if (e) {
  283. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  284. " setting default ciphers.");
  285. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  286. }
  287. /* Log, if available, the intersection of the set of algorithms
  288. used by Tor and the set of algorithms available in the engine */
  289. log_engine("RSA", ENGINE_get_default_RSA());
  290. log_engine("DH", ENGINE_get_default_DH());
  291. #ifdef OPENSSL_1_1_API
  292. log_engine("EC", ENGINE_get_default_EC());
  293. #else
  294. log_engine("ECDH", ENGINE_get_default_ECDH());
  295. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  296. #endif /* defined(OPENSSL_1_1_API) */
  297. log_engine("RAND", ENGINE_get_default_RAND());
  298. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  299. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  300. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  301. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  302. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  303. #ifdef NID_aes_128_ctr
  304. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  305. #endif
  306. #ifdef NID_aes_128_gcm
  307. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  308. #endif
  309. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  310. #ifdef NID_aes_256_gcm
  311. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  312. #endif
  313. #endif /* defined(DISABLE_ENGINES) */
  314. }
  315. /** Perform late (post-init) initialization tasks for OpenSSL */
  316. int
  317. crypto_openssl_late_init(int useAccel, const char *accelName,
  318. const char *accelDir)
  319. {
  320. if (useAccel > 0) {
  321. crypto_openssl_init_engines(accelName, accelDir);
  322. } else {
  323. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  324. }
  325. if (crypto_force_rand_ssleay()) {
  326. if (crypto_seed_rng() < 0)
  327. return -1;
  328. }
  329. evaluate_evp_for_aes(-1);
  330. evaluate_ctr_for_aes();
  331. return 0;
  332. }
  333. /** Free crypto resources held by this thread. */
  334. void
  335. crypto_openssl_thread_cleanup(void)
  336. {
  337. #ifndef NEW_THREAD_API
  338. ERR_remove_thread_state(NULL);
  339. #endif
  340. }
  341. /** Clean up global resources held by openssl. */
  342. void
  343. crypto_openssl_global_cleanup(void)
  344. {
  345. #ifndef OPENSSL_1_1_API
  346. EVP_cleanup();
  347. #endif
  348. #ifndef NEW_THREAD_API
  349. ERR_remove_thread_state(NULL);
  350. #endif
  351. #ifndef OPENSSL_1_1_API
  352. ERR_free_strings();
  353. #endif
  354. #ifndef DISABLE_ENGINES
  355. #ifndef OPENSSL_1_1_API
  356. ENGINE_cleanup();
  357. #endif
  358. #endif
  359. CONF_modules_unload(1);
  360. #ifndef OPENSSL_1_1_API
  361. CRYPTO_cleanup_all_ex_data();
  362. #endif
  363. crypto_openssl_free_all();
  364. }