crypto.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  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-2017, 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 "crypto.h"
  23. #include "compat_openssl.h"
  24. #include "crypto_curve25519.h"
  25. #include "crypto_ed25519.h"
  26. #include "crypto_format.h"
  27. #include "crypto_rsa.h"
  28. #include "crypto_digest.h"
  29. DISABLE_GCC_WARNING(redundant-decls)
  30. #include <openssl/err.h>
  31. #include <openssl/rsa.h>
  32. #include <openssl/pem.h>
  33. #include <openssl/evp.h>
  34. #include <openssl/engine.h>
  35. #include <openssl/rand.h>
  36. #include <openssl/bn.h>
  37. #include <openssl/dh.h>
  38. #include <openssl/conf.h>
  39. #include <openssl/hmac.h>
  40. ENABLE_GCC_WARNING(redundant-decls)
  41. #if __GNUC__ && GCC_VERSION >= 402
  42. #if GCC_VERSION >= 406
  43. #pragma GCC diagnostic pop
  44. #else
  45. #pragma GCC diagnostic warning "-Wredundant-decls"
  46. #endif
  47. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  48. #ifdef HAVE_CTYPE_H
  49. #include <ctype.h>
  50. #endif
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h>
  53. #endif
  54. #ifdef HAVE_FCNTL_H
  55. #include <fcntl.h>
  56. #endif
  57. #ifdef HAVE_SYS_FCNTL_H
  58. #include <sys/fcntl.h>
  59. #endif
  60. #ifdef HAVE_SYS_SYSCALL_H
  61. #include <sys/syscall.h>
  62. #endif
  63. #ifdef HAVE_SYS_RANDOM_H
  64. #include <sys/random.h>
  65. #endif
  66. #include "torlog.h"
  67. #include "torint.h"
  68. #include "aes.h"
  69. #include "util.h"
  70. #include "container.h"
  71. #include "compat.h"
  72. #include "sandbox.h"
  73. #include "util_format.h"
  74. #include "keccak-tiny/keccak-tiny.h"
  75. /** Longest recognized */
  76. #define MAX_DNS_LABEL_SIZE 63
  77. /** Largest strong entropy request */
  78. #define MAX_STRONGEST_RAND_SIZE 256
  79. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  80. * while we're waiting for the second.*/
  81. struct crypto_dh_t {
  82. DH *dh; /**< The openssl DH object */
  83. };
  84. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  85. /** Boolean: has OpenSSL's crypto been initialized? */
  86. static int crypto_early_initialized_ = 0;
  87. /** Boolean: has OpenSSL's crypto been initialized? */
  88. static int crypto_global_initialized_ = 0;
  89. /** Log all pending crypto errors at level <b>severity</b>. Use
  90. * <b>doing</b> to describe our current activities.
  91. */
  92. static void
  93. crypto_log_errors(int severity, const char *doing)
  94. {
  95. unsigned long err;
  96. const char *msg, *lib, *func;
  97. while ((err = ERR_get_error()) != 0) {
  98. msg = (const char*)ERR_reason_error_string(err);
  99. lib = (const char*)ERR_lib_error_string(err);
  100. func = (const char*)ERR_func_error_string(err);
  101. if (!msg) msg = "(null)";
  102. if (!lib) lib = "(null)";
  103. if (!func) func = "(null)";
  104. if (BUG(!doing)) doing = "(null)";
  105. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  106. doing, msg, lib, func);
  107. }
  108. }
  109. #ifndef DISABLE_ENGINES
  110. /** Log any OpenSSL engines we're using at NOTICE. */
  111. static void
  112. log_engine(const char *fn, ENGINE *e)
  113. {
  114. if (e) {
  115. const char *name, *id;
  116. name = ENGINE_get_name(e);
  117. id = ENGINE_get_id(e);
  118. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  119. fn, name?name:"?", id?id:"?");
  120. } else {
  121. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  122. }
  123. }
  124. #endif /* !defined(DISABLE_ENGINES) */
  125. #ifndef DISABLE_ENGINES
  126. /** Try to load an engine in a shared library via fully qualified path.
  127. */
  128. static ENGINE *
  129. try_load_engine(const char *path, const char *engine)
  130. {
  131. ENGINE *e = ENGINE_by_id("dynamic");
  132. if (e) {
  133. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  134. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  135. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  136. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  137. ENGINE_free(e);
  138. e = NULL;
  139. }
  140. }
  141. return e;
  142. }
  143. #endif /* !defined(DISABLE_ENGINES) */
  144. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  145. * adjust it; 0 otherwise. */
  146. STATIC int
  147. crypto_force_rand_ssleay(void)
  148. {
  149. RAND_METHOD *default_method;
  150. default_method = RAND_OpenSSL();
  151. if (RAND_get_rand_method() != default_method) {
  152. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  153. "a replacement the OpenSSL RNG. Resetting it to the default "
  154. "implementation.");
  155. RAND_set_rand_method(default_method);
  156. return 1;
  157. }
  158. return 0;
  159. }
  160. static int have_seeded_siphash = 0;
  161. /** Set up the siphash key if we haven't already done so. */
  162. int
  163. crypto_init_siphash_key(void)
  164. {
  165. struct sipkey key;
  166. if (have_seeded_siphash)
  167. return 0;
  168. crypto_rand((char*) &key, sizeof(key));
  169. siphash_set_global_key(&key);
  170. have_seeded_siphash = 1;
  171. return 0;
  172. }
  173. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  174. */
  175. int
  176. crypto_early_init(void)
  177. {
  178. if (!crypto_early_initialized_) {
  179. crypto_early_initialized_ = 1;
  180. ERR_load_crypto_strings();
  181. OpenSSL_add_all_algorithms();
  182. setup_openssl_threading();
  183. unsigned long version_num = OpenSSL_version_num();
  184. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  185. if (version_num == OPENSSL_VERSION_NUMBER &&
  186. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  187. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  188. "(%lx: %s).", version_num, version_str);
  189. } else {
  190. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  191. "version we're running with. If you get weird crashes, that "
  192. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  193. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  194. version_num, version_str);
  195. }
  196. crypto_force_rand_ssleay();
  197. if (crypto_seed_rng() < 0)
  198. return -1;
  199. if (crypto_init_siphash_key() < 0)
  200. return -1;
  201. curve25519_init();
  202. ed25519_init();
  203. }
  204. return 0;
  205. }
  206. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  207. */
  208. int
  209. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  210. {
  211. if (!crypto_global_initialized_) {
  212. if (crypto_early_init() < 0)
  213. return -1;
  214. crypto_global_initialized_ = 1;
  215. if (useAccel > 0) {
  216. #ifdef DISABLE_ENGINES
  217. (void)accelName;
  218. (void)accelDir;
  219. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  220. #else
  221. ENGINE *e = NULL;
  222. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  223. ENGINE_load_builtin_engines();
  224. ENGINE_register_all_complete();
  225. if (accelName) {
  226. if (accelDir) {
  227. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  228. " via path \"%s\".", accelName, accelDir);
  229. e = try_load_engine(accelName, accelDir);
  230. } else {
  231. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  232. " acceleration support.", accelName);
  233. e = ENGINE_by_id(accelName);
  234. }
  235. if (!e) {
  236. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  237. accelName);
  238. } else {
  239. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  240. accelName);
  241. }
  242. }
  243. if (e) {
  244. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  245. " setting default ciphers.");
  246. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  247. }
  248. /* Log, if available, the intersection of the set of algorithms
  249. used by Tor and the set of algorithms available in the engine */
  250. log_engine("RSA", ENGINE_get_default_RSA());
  251. log_engine("DH", ENGINE_get_default_DH());
  252. #ifdef OPENSSL_1_1_API
  253. log_engine("EC", ENGINE_get_default_EC());
  254. #else
  255. log_engine("ECDH", ENGINE_get_default_ECDH());
  256. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  257. #endif /* defined(OPENSSL_1_1_API) */
  258. log_engine("RAND", ENGINE_get_default_RAND());
  259. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  260. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  261. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  262. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  263. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  264. #ifdef NID_aes_128_ctr
  265. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  266. #endif
  267. #ifdef NID_aes_128_gcm
  268. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  269. #endif
  270. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  271. #ifdef NID_aes_256_gcm
  272. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  273. #endif
  274. #endif /* defined(DISABLE_ENGINES) */
  275. } else {
  276. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  277. }
  278. if (crypto_force_rand_ssleay()) {
  279. if (crypto_seed_rng() < 0)
  280. return -1;
  281. }
  282. evaluate_evp_for_aes(-1);
  283. evaluate_ctr_for_aes();
  284. }
  285. return 0;
  286. }
  287. /** Free crypto resources held by this thread. */
  288. void
  289. crypto_thread_cleanup(void)
  290. {
  291. #ifndef NEW_THREAD_API
  292. ERR_remove_thread_state(NULL);
  293. #endif
  294. }
  295. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  296. */
  297. DH *
  298. crypto_dh_get_dh_(crypto_dh_t *dh)
  299. {
  300. return dh->dh;
  301. }
  302. /** Allocate and return a new symmetric cipher using the provided key and iv.
  303. * The key is <b>bits</b> bits long; the IV is CIPHER_IV_LEN bytes. Both
  304. * must be provided. Key length must be 128, 192, or 256 */
  305. crypto_cipher_t *
  306. crypto_cipher_new_with_iv_and_bits(const uint8_t *key,
  307. const uint8_t *iv,
  308. int bits)
  309. {
  310. tor_assert(key);
  311. tor_assert(iv);
  312. return aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, bits);
  313. }
  314. /** Allocate and return a new symmetric cipher using the provided key and iv.
  315. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  316. * must be provided.
  317. */
  318. crypto_cipher_t *
  319. crypto_cipher_new_with_iv(const char *key, const char *iv)
  320. {
  321. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)iv,
  322. 128);
  323. }
  324. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  325. * zero bytes and key length <b>bits</b>. Key length must be 128, 192, or
  326. * 256. */
  327. crypto_cipher_t *
  328. crypto_cipher_new_with_bits(const char *key, int bits)
  329. {
  330. char zeroiv[CIPHER_IV_LEN];
  331. memset(zeroiv, 0, sizeof(zeroiv));
  332. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)zeroiv,
  333. bits);
  334. }
  335. /** Return a new crypto_cipher_t with the provided <b>key</b> (of
  336. * CIPHER_KEY_LEN bytes) and an IV of all zero bytes. */
  337. crypto_cipher_t *
  338. crypto_cipher_new(const char *key)
  339. {
  340. return crypto_cipher_new_with_bits(key, 128);
  341. }
  342. /** Free a symmetric cipher.
  343. */
  344. void
  345. crypto_cipher_free_(crypto_cipher_t *env)
  346. {
  347. if (!env)
  348. return;
  349. aes_cipher_free(env);
  350. }
  351. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  352. * every four characters. */
  353. void
  354. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  355. {
  356. int n = 0;
  357. char *end = out+outlen;
  358. tor_assert(outlen < SIZE_T_CEILING);
  359. while (*in && out<end) {
  360. *out++ = *in++;
  361. if (++n == 4 && *in && out<end) {
  362. n = 0;
  363. *out++ = ' ';
  364. }
  365. }
  366. tor_assert(out<end);
  367. *out = '\0';
  368. }
  369. /* symmetric crypto */
  370. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  371. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  372. * Does not check for failure.
  373. */
  374. int
  375. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  376. const char *from, size_t fromlen)
  377. {
  378. tor_assert(env);
  379. tor_assert(env);
  380. tor_assert(from);
  381. tor_assert(fromlen);
  382. tor_assert(to);
  383. tor_assert(fromlen < SIZE_T_CEILING);
  384. memcpy(to, from, fromlen);
  385. aes_crypt_inplace(env, to, fromlen);
  386. return 0;
  387. }
  388. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  389. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  390. * Does not check for failure.
  391. */
  392. int
  393. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  394. const char *from, size_t fromlen)
  395. {
  396. tor_assert(env);
  397. tor_assert(from);
  398. tor_assert(to);
  399. tor_assert(fromlen < SIZE_T_CEILING);
  400. memcpy(to, from, fromlen);
  401. aes_crypt_inplace(env, to, fromlen);
  402. return 0;
  403. }
  404. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  405. * on success. Does not check for failure.
  406. */
  407. void
  408. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  409. {
  410. tor_assert(len < SIZE_T_CEILING);
  411. aes_crypt_inplace(env, buf, len);
  412. }
  413. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  414. * <b>key</b> to the buffer in <b>to</b> of length
  415. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  416. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  417. * number of bytes written, on failure, return -1.
  418. */
  419. int
  420. crypto_cipher_encrypt_with_iv(const char *key,
  421. char *to, size_t tolen,
  422. const char *from, size_t fromlen)
  423. {
  424. crypto_cipher_t *cipher;
  425. tor_assert(from);
  426. tor_assert(to);
  427. tor_assert(fromlen < INT_MAX);
  428. if (fromlen < 1)
  429. return -1;
  430. if (tolen < fromlen + CIPHER_IV_LEN)
  431. return -1;
  432. char iv[CIPHER_IV_LEN];
  433. crypto_rand(iv, sizeof(iv));
  434. cipher = crypto_cipher_new_with_iv(key, iv);
  435. memcpy(to, iv, CIPHER_IV_LEN);
  436. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  437. crypto_cipher_free(cipher);
  438. memwipe(iv, 0, sizeof(iv));
  439. return (int)(fromlen + CIPHER_IV_LEN);
  440. }
  441. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  442. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  443. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  444. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  445. * number of bytes written, on failure, return -1.
  446. */
  447. int
  448. crypto_cipher_decrypt_with_iv(const char *key,
  449. char *to, size_t tolen,
  450. const char *from, size_t fromlen)
  451. {
  452. crypto_cipher_t *cipher;
  453. tor_assert(key);
  454. tor_assert(from);
  455. tor_assert(to);
  456. tor_assert(fromlen < INT_MAX);
  457. if (fromlen <= CIPHER_IV_LEN)
  458. return -1;
  459. if (tolen < fromlen - CIPHER_IV_LEN)
  460. return -1;
  461. cipher = crypto_cipher_new_with_iv(key, from);
  462. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  463. crypto_cipher_free(cipher);
  464. return (int)(fromlen - CIPHER_IV_LEN);
  465. }
  466. /* DH */
  467. /** Our DH 'g' parameter */
  468. #define DH_GENERATOR 2
  469. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  470. static BIGNUM *dh_param_p = NULL;
  471. /** Shared P parameter for our TLS DH key exchanges. */
  472. static BIGNUM *dh_param_p_tls = NULL;
  473. /** Shared G parameter for our DH key exchanges. */
  474. static BIGNUM *dh_param_g = NULL;
  475. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  476. * computationally expensive (milliseconds), so should only be called when
  477. * the DH parameters change. Returns 0 on success, * -1 on failure.
  478. */
  479. static int
  480. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  481. {
  482. DH *dh = NULL;
  483. int ret = -1;
  484. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  485. if (!(dh = DH_new()))
  486. goto out;
  487. #ifdef OPENSSL_1_1_API
  488. BIGNUM *dh_p, *dh_g;
  489. if (!(dh_p = BN_dup(p)))
  490. goto out;
  491. if (!(dh_g = BN_dup(g)))
  492. goto out;
  493. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  494. goto out;
  495. #else /* !(defined(OPENSSL_1_1_API)) */
  496. if (!(dh->p = BN_dup(p)))
  497. goto out;
  498. if (!(dh->g = BN_dup(g)))
  499. goto out;
  500. #endif /* defined(OPENSSL_1_1_API) */
  501. /* Perform the validation. */
  502. int codes = 0;
  503. if (!DH_check(dh, &codes))
  504. goto out;
  505. if (BN_is_word(g, DH_GENERATOR_2)) {
  506. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  507. *
  508. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  509. * IETF's primes are congruent to 23 when g = 2.
  510. */
  511. BN_ULONG residue = BN_mod_word(p, 24);
  512. if (residue == 11 || residue == 23)
  513. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  514. }
  515. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  516. goto out;
  517. /* Things are probably not evil. */
  518. ret = 0;
  519. out:
  520. if (dh)
  521. DH_free(dh);
  522. return ret;
  523. }
  524. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  525. * DH stuff.
  526. */
  527. static void
  528. crypto_set_dh_generator(void)
  529. {
  530. BIGNUM *generator;
  531. int r;
  532. if (dh_param_g)
  533. return;
  534. generator = BN_new();
  535. tor_assert(generator);
  536. r = BN_set_word(generator, DH_GENERATOR);
  537. tor_assert(r);
  538. dh_param_g = generator;
  539. }
  540. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  541. * modulus. */
  542. void
  543. crypto_set_tls_dh_prime(void)
  544. {
  545. BIGNUM *tls_prime = NULL;
  546. int r;
  547. /* If the space is occupied, free the previous TLS DH prime */
  548. if (BUG(dh_param_p_tls)) {
  549. /* LCOV_EXCL_START
  550. *
  551. * We shouldn't be calling this twice.
  552. */
  553. BN_clear_free(dh_param_p_tls);
  554. dh_param_p_tls = NULL;
  555. /* LCOV_EXCL_STOP */
  556. }
  557. tls_prime = BN_new();
  558. tor_assert(tls_prime);
  559. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  560. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  561. * prime.
  562. */
  563. r = BN_hex2bn(&tls_prime,
  564. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  565. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  566. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  567. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  568. "B0E7393E0F24218EB3");
  569. tor_assert(r);
  570. tor_assert(tls_prime);
  571. dh_param_p_tls = tls_prime;
  572. crypto_set_dh_generator();
  573. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  574. }
  575. /** Initialize dh_param_p and dh_param_g if they are not already
  576. * set. */
  577. static void
  578. init_dh_param(void)
  579. {
  580. BIGNUM *circuit_dh_prime;
  581. int r;
  582. if (BUG(dh_param_p && dh_param_g))
  583. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  584. circuit_dh_prime = BN_new();
  585. tor_assert(circuit_dh_prime);
  586. /* This is from rfc2409, section 6.2. It's a safe prime, and
  587. supposedly it equals:
  588. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  589. */
  590. r = BN_hex2bn(&circuit_dh_prime,
  591. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  592. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  593. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  594. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  595. "49286651ECE65381FFFFFFFFFFFFFFFF");
  596. tor_assert(r);
  597. /* Set the new values as the global DH parameters. */
  598. dh_param_p = circuit_dh_prime;
  599. crypto_set_dh_generator();
  600. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  601. if (!dh_param_p_tls) {
  602. crypto_set_tls_dh_prime();
  603. }
  604. }
  605. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  606. * handshake. Since we exponentiate by this value, choosing a smaller one
  607. * lets our handhake go faster.
  608. */
  609. #define DH_PRIVATE_KEY_BITS 320
  610. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  611. * failure.
  612. */
  613. crypto_dh_t *
  614. crypto_dh_new(int dh_type)
  615. {
  616. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  617. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  618. dh_type == DH_TYPE_REND);
  619. if (!dh_param_p)
  620. init_dh_param();
  621. if (!(res->dh = DH_new()))
  622. goto err;
  623. #ifdef OPENSSL_1_1_API
  624. BIGNUM *dh_p = NULL, *dh_g = NULL;
  625. if (dh_type == DH_TYPE_TLS) {
  626. dh_p = BN_dup(dh_param_p_tls);
  627. } else {
  628. dh_p = BN_dup(dh_param_p);
  629. }
  630. if (!dh_p)
  631. goto err;
  632. dh_g = BN_dup(dh_param_g);
  633. if (!dh_g) {
  634. BN_free(dh_p);
  635. goto err;
  636. }
  637. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  638. goto err;
  639. }
  640. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  641. goto err;
  642. #else /* !(defined(OPENSSL_1_1_API)) */
  643. if (dh_type == DH_TYPE_TLS) {
  644. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  645. goto err;
  646. } else {
  647. if (!(res->dh->p = BN_dup(dh_param_p)))
  648. goto err;
  649. }
  650. if (!(res->dh->g = BN_dup(dh_param_g)))
  651. goto err;
  652. res->dh->length = DH_PRIVATE_KEY_BITS;
  653. #endif /* defined(OPENSSL_1_1_API) */
  654. return res;
  655. /* LCOV_EXCL_START
  656. * This error condition is only reached when an allocation fails */
  657. err:
  658. crypto_log_errors(LOG_WARN, "creating DH object");
  659. if (res->dh) DH_free(res->dh); /* frees p and g too */
  660. tor_free(res);
  661. return NULL;
  662. /* LCOV_EXCL_STOP */
  663. }
  664. /** Return a copy of <b>dh</b>, sharing its internal state. */
  665. crypto_dh_t *
  666. crypto_dh_dup(const crypto_dh_t *dh)
  667. {
  668. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  669. tor_assert(dh);
  670. tor_assert(dh->dh);
  671. dh_new->dh = dh->dh;
  672. DH_up_ref(dh->dh);
  673. return dh_new;
  674. }
  675. /** Return the length of the DH key in <b>dh</b>, in bytes.
  676. */
  677. int
  678. crypto_dh_get_bytes(crypto_dh_t *dh)
  679. {
  680. tor_assert(dh);
  681. return DH_size(dh->dh);
  682. }
  683. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  684. * success, -1 on failure.
  685. */
  686. int
  687. crypto_dh_generate_public(crypto_dh_t *dh)
  688. {
  689. #ifndef OPENSSL_1_1_API
  690. again:
  691. #endif
  692. if (!DH_generate_key(dh->dh)) {
  693. /* LCOV_EXCL_START
  694. * To test this we would need some way to tell openssl to break DH. */
  695. crypto_log_errors(LOG_WARN, "generating DH key");
  696. return -1;
  697. /* LCOV_EXCL_STOP */
  698. }
  699. #ifdef OPENSSL_1_1_API
  700. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  701. * recreating the DH object. I have no idea what sort of aliasing madness
  702. * can occur here, so do the check, and just bail on failure.
  703. */
  704. const BIGNUM *pub_key, *priv_key;
  705. DH_get0_key(dh->dh, &pub_key, &priv_key);
  706. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  707. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  708. "the-universe chances really do happen. Treating as a failure.");
  709. return -1;
  710. }
  711. #else /* !(defined(OPENSSL_1_1_API)) */
  712. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  713. /* LCOV_EXCL_START
  714. * If this happens, then openssl's DH implementation is busted. */
  715. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  716. "the-universe chances really do happen. Trying again.");
  717. /* Free and clear the keys, so OpenSSL will actually try again. */
  718. BN_clear_free(dh->dh->pub_key);
  719. BN_clear_free(dh->dh->priv_key);
  720. dh->dh->pub_key = dh->dh->priv_key = NULL;
  721. goto again;
  722. /* LCOV_EXCL_STOP */
  723. }
  724. #endif /* defined(OPENSSL_1_1_API) */
  725. return 0;
  726. }
  727. /** Generate g^x as necessary, and write the g^x for the key exchange
  728. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  729. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  730. */
  731. int
  732. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  733. {
  734. int bytes;
  735. tor_assert(dh);
  736. const BIGNUM *dh_pub;
  737. #ifdef OPENSSL_1_1_API
  738. const BIGNUM *dh_priv;
  739. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  740. #else
  741. dh_pub = dh->dh->pub_key;
  742. #endif /* defined(OPENSSL_1_1_API) */
  743. if (!dh_pub) {
  744. if (crypto_dh_generate_public(dh)<0)
  745. return -1;
  746. else {
  747. #ifdef OPENSSL_1_1_API
  748. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  749. #else
  750. dh_pub = dh->dh->pub_key;
  751. #endif
  752. }
  753. }
  754. tor_assert(dh_pub);
  755. bytes = BN_num_bytes(dh_pub);
  756. tor_assert(bytes >= 0);
  757. if (pubkey_len < (size_t)bytes) {
  758. log_warn(LD_CRYPTO,
  759. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  760. (int) pubkey_len, bytes);
  761. return -1;
  762. }
  763. memset(pubkey, 0, pubkey_len);
  764. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  765. return 0;
  766. }
  767. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  768. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  769. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  770. */
  771. static int
  772. tor_check_dh_key(int severity, const BIGNUM *bn)
  773. {
  774. BIGNUM *x;
  775. char *s;
  776. tor_assert(bn);
  777. x = BN_new();
  778. tor_assert(x);
  779. if (BUG(!dh_param_p))
  780. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  781. BN_set_word(x, 1);
  782. if (BN_cmp(bn,x)<=0) {
  783. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  784. goto err;
  785. }
  786. BN_copy(x,dh_param_p);
  787. BN_sub_word(x, 1);
  788. if (BN_cmp(bn,x)>=0) {
  789. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  790. goto err;
  791. }
  792. BN_clear_free(x);
  793. return 0;
  794. err:
  795. BN_clear_free(x);
  796. s = BN_bn2hex(bn);
  797. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  798. OPENSSL_free(s);
  799. return -1;
  800. }
  801. /** Given a DH key exchange object, and our peer's value of g^y (as a
  802. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  803. * <b>secret_bytes_out</b> bytes of shared key material and write them
  804. * to <b>secret_out</b>. Return the number of bytes generated on success,
  805. * or -1 on failure.
  806. *
  807. * (We generate key material by computing
  808. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  809. * where || is concatenation.)
  810. */
  811. ssize_t
  812. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  813. const char *pubkey, size_t pubkey_len,
  814. char *secret_out, size_t secret_bytes_out)
  815. {
  816. char *secret_tmp = NULL;
  817. BIGNUM *pubkey_bn = NULL;
  818. size_t secret_len=0, secret_tmp_len=0;
  819. int result=0;
  820. tor_assert(dh);
  821. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  822. tor_assert(pubkey_len < INT_MAX);
  823. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  824. (int)pubkey_len, NULL)))
  825. goto error;
  826. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  827. /* Check for invalid public keys. */
  828. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  829. goto error;
  830. }
  831. secret_tmp_len = crypto_dh_get_bytes(dh);
  832. secret_tmp = tor_malloc(secret_tmp_len);
  833. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  834. if (result < 0) {
  835. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  836. goto error;
  837. }
  838. secret_len = result;
  839. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  840. (uint8_t*)secret_out, secret_bytes_out)<0)
  841. goto error;
  842. secret_len = secret_bytes_out;
  843. goto done;
  844. error:
  845. result = -1;
  846. done:
  847. crypto_log_errors(LOG_WARN, "completing DH handshake");
  848. if (pubkey_bn)
  849. BN_clear_free(pubkey_bn);
  850. if (secret_tmp) {
  851. memwipe(secret_tmp, 0, secret_tmp_len);
  852. tor_free(secret_tmp);
  853. }
  854. if (result < 0)
  855. return result;
  856. else
  857. return secret_len;
  858. }
  859. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  860. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  861. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  862. * H(K | [00]) | H(K | [01]) | ....
  863. *
  864. * This is the key expansion algorithm used in the "TAP" circuit extension
  865. * mechanism; it shouldn't be used for new protocols.
  866. *
  867. * Return 0 on success, -1 on failure.
  868. */
  869. int
  870. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  871. uint8_t *key_out, size_t key_out_len)
  872. {
  873. int i, r = -1;
  874. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  875. uint8_t digest[DIGEST_LEN];
  876. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  877. tor_assert(key_out_len <= DIGEST_LEN*256);
  878. memcpy(tmp, key_in, key_in_len);
  879. for (cp = key_out, i=0; cp < key_out+key_out_len;
  880. ++i, cp += DIGEST_LEN) {
  881. tmp[key_in_len] = i;
  882. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1) < 0)
  883. goto exit;
  884. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  885. }
  886. r = 0;
  887. exit:
  888. memwipe(tmp, 0, key_in_len+1);
  889. tor_free(tmp);
  890. memwipe(digest, 0, sizeof(digest));
  891. return r;
  892. }
  893. /** Expand some secret key material according to RFC5869, using SHA256 as the
  894. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  895. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  896. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  897. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  898. * bytes to <b>key_out</b> and return 0. Assert on failure.
  899. */
  900. int
  901. crypto_expand_key_material_rfc5869_sha256(
  902. const uint8_t *key_in, size_t key_in_len,
  903. const uint8_t *salt_in, size_t salt_in_len,
  904. const uint8_t *info_in, size_t info_in_len,
  905. uint8_t *key_out, size_t key_out_len)
  906. {
  907. uint8_t prk[DIGEST256_LEN];
  908. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  909. uint8_t mac[DIGEST256_LEN];
  910. int i;
  911. uint8_t *outp;
  912. size_t tmp_len;
  913. crypto_hmac_sha256((char*)prk,
  914. (const char*)salt_in, salt_in_len,
  915. (const char*)key_in, key_in_len);
  916. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  917. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  918. tor_assert(info_in_len <= 128);
  919. memset(tmp, 0, sizeof(tmp));
  920. outp = key_out;
  921. i = 1;
  922. while (key_out_len) {
  923. size_t n;
  924. if (i > 1) {
  925. memcpy(tmp, mac, DIGEST256_LEN);
  926. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  927. tmp[DIGEST256_LEN+info_in_len] = i;
  928. tmp_len = DIGEST256_LEN + info_in_len + 1;
  929. } else {
  930. memcpy(tmp, info_in, info_in_len);
  931. tmp[info_in_len] = i;
  932. tmp_len = info_in_len + 1;
  933. }
  934. crypto_hmac_sha256((char*)mac,
  935. (const char*)prk, DIGEST256_LEN,
  936. (const char*)tmp, tmp_len);
  937. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  938. memcpy(outp, mac, n);
  939. key_out_len -= n;
  940. outp += n;
  941. ++i;
  942. }
  943. memwipe(tmp, 0, sizeof(tmp));
  944. memwipe(mac, 0, sizeof(mac));
  945. return 0;
  946. }
  947. /** Free a DH key exchange object.
  948. */
  949. void
  950. crypto_dh_free_(crypto_dh_t *dh)
  951. {
  952. if (!dh)
  953. return;
  954. tor_assert(dh->dh);
  955. DH_free(dh->dh);
  956. tor_free(dh);
  957. }
  958. /* random numbers */
  959. /** How many bytes of entropy we add at once.
  960. *
  961. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  962. * work for us too. */
  963. #define ADD_ENTROPY 32
  964. /** Set the seed of the weak RNG to a random value. */
  965. void
  966. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  967. {
  968. unsigned seed;
  969. crypto_rand((void*)&seed, sizeof(seed));
  970. tor_init_weak_random(rng, seed);
  971. }
  972. #ifdef TOR_UNIT_TESTS
  973. int break_strongest_rng_syscall = 0;
  974. int break_strongest_rng_fallback = 0;
  975. #endif
  976. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  977. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  978. * failure. A maximum request size of 256 bytes is imposed.
  979. */
  980. static int
  981. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  982. {
  983. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  984. /* We only log at notice-level here because in the case that this function
  985. * fails the crypto_strongest_rand_raw() caller will log with a warning-level
  986. * message and let crypto_strongest_rand() error out and finally terminating
  987. * Tor with an assertion error.
  988. */
  989. #ifdef TOR_UNIT_TESTS
  990. if (break_strongest_rng_syscall)
  991. return -1;
  992. #endif
  993. #if defined(_WIN32)
  994. static int provider_set = 0;
  995. static HCRYPTPROV provider;
  996. if (!provider_set) {
  997. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  998. CRYPT_VERIFYCONTEXT)) {
  999. log_notice(LD_CRYPTO, "Unable to set Windows CryptoAPI provider [1].");
  1000. return -1;
  1001. }
  1002. provider_set = 1;
  1003. }
  1004. if (!CryptGenRandom(provider, out_len, out)) {
  1005. log_notice(LD_CRYPTO, "Unable get entropy from the Windows CryptoAPI.");
  1006. return -1;
  1007. }
  1008. return 0;
  1009. #elif defined(__linux__) && defined(SYS_getrandom)
  1010. static int getrandom_works = 1; /* Be optimistic about our chances... */
  1011. /* getrandom() isn't as straightforward as getentropy(), and has
  1012. * no glibc wrapper.
  1013. *
  1014. * As far as I can tell from getrandom(2) and the source code, the
  1015. * requests we issue will always succeed (though it will block on the
  1016. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  1017. * GRND_NONBLOCK and the request is <= 256 bytes.
  1018. *
  1019. * The manpage is unclear on what happens if a signal interrupts the call
  1020. * while the request is blocked due to lack of entropy....
  1021. *
  1022. * We optimistically assume that getrandom() is available and functional
  1023. * because it is the way of the future, and 2 branch mispredicts pale in
  1024. * comparison to the overheads involved with failing to open
  1025. * /dev/srandom followed by opening and reading from /dev/urandom.
  1026. */
  1027. if (PREDICT_LIKELY(getrandom_works)) {
  1028. long ret;
  1029. /* A flag of '0' here means to read from '/dev/urandom', and to
  1030. * block if insufficient entropy is available to service the
  1031. * request.
  1032. */
  1033. const unsigned int flags = 0;
  1034. do {
  1035. ret = syscall(SYS_getrandom, out, out_len, flags);
  1036. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  1037. if (PREDICT_UNLIKELY(ret == -1)) {
  1038. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  1039. tor_assert(errno != EAGAIN);
  1040. tor_assert(errno != EINTR);
  1041. /* Useful log message for errno. */
  1042. if (errno == ENOSYS) {
  1043. log_notice(LD_CRYPTO, "Can't get entropy from getrandom()."
  1044. " You are running a version of Tor built to support"
  1045. " getrandom(), but the kernel doesn't implement this"
  1046. " function--probably because it is too old?"
  1047. " Trying fallback method instead.");
  1048. } else {
  1049. log_notice(LD_CRYPTO, "Can't get entropy from getrandom(): %s."
  1050. " Trying fallback method instead.",
  1051. strerror(errno));
  1052. }
  1053. getrandom_works = 0; /* Don't bother trying again. */
  1054. return -1;
  1055. /* LCOV_EXCL_STOP */
  1056. }
  1057. tor_assert(ret == (long)out_len);
  1058. return 0;
  1059. }
  1060. return -1; /* getrandom() previously failed unexpectedly. */
  1061. #elif defined(HAVE_GETENTROPY)
  1062. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  1063. * the only gotcha is that requests are limited to 256 bytes.
  1064. */
  1065. return getentropy(out, out_len);
  1066. #else
  1067. (void) out;
  1068. #endif /* defined(_WIN32) || ... */
  1069. /* This platform doesn't have a supported syscall based random. */
  1070. return -1;
  1071. }
  1072. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1073. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  1074. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  1075. * is imposed.
  1076. */
  1077. static int
  1078. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  1079. {
  1080. #ifdef TOR_UNIT_TESTS
  1081. if (break_strongest_rng_fallback)
  1082. return -1;
  1083. #endif
  1084. #ifdef _WIN32
  1085. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  1086. (void)out;
  1087. (void)out_len;
  1088. return -1;
  1089. #else /* !(defined(_WIN32)) */
  1090. static const char *filenames[] = {
  1091. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1092. };
  1093. int fd, i;
  1094. size_t n;
  1095. for (i = 0; filenames[i]; ++i) {
  1096. log_debug(LD_FS, "Considering %s as entropy source", filenames[i]);
  1097. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  1098. if (fd<0) continue;
  1099. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  1100. n = read_all(fd, (char*)out, out_len, 0);
  1101. close(fd);
  1102. if (n != out_len) {
  1103. /* LCOV_EXCL_START
  1104. * We can't make /dev/foorandom actually fail. */
  1105. log_notice(LD_CRYPTO,
  1106. "Error reading from entropy source %s (read only %lu bytes).",
  1107. filenames[i],
  1108. (unsigned long)n);
  1109. return -1;
  1110. /* LCOV_EXCL_STOP */
  1111. }
  1112. return 0;
  1113. }
  1114. return -1;
  1115. #endif /* defined(_WIN32) */
  1116. }
  1117. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1118. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  1119. * request size of 256 bytes is imposed.
  1120. */
  1121. STATIC int
  1122. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  1123. {
  1124. static const size_t sanity_min_size = 16;
  1125. static const int max_attempts = 3;
  1126. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  1127. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  1128. * zero filling the buffer and ensuring that it actually was at least
  1129. * partially modified.
  1130. *
  1131. * Checking that any individual byte is non-zero seems like it would
  1132. * fail too often (p = out_len * 1/256) for comfort, but this is an
  1133. * "adjust according to taste" sort of check.
  1134. */
  1135. memwipe(out, 0, out_len);
  1136. for (int i = 0; i < max_attempts; i++) {
  1137. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  1138. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  1139. /* Try to use the less-favored mechanism to get strong entropy. */
  1140. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  1141. /* Welp, we tried. Hopefully the calling code terminates the process
  1142. * since we're basically boned without good entropy.
  1143. */
  1144. log_warn(LD_CRYPTO,
  1145. "Cannot get strong entropy: no entropy source found.");
  1146. return -1;
  1147. }
  1148. }
  1149. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  1150. return 0;
  1151. }
  1152. /* LCOV_EXCL_START
  1153. *
  1154. * We tried max_attempts times to fill a buffer >= 128 bits long,
  1155. * and each time it returned all '0's. Either the system entropy
  1156. * source is busted, or the user should go out and buy a ticket to
  1157. * every lottery on the planet.
  1158. */
  1159. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  1160. return -1;
  1161. /* LCOV_EXCL_STOP */
  1162. }
  1163. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1164. * storing it into <b>out</b>.
  1165. */
  1166. void
  1167. crypto_strongest_rand(uint8_t *out, size_t out_len)
  1168. {
  1169. #define DLEN SHA512_DIGEST_LENGTH
  1170. /* We're going to hash DLEN bytes from the system RNG together with some
  1171. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  1172. */
  1173. uint8_t inp[DLEN*2];
  1174. uint8_t tmp[DLEN];
  1175. tor_assert(out);
  1176. while (out_len) {
  1177. crypto_rand((char*) inp, DLEN);
  1178. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  1179. // LCOV_EXCL_START
  1180. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  1181. "important key. Exiting.");
  1182. /* Die with an assertion so we get a stack trace. */
  1183. tor_assert(0);
  1184. // LCOV_EXCL_STOP
  1185. }
  1186. if (out_len >= DLEN) {
  1187. SHA512(inp, sizeof(inp), out);
  1188. out += DLEN;
  1189. out_len -= DLEN;
  1190. } else {
  1191. SHA512(inp, sizeof(inp), tmp);
  1192. memcpy(out, tmp, out_len);
  1193. break;
  1194. }
  1195. }
  1196. memwipe(tmp, 0, sizeof(tmp));
  1197. memwipe(inp, 0, sizeof(inp));
  1198. #undef DLEN
  1199. }
  1200. /** Seed OpenSSL's random number generator with bytes from the operating
  1201. * system. Return 0 on success, -1 on failure.
  1202. */
  1203. int
  1204. crypto_seed_rng(void)
  1205. {
  1206. int rand_poll_ok = 0, load_entropy_ok = 0;
  1207. uint8_t buf[ADD_ENTROPY];
  1208. /* OpenSSL has a RAND_poll function that knows about more kinds of
  1209. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1210. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1211. rand_poll_ok = RAND_poll();
  1212. if (rand_poll_ok == 0)
  1213. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  1214. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  1215. if (load_entropy_ok) {
  1216. RAND_seed(buf, sizeof(buf));
  1217. }
  1218. memwipe(buf, 0, sizeof(buf));
  1219. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  1220. return 0;
  1221. else
  1222. return -1;
  1223. }
  1224. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  1225. * for unit tests.
  1226. *
  1227. * This function is not allowed to fail; if it would fail to generate strong
  1228. * entropy, it must terminate the process instead.
  1229. */
  1230. MOCK_IMPL(void,
  1231. crypto_rand, (char *to, size_t n))
  1232. {
  1233. crypto_rand_unmocked(to, n);
  1234. }
  1235. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  1236. * will want crypto_rand instead.
  1237. *
  1238. * This function is not allowed to fail; if it would fail to generate strong
  1239. * entropy, it must terminate the process instead.
  1240. */
  1241. void
  1242. crypto_rand_unmocked(char *to, size_t n)
  1243. {
  1244. int r;
  1245. if (n == 0)
  1246. return;
  1247. tor_assert(n < INT_MAX);
  1248. tor_assert(to);
  1249. r = RAND_bytes((unsigned char*)to, (int)n);
  1250. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  1251. * stack trace about where it happened.
  1252. */
  1253. tor_assert(r >= 0);
  1254. }
  1255. /** Return a pseudorandom integer, chosen uniformly from the values
  1256. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  1257. * INT_MAX+1, inclusive. */
  1258. int
  1259. crypto_rand_int(unsigned int max)
  1260. {
  1261. unsigned int val;
  1262. unsigned int cutoff;
  1263. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  1264. tor_assert(max > 0); /* don't div by 0 */
  1265. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1266. * distribution with clipping at the upper end of unsigned int's
  1267. * range.
  1268. */
  1269. cutoff = UINT_MAX - (UINT_MAX%max);
  1270. while (1) {
  1271. crypto_rand((char*)&val, sizeof(val));
  1272. if (val < cutoff)
  1273. return val % max;
  1274. }
  1275. }
  1276. /** Return a pseudorandom integer, chosen uniformly from the values i such
  1277. * that min <= i < max.
  1278. *
  1279. * <b>min</b> MUST be in range [0, <b>max</b>).
  1280. * <b>max</b> MUST be in range (min, INT_MAX].
  1281. */
  1282. int
  1283. crypto_rand_int_range(unsigned int min, unsigned int max)
  1284. {
  1285. tor_assert(min < max);
  1286. tor_assert(max <= INT_MAX);
  1287. /* The overflow is avoided here because crypto_rand_int() returns a value
  1288. * between 0 and (max - min) inclusive. */
  1289. return min + crypto_rand_int(max - min);
  1290. }
  1291. /** As crypto_rand_int_range, but supports uint64_t. */
  1292. uint64_t
  1293. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  1294. {
  1295. tor_assert(min < max);
  1296. return min + crypto_rand_uint64(max - min);
  1297. }
  1298. /** As crypto_rand_int_range, but supports time_t. */
  1299. time_t
  1300. crypto_rand_time_range(time_t min, time_t max)
  1301. {
  1302. tor_assert(min < max);
  1303. return min + (time_t)crypto_rand_uint64(max - min);
  1304. }
  1305. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  1306. * between 0 and <b>max</b>-1 inclusive. */
  1307. uint64_t
  1308. crypto_rand_uint64(uint64_t max)
  1309. {
  1310. uint64_t val;
  1311. uint64_t cutoff;
  1312. tor_assert(max < UINT64_MAX);
  1313. tor_assert(max > 0); /* don't div by 0 */
  1314. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1315. * distribution with clipping at the upper end of unsigned int's
  1316. * range.
  1317. */
  1318. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1319. while (1) {
  1320. crypto_rand((char*)&val, sizeof(val));
  1321. if (val < cutoff)
  1322. return val % max;
  1323. }
  1324. }
  1325. /** Return a pseudorandom double d, chosen uniformly from the range
  1326. * 0.0 <= d < 1.0.
  1327. */
  1328. double
  1329. crypto_rand_double(void)
  1330. {
  1331. /* We just use an unsigned int here; we don't really care about getting
  1332. * more than 32 bits of resolution */
  1333. unsigned int u;
  1334. crypto_rand((char*)&u, sizeof(u));
  1335. #if SIZEOF_INT == 4
  1336. #define UINT_MAX_AS_DOUBLE 4294967296.0
  1337. #elif SIZEOF_INT == 8
  1338. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  1339. #else
  1340. #error SIZEOF_INT is neither 4 nor 8
  1341. #endif /* SIZEOF_INT == 4 || ... */
  1342. return ((double)u) / UINT_MAX_AS_DOUBLE;
  1343. }
  1344. /** Generate and return a new random hostname starting with <b>prefix</b>,
  1345. * ending with <b>suffix</b>, and containing no fewer than
  1346. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  1347. * characters. Does not check for failure.
  1348. *
  1349. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  1350. **/
  1351. char *
  1352. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  1353. const char *suffix)
  1354. {
  1355. char *result, *rand_bytes;
  1356. int randlen, rand_bytes_len;
  1357. size_t resultlen, prefixlen;
  1358. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  1359. max_rand_len = MAX_DNS_LABEL_SIZE;
  1360. if (min_rand_len > max_rand_len)
  1361. min_rand_len = max_rand_len;
  1362. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  1363. prefixlen = strlen(prefix);
  1364. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  1365. rand_bytes_len = ((randlen*5)+7)/8;
  1366. if (rand_bytes_len % 5)
  1367. rand_bytes_len += 5 - (rand_bytes_len%5);
  1368. rand_bytes = tor_malloc(rand_bytes_len);
  1369. crypto_rand(rand_bytes, rand_bytes_len);
  1370. result = tor_malloc(resultlen);
  1371. memcpy(result, prefix, prefixlen);
  1372. base32_encode(result+prefixlen, resultlen-prefixlen,
  1373. rand_bytes, rand_bytes_len);
  1374. tor_free(rand_bytes);
  1375. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  1376. return result;
  1377. }
  1378. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  1379. * is empty. */
  1380. void *
  1381. smartlist_choose(const smartlist_t *sl)
  1382. {
  1383. int len = smartlist_len(sl);
  1384. if (len)
  1385. return smartlist_get(sl,crypto_rand_int(len));
  1386. return NULL; /* no elements to choose from */
  1387. }
  1388. /** Scramble the elements of <b>sl</b> into a random order. */
  1389. void
  1390. smartlist_shuffle(smartlist_t *sl)
  1391. {
  1392. int i;
  1393. /* From the end of the list to the front, choose at random from the
  1394. positions we haven't looked at yet, and swap that position into the
  1395. current position. Remember to give "no swap" the same probability as
  1396. any other swap. */
  1397. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1398. int j = crypto_rand_int(i+1);
  1399. smartlist_swap(sl, i, j);
  1400. }
  1401. }
  1402. /**
  1403. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  1404. * the value <b>byte</b>.
  1405. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  1406. *
  1407. * This function is preferable to memset, since many compilers will happily
  1408. * optimize out memset() when they can convince themselves that the data being
  1409. * cleared will never be read.
  1410. *
  1411. * Right now, our convention is to use this function when we are wiping data
  1412. * that's about to become inaccessible, such as stack buffers that are about
  1413. * to go out of scope or structures that are about to get freed. (In
  1414. * practice, it appears that the compilers we're currently using will optimize
  1415. * out the memset()s for stack-allocated buffers, but not those for
  1416. * about-to-be-freed structures. That could change, though, so we're being
  1417. * wary.) If there are live reads for the data, then you can just use
  1418. * memset().
  1419. */
  1420. void
  1421. memwipe(void *mem, uint8_t byte, size_t sz)
  1422. {
  1423. if (sz == 0) {
  1424. return;
  1425. }
  1426. /* If sz is nonzero, then mem must not be NULL. */
  1427. tor_assert(mem != NULL);
  1428. /* Data this large is likely to be an underflow. */
  1429. tor_assert(sz < SIZE_T_CEILING);
  1430. /* Because whole-program-optimization exists, we may not be able to just
  1431. * have this function call "memset". A smart compiler could inline it, then
  1432. * eliminate dead memsets, and declare itself to be clever. */
  1433. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  1434. /* Here's what you do on windows. */
  1435. SecureZeroMemory(mem,sz);
  1436. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  1437. RtlSecureZeroMemory(mem,sz);
  1438. #elif defined(HAVE_EXPLICIT_BZERO)
  1439. /* The BSDs provide this. */
  1440. explicit_bzero(mem, sz);
  1441. #elif defined(HAVE_MEMSET_S)
  1442. /* This is in the C99 standard. */
  1443. memset_s(mem, sz, 0, sz);
  1444. #else
  1445. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  1446. * based on the pointer value, then uses that junk to update a global
  1447. * variable. It's an elaborate ruse to trick the compiler into not
  1448. * optimizing out the "wipe this memory" code. Read it if you like zany
  1449. * programming tricks! In later versions of Tor, we should look for better
  1450. * not-optimized-out memory wiping stuff...
  1451. *
  1452. * ...or maybe not. In practice, there are pure-asm implementations of
  1453. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  1454. **/
  1455. OPENSSL_cleanse(mem, sz);
  1456. #endif /* defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY) || ... */
  1457. /* Just in case some caller of memwipe() is relying on getting a buffer
  1458. * filled with a particular value, fill the buffer.
  1459. *
  1460. * If this function gets inlined, this memset might get eliminated, but
  1461. * that's okay: We only care about this particular memset in the case where
  1462. * the caller should have been using memset(), and the memset() wouldn't get
  1463. * eliminated. In other words, this is here so that we won't break anything
  1464. * if somebody accidentally calls memwipe() instead of memset().
  1465. **/
  1466. memset(mem, byte, sz);
  1467. }
  1468. /** @{ */
  1469. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  1470. * failure.
  1471. */
  1472. int
  1473. crypto_global_cleanup(void)
  1474. {
  1475. EVP_cleanup();
  1476. #ifndef NEW_THREAD_API
  1477. ERR_remove_thread_state(NULL);
  1478. #endif
  1479. ERR_free_strings();
  1480. if (dh_param_p)
  1481. BN_clear_free(dh_param_p);
  1482. if (dh_param_p_tls)
  1483. BN_clear_free(dh_param_p_tls);
  1484. if (dh_param_g)
  1485. BN_clear_free(dh_param_g);
  1486. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  1487. #ifndef DISABLE_ENGINES
  1488. ENGINE_cleanup();
  1489. #endif
  1490. CONF_modules_unload(1);
  1491. CRYPTO_cleanup_all_ex_data();
  1492. crypto_openssl_free_all();
  1493. crypto_early_initialized_ = 0;
  1494. crypto_global_initialized_ = 0;
  1495. have_seeded_siphash = 0;
  1496. siphash_unset_global_key();
  1497. return 0;
  1498. }
  1499. /** @} */
  1500. #ifdef USE_DMALLOC
  1501. /** Tell the crypto library to use Tor's allocation functions rather than
  1502. * calling libc's allocation functions directly. Return 0 on success, -1
  1503. * on failure. */
  1504. int
  1505. crypto_use_tor_alloc_functions(void)
  1506. {
  1507. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1508. return r ? 0 : -1;
  1509. }
  1510. #endif /* defined(USE_DMALLOC) */