rand.c 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. #include <curl/curl.h>
  33. #include "urldata.h"
  34. #include "vtls/vtls.h"
  35. #include "sendf.h"
  36. #include "timeval.h"
  37. #include "rand.h"
  38. #include "escape.h"
  39. /* The last 3 #include files should be in this order */
  40. #include "curl_printf.h"
  41. #include "curl_memory.h"
  42. #include "memdebug.h"
  43. #ifdef _WIN32
  44. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 && \
  45. !defined(CURL_WINDOWS_APP)
  46. # define HAVE_WIN_BCRYPTGENRANDOM
  47. # include <bcrypt.h>
  48. # ifdef _MSC_VER
  49. # pragma comment(lib, "bcrypt.lib")
  50. # endif
  51. # ifndef BCRYPT_USE_SYSTEM_PREFERRED_RNG
  52. # define BCRYPT_USE_SYSTEM_PREFERRED_RNG 0x00000002
  53. # endif
  54. # ifndef STATUS_SUCCESS
  55. # define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
  56. # endif
  57. #elif defined(USE_WIN32_CRYPTO)
  58. # include <wincrypt.h>
  59. # ifdef _MSC_VER
  60. # pragma comment(lib, "advapi32.lib")
  61. # endif
  62. #endif
  63. CURLcode Curl_win32_random(unsigned char *entropy, size_t length)
  64. {
  65. memset(entropy, 0, length);
  66. #if defined(HAVE_WIN_BCRYPTGENRANDOM)
  67. if(BCryptGenRandom(NULL, entropy, (ULONG)length,
  68. BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS)
  69. return CURLE_FAILED_INIT;
  70. return CURLE_OK;
  71. #elif defined(USE_WIN32_CRYPTO)
  72. {
  73. HCRYPTPROV hCryptProv = 0;
  74. if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
  75. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  76. return CURLE_FAILED_INIT;
  77. if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) {
  78. CryptReleaseContext(hCryptProv, 0UL);
  79. return CURLE_FAILED_INIT;
  80. }
  81. CryptReleaseContext(hCryptProv, 0UL);
  82. }
  83. return CURLE_OK;
  84. #else
  85. return CURLE_NOT_BUILT_IN;
  86. #endif
  87. }
  88. #endif
  89. static CURLcode randit(struct Curl_easy *data, unsigned int *rnd)
  90. {
  91. CURLcode result = CURLE_OK;
  92. static unsigned int randseed;
  93. static bool seeded = FALSE;
  94. #ifdef DEBUGBUILD
  95. char *force_entropy = getenv("CURL_ENTROPY");
  96. if(force_entropy) {
  97. if(!seeded) {
  98. unsigned int seed = 0;
  99. size_t elen = strlen(force_entropy);
  100. size_t clen = sizeof(seed);
  101. size_t min = elen < clen ? elen : clen;
  102. memcpy((char *)&seed, force_entropy, min);
  103. randseed = ntohl(seed);
  104. seeded = TRUE;
  105. }
  106. else
  107. randseed++;
  108. *rnd = randseed;
  109. return CURLE_OK;
  110. }
  111. #endif
  112. /* data may be NULL! */
  113. result = Curl_ssl_random(data, (unsigned char *)rnd, sizeof(*rnd));
  114. if(result != CURLE_NOT_BUILT_IN)
  115. /* only if there is no random function in the TLS backend do the non crypto
  116. version, otherwise return result */
  117. return result;
  118. /* ---- non-cryptographic version following ---- */
  119. #ifdef _WIN32
  120. if(!seeded) {
  121. result = Curl_win32_random((unsigned char *)rnd, sizeof(*rnd));
  122. if(result != CURLE_NOT_BUILT_IN)
  123. return result;
  124. }
  125. #endif
  126. #if defined(HAVE_ARC4RANDOM) && !defined(USE_OPENSSL)
  127. if(!seeded) {
  128. *rnd = (unsigned int)arc4random();
  129. return CURLE_OK;
  130. }
  131. #endif
  132. #if defined(RANDOM_FILE) && !defined(_WIN32)
  133. if(!seeded) {
  134. /* if there's a random file to read a seed from, use it */
  135. int fd = open(RANDOM_FILE, O_RDONLY);
  136. if(fd > -1) {
  137. /* read random data into the randseed variable */
  138. ssize_t nread = read(fd, &randseed, sizeof(randseed));
  139. if(nread == sizeof(randseed))
  140. seeded = TRUE;
  141. close(fd);
  142. }
  143. }
  144. #endif
  145. if(!seeded) {
  146. struct curltime now = Curl_now();
  147. infof(data, "WARNING: using weak random seed");
  148. randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
  149. randseed = randseed * 1103515245 + 12345;
  150. randseed = randseed * 1103515245 + 12345;
  151. randseed = randseed * 1103515245 + 12345;
  152. seeded = TRUE;
  153. }
  154. {
  155. unsigned int r;
  156. /* Return an unsigned 32-bit pseudo-random number. */
  157. r = randseed = randseed * 1103515245 + 12345;
  158. *rnd = (r << 16) | ((r >> 16) & 0xFFFF);
  159. }
  160. return CURLE_OK;
  161. }
  162. /*
  163. * Curl_rand() stores 'num' number of random unsigned characters in the buffer
  164. * 'rnd' points to.
  165. *
  166. * If libcurl is built without TLS support or with a TLS backend that lacks a
  167. * proper random API (rustls or mbedTLS), this function will use "weak"
  168. * random.
  169. *
  170. * When built *with* TLS support and a backend that offers strong random, it
  171. * will return error if it cannot provide strong random values.
  172. *
  173. * NOTE: 'data' may be passed in as NULL when coming from external API without
  174. * easy handle!
  175. *
  176. */
  177. CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num)
  178. {
  179. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  180. DEBUGASSERT(num);
  181. while(num) {
  182. unsigned int r;
  183. size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int);
  184. result = randit(data, &r);
  185. if(result)
  186. return result;
  187. while(left) {
  188. *rnd++ = (unsigned char)(r & 0xFF);
  189. r >>= 8;
  190. --num;
  191. --left;
  192. }
  193. }
  194. return result;
  195. }
  196. /*
  197. * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random
  198. * hexadecimal digits PLUS a null-terminating byte. It must be an odd number
  199. * size.
  200. */
  201. CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd,
  202. size_t num)
  203. {
  204. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  205. unsigned char buffer[128];
  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. DEBUGF(infof(data, "invalid buffer size with Curl_rand_hex"));
  215. return CURLE_BAD_FUNCTION_ARGUMENT;
  216. }
  217. num--; /* save one for null-termination */
  218. result = Curl_rand(data, buffer, num/2);
  219. if(result)
  220. return result;
  221. Curl_hexencode(buffer, num/2, rnd, num + 1);
  222. return result;
  223. }
  224. /*
  225. * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random
  226. * alphanumerical chars PLUS a null-terminating byte.
  227. */
  228. static const char alnum[] =
  229. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  230. CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd,
  231. size_t num)
  232. {
  233. CURLcode result = CURLE_OK;
  234. const unsigned int alnumspace = sizeof(alnum) - 1;
  235. unsigned int r;
  236. DEBUGASSERT(num > 1);
  237. num--; /* save one for null-termination */
  238. while(num) {
  239. do {
  240. result = randit(data, &r);
  241. if(result)
  242. return result;
  243. } while(r >= (UINT_MAX - UINT_MAX % alnumspace));
  244. *rnd++ = (unsigned char)alnum[r % alnumspace];
  245. num--;
  246. }
  247. *rnd = 0;
  248. return result;
  249. }