lighttpd 1.4.x https://www.lighttpd.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

500 lines
16 KiB

  1. /*
  2. * rand - generate random bytes
  3. *
  4. * Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com All rights reserved
  5. * License: BSD 3-clause (same as lighttpd)
  6. */
  7. #include "first.h"
  8. #include "rand.h"
  9. #include "buffer.h"
  10. #include "fdevent.h"
  11. #include "safe_memclear.h"
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <errno.h>
  15. #include <fcntl.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <time.h>
  19. #include <unistd.h>
  20. #include "sys-crypto-md.h" /* USE_LIB_CRYPTO and additional crypto lib config */
  21. #ifdef USE_NETTLE_CRYPTO
  22. #undef USE_MBEDTLS_CRYPTO
  23. #undef USE_WOLFSSL_CRYPTO
  24. #undef USE_OPENSSL_CRYPTO
  25. #undef USE_GNUTLS_CRYPTO
  26. #undef USE_NSS_CRYPTO
  27. #include <nettle/knuth-lfib.h>
  28. #include <nettle/arcfour.h>
  29. #include <nettle/yarrow.h>
  30. #endif
  31. #ifdef USE_MBEDTLS_CRYPTO
  32. #undef USE_WOLFSSL_CRYPTO
  33. #undef USE_OPENSSL_CRYPTO
  34. #undef USE_GNUTLS_CRYPTO
  35. #undef USE_NSS_CRYPTO
  36. #include <mbedtls/ctr_drbg.h>
  37. #include <mbedtls/entropy.h>
  38. #endif
  39. #ifdef USE_WOLFSSL_CRYPTO
  40. #undef USE_OPENSSL_CRYPTO
  41. #undef USE_GNUTLS_CRYPTO
  42. #undef USE_NSS_CRYPTO
  43. #include <wolfssl/wolfcrypt/random.h>
  44. #endif
  45. #ifdef USE_OPENSSL_CRYPTO
  46. #undef USE_GNUTLS_CRYPTO
  47. #undef USE_NSS_CRYPTO
  48. #include <openssl/opensslv.h> /* OPENSSL_VERSION_NUMBER */
  49. #include <openssl/rand.h>
  50. #endif
  51. #ifdef USE_GNUTLS_CRYPTO
  52. #undef USE_NSS_CRYPTO
  53. #include <gnutls/crypto.h>
  54. #endif
  55. #ifdef USE_NSS_CRYPTO
  56. #ifdef NSS_VER_INCLUDE
  57. #include <nss3/nss.h>
  58. #include <nss3/pk11pub.h>
  59. #else
  60. #include <nss/nss.h>
  61. #include <nss/pk11pub.h>
  62. #endif
  63. #endif
  64. #ifndef USE_LIB_CRYPTO
  65. #undef USE_NETTLE_CRYPTO
  66. #undef USE_MBEDTLS_CRYPTO
  67. #undef USE_WOLFSSL_CRYPTO
  68. #undef USE_OPENSSL_CRYPTO
  69. #undef USE_GNUTLS_CRYPTO
  70. #undef USE_NSS_CRYPTO
  71. #endif
  72. #ifdef HAVE_GETENTROPY
  73. #include <sys/random.h>
  74. #endif
  75. #ifdef HAVE_LINUX_RANDOM_H
  76. #include <sys/syscall.h>
  77. #include <linux/random.h>
  78. #endif
  79. #ifdef RNDGETENTCNT
  80. #include <sys/ioctl.h>
  81. #endif
  82. /* Take some reasonable steps to attempt to *seed* random number generators with
  83. * cryptographically random data. Some of these initialization routines may
  84. * block, and are intended to be called only at startup in lighttpd, or
  85. * immediately after fork() to start lighttpd workers.
  86. *
  87. * Update: li_rand_init() is now deferred until first use so that installations
  88. * that do not use modules which use these routines do need to potentially block
  89. * at startup. Current use by core lighttpd modules is in mod_auth HTTP Digest
  90. * auth and in mod_usertrack. Deferring collection of random data until first
  91. * use may allow sufficient entropy to be collected by kernel before first use,
  92. * helping reduce or avoid situations in low-entropy-generating embedded devices
  93. * which might otherwise block lighttpd for minutes at device startup.
  94. * Further discussion in https://redmine.lighttpd.net/boards/2/topics/6981
  95. *
  96. * Note: results from li_rand_pseudo_bytes() are not necessarily
  97. * cryptographically random and must not be used for purposes such
  98. * as key generation which require cryptographic randomness.
  99. *
  100. * https://wiki.openssl.org/index.php/Random_Numbers
  101. * https://wiki.openssl.org/index.php/Random_fork-safety
  102. *
  103. * openssl random number generators are not thread-safe by default
  104. * https://wiki.openssl.org/index.php/Manual:Threads(3)
  105. *
  106. * RFE: add more paranoid checks from the following to improve confidence:
  107. * http://insanecoding.blogspot.co.uk/2014/05/a-good-idea-with-bad-usage-devurandom.html
  108. * RFE: retry on EINTR
  109. * RFE: check RAND_status()
  110. */
  111. static int li_getentropy (void *buf, size_t buflen)
  112. {
  113. #ifdef HAVE_GETENTROPY
  114. return getentropy(buf, buflen);
  115. #else
  116. /*(see NOTES section in 'man getrandom' on Linux)*/
  117. #if defined(HAVE_GETRANDOM) || defined(SYS_getrandom)
  118. if (buflen <= 256) {
  119. #ifdef HAVE_GETRANDOM /*(not implemented in glibc yet)*/
  120. int num = getrandom(buf, buflen, 0);
  121. #elif defined(SYS_getrandom)
  122. /* https://lwn.net/Articles/605828/ */
  123. /* https://bbs.archlinux.org/viewtopic.php?id=200039 */
  124. int num = (int)syscall(SYS_getrandom, buf, buflen, 0);
  125. #endif
  126. if (num == (int)buflen) return 0;
  127. if (num < 0) return num; /* -1 */
  128. }
  129. #else
  130. UNUSED(buf);
  131. UNUSED(buflen);
  132. #endif
  133. errno = EIO;
  134. return -1;
  135. #endif
  136. }
  137. static int li_rand_device_bytes (unsigned char *buf, int num)
  138. {
  139. /* randomness from these devices is cryptographically strong,
  140. * unless /dev/urandom is low on entropy */
  141. static const char * const devices[] = {
  142. #ifdef __OpenBSD__
  143. "/dev/arandom",
  144. #endif
  145. "/dev/urandom",
  146. "/dev/random"
  147. };
  148. /* device files might not be available in chroot environment,
  149. * so prefer syscall, if available */
  150. if (0 == li_getentropy(buf, (size_t)num)) return 1;
  151. for (unsigned int u = 0; u < sizeof(devices)/sizeof(devices[0]); ++u) {
  152. /*(some systems might have symlink to another device; omit O_NOFOLLOW)*/
  153. int fd = fdevent_open_cloexec(devices[u], 1, O_RDONLY, 0);
  154. if (fd >= 0) {
  155. ssize_t rd = 0;
  156. #ifdef RNDGETENTCNT
  157. int entropy;
  158. if (0 == ioctl(fd, (unsigned long)(RNDGETENTCNT), &entropy)
  159. && entropy >= num*8)
  160. #endif
  161. rd = read(fd, buf, (size_t)num);
  162. close(fd);
  163. if (rd == num) {
  164. return 1;
  165. }
  166. }
  167. }
  168. return 0;
  169. }
  170. static int li_rand_inited;
  171. static unsigned short xsubi[3];
  172. #ifdef USE_MBEDTLS_CRYPTO
  173. #ifdef MBEDTLS_ENTROPY_C
  174. static mbedtls_entropy_context entropy;
  175. #ifdef MBEDTLS_CTR_DRBG_C
  176. static mbedtls_ctr_drbg_context ctr_drbg;
  177. #endif
  178. #endif
  179. #endif
  180. #ifdef USE_WOLFSSL_CRYPTO
  181. static WC_RNG wolf_globalRNG;
  182. #endif
  183. #ifdef USE_NETTLE_CRYPTO
  184. static struct knuth_lfib_ctx knuth_lfib_ctx;
  185. static struct arcfour_ctx arcfour_ctx;
  186. static struct yarrow256_ctx yarrow256_ctx;
  187. #endif
  188. #ifdef USE_NETTLE_CRYPTO
  189. /* adapted from Nettle documentation arcfour_set_key_hashed() in nettle.pdf */
  190. /* A more robust key setup function for ARCFOUR */
  191. static void
  192. li_arcfour_init_random_key_hashed(struct arcfour_ctx *ctx)
  193. {
  194. uint8_t key[ARCFOUR_KEY_SIZE];
  195. const size_t length = sizeof(key);
  196. if (1 != li_rand_device_bytes(key, (int)sizeof(key))) {
  197. log_failed_assert(__FILE__, __LINE__,
  198. "gathering entropy for arcfour seed failed");
  199. }
  200. memset(ctx, 0, sizeof(*ctx));
  201. struct sha256_ctx hash;
  202. uint8_t digest[SHA256_DIGEST_SIZE];
  203. uint8_t buf[0x200];
  204. memset(buf, 0, sizeof(buf));
  205. sha256_init(&hash);
  206. sha256_update(&hash, length, key);
  207. sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);
  208. nettle_arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
  209. nettle_arcfour_crypt(ctx, sizeof(buf), buf, buf);
  210. nettle_arcfour_crypt(ctx, sizeof(buf), buf, buf);
  211. nettle_arcfour_crypt(ctx, sizeof(buf), buf, buf);
  212. }
  213. #endif
  214. __attribute_cold__
  215. static void li_rand_init (void)
  216. {
  217. /* (intended to be called at init and after fork() in order to re-seed PRNG
  218. * so that forked children, grandchildren, etc do not share PRNG seed)
  219. * https://github.com/ramsey/uuid/issues/80
  220. * https://www.agwa.name/blog/post/libressls_prng_is_unsafe_on_linux
  221. * (issue in early version of libressl has since been fixed)
  222. * https://github.com/libressl-portable/portable/commit/32d9eeeecf4e951e1566d5f4a42b36ea37b60f35
  223. */
  224. unsigned int u;
  225. li_rand_inited = 1;
  226. if (1 == li_rand_device_bytes((unsigned char *)xsubi, (int)sizeof(xsubi))) {
  227. u = ((unsigned int)xsubi[0] << 16) | xsubi[1];
  228. }
  229. else {
  230. #ifdef HAVE_ARC4RANDOM_BUF
  231. u = arc4random();
  232. arc4random_buf(xsubi, sizeof(xsubi));
  233. #elif defined(__COVERITY__)
  234. /* Coverity Scan ignores(?) annotation below,
  235. * so hide fallback path from Coverity Scan */
  236. u = (unsigned int)(time(NULL) ^ getpid());
  237. #else
  238. /* NOTE: not cryptographically random !!! */
  239. srand((unsigned int)(time(NULL) ^ getpid()));
  240. for (u = 0; u < sizeof(unsigned short); ++u)
  241. /* coverity[dont_call : FALSE] */
  242. xsubi[u] = (unsigned short)(rand() & 0xFFFF);
  243. u = ((unsigned int)xsubi[0] << 16) | xsubi[1];
  244. #endif
  245. }
  246. srand(u); /*(initialize just in case rand() used elsewhere)*/
  247. #ifdef HAVE_SRANDOM
  248. srandom(u); /*(initialize just in case random() used elsewhere)*/
  249. #endif
  250. #ifdef USE_NETTLE_CRYPTO
  251. nettle_knuth_lfib_init(&knuth_lfib_ctx, u);
  252. nettle_yarrow256_init(&yarrow256_ctx, 0, NULL);
  253. li_arcfour_init_random_key_hashed(&arcfour_ctx);
  254. #endif
  255. #ifdef USE_WOLFSSL_CRYPTO
  256. /* xsubi[] is small, so use wc_InitRng() instead of wc_InitRngNonce()
  257. * to get default behavior of a larger internally-generated nonce */
  258. if (0 != wolfCrypt_Init() || 0 != wc_InitRng(&wolf_globalRNG))
  259. log_failed_assert(__FILE__, __LINE__,
  260. "wolfCrypt_Init or wc_InitRng() failed");
  261. #endif
  262. #ifdef USE_OPENSSL_CRYPTO
  263. RAND_poll();
  264. RAND_seed(xsubi, (int)sizeof(xsubi));
  265. #endif
  266. #ifdef USE_MBEDTLS_CRYPTO
  267. #ifdef MBEDTLS_ENTROPY_C
  268. mbedtls_entropy_init(&entropy);
  269. #ifdef MBEDTLS_CTR_DRBG_C
  270. mbedtls_ctr_drbg_init(&ctr_drbg);
  271. int rc =
  272. mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  273. (unsigned char *)xsubi, sizeof(xsubi));
  274. if (0 != rc) /*(not expecting built-in entropy function to fail)*/
  275. log_failed_assert(__FILE__, __LINE__, "mbedtls_ctr_drbg_seed() failed");
  276. #endif
  277. #endif
  278. #endif
  279. #ifdef USE_NSS_CRYPTO
  280. if (!NSS_IsInitialized() && NSS_NoDB_Init(NULL) < 0)
  281. SEGFAULT();
  282. PK11_RandomUpdate(xsubi, sizeof(xsubi));
  283. #endif
  284. }
  285. void li_rand_reseed (void)
  286. {
  287. #ifdef USE_GNUTLS_CRYPTO
  288. gnutls_rnd_refresh();
  289. return;
  290. #endif
  291. #ifdef USE_WOLFSSL_CRYPTO
  292. if (li_rand_inited) {
  293. #if 0 /*(wc_RNG_DRBG_Reseed() is not part of public API)*/
  294. /*(XXX: might use stack to procure larger seed;
  295. * xsubi[] is short (6 bytes)) */
  296. if (1 == li_rand_device_bytes((unsigned char *)xsubi,
  297. (int)sizeof(xsubi))) {
  298. if (0 != wc_RNG_DRBG_Reseed(&wolf_globalRNG,
  299. (const byte *)xsubi,
  300. (word32)sizeof(xsubi)))
  301. /*(not expecting this to fail)*/
  302. log_failed_assert(__FILE__, __LINE__,
  303. "wc_RNG_DRBG_Reseed() failed");
  304. }
  305. #else
  306. wc_FreeRng(&wolf_globalRNG);
  307. if (0 != wc_InitRng(&wolf_globalRNG))
  308. log_failed_assert(__FILE__, __LINE__, "wc_InitRng() failed");
  309. #endif
  310. return;
  311. }
  312. #endif
  313. #ifdef USE_MBEDTLS_CRYPTO
  314. if (li_rand_inited) {
  315. #ifdef MBEDTLS_ENTROPY_C
  316. #ifdef MBEDTLS_CTR_DRBG_C
  317. mbedtls_ctr_drbg_free(&ctr_drbg);
  318. #endif
  319. mbedtls_entropy_free(&entropy);
  320. #endif
  321. }
  322. #endif
  323. if (li_rand_inited) li_rand_init();
  324. }
  325. int li_rand_pseudo (void)
  326. {
  327. #ifdef USE_GNUTLS_CRYPTO
  328. int i;
  329. if (0 == gnutls_rnd(GNUTLS_RND_NONCE, &i, sizeof(i))) return i;
  330. #endif
  331. if (!li_rand_inited) li_rand_init();
  332. /* randomness *is not* cryptographically strong */
  333. /* (attempt to use better mechanisms to replace the more portable rand()) */
  334. #ifdef USE_OPENSSL_CRYPTO /* (openssl 1.1.0 deprecates RAND_pseudo_bytes()) */
  335. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  336. int i;
  337. if (-1 != RAND_pseudo_bytes((unsigned char *)&i, sizeof(i))) return i;
  338. #endif
  339. #endif
  340. #ifdef USE_WOLFSSL_CRYPTO
  341. /* RAND_pseudo_bytes() in WolfSSL is equivalent to RAND_bytes() */
  342. int i;
  343. if (0 == wc_RNG_GenerateBlock(&wolf_globalRNG,(byte *)&i,(word32)sizeof(i)))
  344. return i;
  345. #endif
  346. #ifdef USE_NETTLE_CRYPTO
  347. int i = (int)nettle_knuth_lfib_get(&knuth_lfib_ctx);
  348. nettle_arcfour_crypt(&arcfour_ctx, sizeof(i), (uint8_t *)&i, (uint8_t *)&i);
  349. if (i) return i; /*(cond to avoid compiler warning for code after return)*/
  350. #endif
  351. #ifdef USE_MBEDTLS_CRYPTO
  352. #ifdef MBEDTLS_CTR_DRBG_C
  353. int i;
  354. if (0 == mbedtls_ctr_drbg_random(&ctr_drbg, (unsigned char *)&i, sizeof(i)))
  355. return i;
  356. #endif
  357. #endif
  358. #ifdef USE_NSS_CRYPTO
  359. int i;
  360. if (SECSuccess == PK11_GenerateRandom((unsigned char *)&i, sizeof(i)))
  361. return i;
  362. #endif
  363. #ifdef HAVE_ARC4RANDOM_BUF
  364. return (int)arc4random();
  365. #elif defined(__COVERITY__)
  366. /* li_rand_pseudo() is not intended for cryptographic use */
  367. /* Coverity Scan ignores(?) annotation below,
  368. * so hide fallback paths from Coverity Scan */
  369. return (int)(time(NULL) ^ getpid());
  370. #elif defined(HAVE_SRANDOM)
  371. /* coverity[dont_call : FALSE] */
  372. return (int)random();
  373. #elif defined(HAVE_JRAND48)
  374. /*(FYI: jrand48() reentrant, but use of file-scoped static xsubi[] is not)*/
  375. /* coverity[dont_call : FALSE] */
  376. return (int)jrand48(xsubi);
  377. #else
  378. /* coverity[dont_call : FALSE] */
  379. return rand();
  380. #endif
  381. }
  382. void li_rand_pseudo_bytes (unsigned char *buf, int num)
  383. {
  384. #ifdef USE_GNUTLS_CRYPTO
  385. if (0 == gnutls_rnd(GNUTLS_RND_NONCE, buf, (size_t)num)) return;
  386. #endif
  387. if (!li_rand_inited) li_rand_init();
  388. #ifdef USE_NSS_CRYPTO
  389. if (SECSuccess == PK11_GenerateRandom(buf, num)) return;
  390. #endif
  391. #ifdef USE_MBEDTLS_CRYPTO
  392. #ifdef MBEDTLS_CTR_DRBG_C
  393. if (0 == mbedtls_ctr_drbg_random(&ctr_drbg, buf, (size_t)num)) return;
  394. #endif
  395. #endif
  396. #ifdef USE_WOLFSSL_CRYPTO
  397. /* RAND_pseudo_bytes() in WolfSSL is equivalent to RAND_bytes() */
  398. if (0 == wc_RNG_GenerateBlock(&wolf_globalRNG, (byte *)buf, (word32)num))
  399. return;
  400. #endif
  401. for (int i = 0; i < num; ++i)
  402. buf[i] = li_rand_pseudo() & 0xFF;
  403. }
  404. int li_rand_bytes (unsigned char *buf, int num)
  405. {
  406. #ifdef USE_GNUTLS_CRYPTO /* should use GNUTLS_RND_KEY for long-term keys */
  407. if (0 == gnutls_rnd(GNUTLS_RND_RANDOM, buf, (size_t)num)) return 1;
  408. #endif
  409. #ifdef USE_NSS_CRYPTO
  410. if (!li_rand_inited) li_rand_init();
  411. if (SECSuccess == PK11_GenerateRandom(buf, num)) return 1;
  412. #endif
  413. #ifdef USE_NETTLE_CRYPTO
  414. #if 0 /* not implemented: periodic nettle_yarrow256_update() and reseed */
  415. if (!nettle_yarrow256_is_seeded(&yarrow256_ctx)) {
  416. uint8_t seed_file[YARROW256_SEED_FILE_SIZE];
  417. if (1 == li_rand_device_bytes((unsigned char *)seed_file,
  418. (int)sizeof(seed_file))) {
  419. nettle_yarrow256_seed(&yarrow256_ctx, sizeof(seed_file), seed_file);
  420. }
  421. }
  422. if (nettle_yarrow256_is_seeded(&yarrow256_ctx)) {
  423. nettle_yarrow256_random(&yarrow256_ctx, (size_t)num, (uint8_t *)buf);
  424. return 1;
  425. }
  426. #endif
  427. #endif
  428. #ifdef USE_OPENSSL_CRYPTO
  429. int rc = RAND_bytes(buf, num);
  430. if (-1 != rc) {
  431. return rc;
  432. }
  433. #endif
  434. #ifdef USE_WOLFSSL_CRYPTO
  435. if (0 == wc_RNG_GenerateBlock(&wolf_globalRNG, (byte *)buf, (word32)num)) {
  436. return 1;
  437. }
  438. #endif
  439. #ifdef USE_MBEDTLS_CRYPTO
  440. #ifdef MBEDTLS_ENTROPY_C
  441. /*(each call <= MBEDTLS_ENTROPY_BLOCK_SIZE; could implement loop here)*/
  442. if (num <= MBEDTLS_ENTROPY_BLOCK_SIZE
  443. && 0 == mbedtls_entropy_func(&entropy, buf, (size_t)num)) {
  444. return 1;
  445. }
  446. #endif
  447. #endif
  448. if (1 == li_rand_device_bytes(buf, num)) {
  449. return 1;
  450. }
  451. else {
  452. /* NOTE: not cryptographically random !!! */
  453. li_rand_pseudo_bytes(buf, num);
  454. /*(openssl RAND_pseudo_bytes rc for non-cryptographically random data)*/
  455. return 0;
  456. }
  457. }
  458. void li_rand_cleanup (void)
  459. {
  460. #ifdef USE_WOLFSSL_CRYPTO
  461. if (li_rand_inited) {
  462. wc_FreeRng(&wolf_globalRNG);
  463. wolfCrypt_Cleanup();
  464. li_rand_inited = 0;
  465. }
  466. #endif
  467. #ifdef USE_OPENSSL_CRYPTO
  468. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  469. RAND_cleanup();
  470. #endif
  471. #endif
  472. #ifdef USE_MBEDTLS_CRYPTO
  473. #ifdef MBEDTLS_ENTROPY_C
  474. #ifdef MBEDTLS_CTR_DRBG_C
  475. mbedtls_ctr_drbg_free(&ctr_drbg);
  476. #endif
  477. mbedtls_entropy_free(&entropy);
  478. #endif
  479. #endif
  480. safe_memclear(xsubi, sizeof(xsubi));
  481. }