crypto.c 49 KB

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