rand.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include <limits.h>
  26. #ifdef HAVE_FCNTL_H
  27. #include <fcntl.h>
  28. #endif
  29. #ifdef HAVE_ARPA_INET_H
  30. #include <arpa/inet.h>
  31. #endif
  32. #ifdef HAVE_ARC4RANDOM
  33. /* Some platforms might have the prototype missing (ubuntu + libressl) */
  34. uint32_t arc4random(void);
  35. #endif
  36. #include <curl/curl.h>
  37. #include "urldata.h"
  38. #include "vtls/vtls.h"
  39. #include "sendf.h"
  40. #include "timeval.h"
  41. #include "rand.h"
  42. /* The last 3 #include files should be in this order */
  43. #include "curl_printf.h"
  44. #include "curl_memory.h"
  45. #include "memdebug.h"
  46. #ifdef WIN32
  47. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600
  48. # define HAVE_WIN_BCRYPTGENRANDOM
  49. # include <bcrypt.h>
  50. # ifdef _MSC_VER
  51. # pragma comment(lib, "bcrypt.lib")
  52. # endif
  53. # ifndef BCRYPT_USE_SYSTEM_PREFERRED_RNG
  54. # define BCRYPT_USE_SYSTEM_PREFERRED_RNG 0x00000002
  55. # endif
  56. # ifndef STATUS_SUCCESS
  57. # define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
  58. # endif
  59. #elif defined(USE_WIN32_CRYPTO)
  60. # include <wincrypt.h>
  61. # ifdef _MSC_VER
  62. # pragma comment(lib, "advapi32.lib")
  63. # endif
  64. #endif
  65. CURLcode Curl_win32_random(unsigned char *entropy, size_t length)
  66. {
  67. memset(entropy, 0, length);
  68. #if defined(HAVE_WIN_BCRYPTGENRANDOM)
  69. if(BCryptGenRandom(NULL, entropy, (ULONG)length,
  70. BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS)
  71. return CURLE_FAILED_INIT;
  72. return CURLE_OK;
  73. #elif defined(USE_WIN32_CRYPTO)
  74. {
  75. HCRYPTPROV hCryptProv = 0;
  76. if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
  77. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  78. return CURLE_FAILED_INIT;
  79. if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) {
  80. CryptReleaseContext(hCryptProv, 0UL);
  81. return CURLE_FAILED_INIT;
  82. }
  83. CryptReleaseContext(hCryptProv, 0UL);
  84. }
  85. return CURLE_OK;
  86. #else
  87. return CURLE_NOT_BUILT_IN;
  88. #endif
  89. }
  90. #endif
  91. static CURLcode randit(struct Curl_easy *data, unsigned int *rnd)
  92. {
  93. unsigned int r;
  94. CURLcode result = CURLE_OK;
  95. static unsigned int randseed;
  96. static bool seeded = FALSE;
  97. #ifdef CURLDEBUG
  98. char *force_entropy = getenv("CURL_ENTROPY");
  99. if(force_entropy) {
  100. if(!seeded) {
  101. unsigned int seed = 0;
  102. size_t elen = strlen(force_entropy);
  103. size_t clen = sizeof(seed);
  104. size_t min = elen < clen ? elen : clen;
  105. memcpy((char *)&seed, force_entropy, min);
  106. randseed = ntohl(seed);
  107. seeded = TRUE;
  108. }
  109. else
  110. randseed++;
  111. *rnd = randseed;
  112. return CURLE_OK;
  113. }
  114. #endif
  115. /* data may be NULL! */
  116. result = Curl_ssl_random(data, (unsigned char *)rnd, sizeof(*rnd));
  117. if(result != CURLE_NOT_BUILT_IN)
  118. /* only if there is no random function in the TLS backend do the non crypto
  119. version, otherwise return result */
  120. return result;
  121. /* ---- non-cryptographic version following ---- */
  122. #ifdef WIN32
  123. if(!seeded) {
  124. result = Curl_win32_random((unsigned char *)rnd, sizeof(*rnd));
  125. if(result != CURLE_NOT_BUILT_IN)
  126. return result;
  127. }
  128. #endif
  129. #ifdef HAVE_ARC4RANDOM
  130. *rnd = (unsigned int)arc4random();
  131. return CURLE_OK;
  132. #endif
  133. #if defined(RANDOM_FILE) && !defined(WIN32)
  134. if(!seeded) {
  135. /* if there's a random file to read a seed from, use it */
  136. int fd = open(RANDOM_FILE, O_RDONLY);
  137. if(fd > -1) {
  138. /* read random data into the randseed variable */
  139. ssize_t nread = read(fd, &randseed, sizeof(randseed));
  140. if(nread == sizeof(randseed))
  141. seeded = TRUE;
  142. close(fd);
  143. }
  144. }
  145. #endif
  146. if(!seeded) {
  147. struct curltime now = Curl_now();
  148. infof(data, "WARNING: using weak random seed");
  149. randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
  150. randseed = randseed * 1103515245 + 12345;
  151. randseed = randseed * 1103515245 + 12345;
  152. randseed = randseed * 1103515245 + 12345;
  153. seeded = TRUE;
  154. }
  155. /* Return an unsigned 32-bit pseudo-random number. */
  156. r = randseed = randseed * 1103515245 + 12345;
  157. *rnd = (r << 16) | ((r >> 16) & 0xFFFF);
  158. return CURLE_OK;
  159. }
  160. /*
  161. * Curl_rand() stores 'num' number of random unsigned characters in the buffer
  162. * 'rnd' points to.
  163. *
  164. * If libcurl is built without TLS support or with a TLS backend that lacks a
  165. * proper random API (rustls or mbedTLS), this function will use "weak"
  166. * random.
  167. *
  168. * When built *with* TLS support and a backend that offers strong random, it
  169. * will return error if it cannot provide strong random values.
  170. *
  171. * NOTE: 'data' may be passed in as NULL when coming from external API without
  172. * easy handle!
  173. *
  174. */
  175. CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num)
  176. {
  177. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  178. DEBUGASSERT(num > 0);
  179. while(num) {
  180. unsigned int r;
  181. size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int);
  182. result = randit(data, &r);
  183. if(result)
  184. return result;
  185. while(left) {
  186. *rnd++ = (unsigned char)(r & 0xFF);
  187. r >>= 8;
  188. --num;
  189. --left;
  190. }
  191. }
  192. return result;
  193. }
  194. /*
  195. * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random
  196. * hexadecimal digits PLUS a null-terminating byte. It must be an odd number
  197. * size.
  198. */
  199. CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd,
  200. size_t num)
  201. {
  202. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  203. const char *hex = "0123456789abcdef";
  204. unsigned char buffer[128];
  205. unsigned char *bufp = buffer;
  206. DEBUGASSERT(num > 1);
  207. #ifdef __clang_analyzer__
  208. /* This silences a scan-build warning about accessing this buffer with
  209. uninitialized memory. */
  210. memset(buffer, 0, sizeof(buffer));
  211. #endif
  212. if((num/2 >= sizeof(buffer)) || !(num&1))
  213. /* make sure it fits in the local buffer and that it is an odd number! */
  214. return CURLE_BAD_FUNCTION_ARGUMENT;
  215. num--; /* save one for null-termination */
  216. result = Curl_rand(data, buffer, num/2);
  217. if(result)
  218. return result;
  219. while(num) {
  220. /* clang-tidy warns on this line without this comment: */
  221. /* NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult) */
  222. *rnd++ = hex[(*bufp & 0xF0)>>4];
  223. *rnd++ = hex[*bufp & 0x0F];
  224. bufp++;
  225. num -= 2;
  226. }
  227. *rnd = 0;
  228. return result;
  229. }
  230. /*
  231. * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random
  232. * alphanumerical chars PLUS a null-terminating byte.
  233. */
  234. static const char alnum[] =
  235. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  236. CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd,
  237. size_t num)
  238. {
  239. CURLcode result = CURLE_OK;
  240. const int alnumspace = sizeof(alnum) - 1;
  241. unsigned int r;
  242. DEBUGASSERT(num > 1);
  243. num--; /* save one for null-termination */
  244. while(num) {
  245. do {
  246. result = randit(data, &r);
  247. if(result)
  248. return result;
  249. } while(r >= (UINT_MAX - UINT_MAX % alnumspace));
  250. *rnd++ = alnum[r % alnumspace];
  251. num--;
  252. }
  253. *rnd = 0;
  254. return result;
  255. }