rand.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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_UWP)
  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. #if !defined(USE_SSL)
  90. /* ---- possibly non-cryptographic version following ---- */
  91. static CURLcode weak_random(struct Curl_easy *data,
  92. unsigned char *entropy,
  93. size_t length) /* always 4, size of int */
  94. {
  95. unsigned int r;
  96. DEBUGASSERT(length == sizeof(int));
  97. /* Trying cryptographically secure functions first */
  98. #ifdef _WIN32
  99. (void)data;
  100. {
  101. CURLcode result = Curl_win32_random(entropy, length);
  102. if(result != CURLE_NOT_BUILT_IN)
  103. return result;
  104. }
  105. #endif
  106. #if defined(HAVE_ARC4RANDOM)
  107. (void)data;
  108. r = (unsigned int)arc4random();
  109. memcpy(entropy, &r, length);
  110. #else
  111. infof(data, "WARNING: using weak random seed");
  112. {
  113. static unsigned int randseed;
  114. static bool seeded = FALSE;
  115. unsigned int rnd;
  116. if(!seeded) {
  117. struct curltime now = Curl_now();
  118. randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
  119. randseed = randseed * 1103515245 + 12345;
  120. randseed = randseed * 1103515245 + 12345;
  121. randseed = randseed * 1103515245 + 12345;
  122. seeded = TRUE;
  123. }
  124. /* Return an unsigned 32-bit pseudo-random number. */
  125. r = randseed = randseed * 1103515245 + 12345;
  126. rnd = (r << 16) | ((r >> 16) & 0xFFFF);
  127. memcpy(entropy, &rnd, length);
  128. }
  129. #endif
  130. return CURLE_OK;
  131. }
  132. #endif
  133. #ifdef USE_SSL
  134. #define _random(x,y,z) Curl_ssl_random(x,y,z)
  135. #else
  136. #define _random(x,y,z) weak_random(x,y,z)
  137. #endif
  138. static CURLcode randit(struct Curl_easy *data, unsigned int *rnd,
  139. bool env_override)
  140. {
  141. #ifdef DEBUGBUILD
  142. if(env_override) {
  143. char *force_entropy = getenv("CURL_ENTROPY");
  144. if(force_entropy) {
  145. static unsigned int randseed;
  146. static bool seeded = FALSE;
  147. if(!seeded) {
  148. unsigned int seed = 0;
  149. size_t elen = strlen(force_entropy);
  150. size_t clen = sizeof(seed);
  151. size_t min = elen < clen ? elen : clen;
  152. memcpy((char *)&seed, force_entropy, min);
  153. randseed = ntohl(seed);
  154. seeded = TRUE;
  155. }
  156. else
  157. randseed++;
  158. *rnd = randseed;
  159. return CURLE_OK;
  160. }
  161. }
  162. #else
  163. (void)env_override;
  164. #endif
  165. /* data may be NULL! */
  166. return _random(data, (unsigned char *)rnd, sizeof(*rnd));
  167. }
  168. /*
  169. * Curl_rand() stores 'num' number of random unsigned characters in the buffer
  170. * 'rnd' points to.
  171. *
  172. * If libcurl is built without TLS support or with a TLS backend that lacks a
  173. * proper random API (Rustls or mbedTLS), this function will use "weak"
  174. * random.
  175. *
  176. * When built *with* TLS support and a backend that offers strong random, it
  177. * will return error if it cannot provide strong random values.
  178. *
  179. * NOTE: 'data' may be passed in as NULL when coming from external API without
  180. * easy handle!
  181. *
  182. */
  183. CURLcode Curl_rand_bytes(struct Curl_easy *data,
  184. #ifdef DEBUGBUILD
  185. bool env_override,
  186. #endif
  187. unsigned char *rnd, size_t num)
  188. {
  189. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  190. #ifndef DEBUGBUILD
  191. const bool env_override = FALSE;
  192. #endif
  193. DEBUGASSERT(num);
  194. while(num) {
  195. unsigned int r;
  196. size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int);
  197. result = randit(data, &r, env_override);
  198. if(result)
  199. return result;
  200. while(left) {
  201. *rnd++ = (unsigned char)(r & 0xFF);
  202. r >>= 8;
  203. --num;
  204. --left;
  205. }
  206. }
  207. return result;
  208. }
  209. /*
  210. * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random
  211. * hexadecimal digits PLUS a null-terminating byte. It must be an odd number
  212. * size.
  213. */
  214. CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd,
  215. size_t num)
  216. {
  217. CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
  218. unsigned char buffer[128];
  219. DEBUGASSERT(num > 1);
  220. #ifdef __clang_analyzer__
  221. /* This silences a scan-build warning about accessing this buffer with
  222. uninitialized memory. */
  223. memset(buffer, 0, sizeof(buffer));
  224. #endif
  225. if((num/2 >= sizeof(buffer)) || !(num&1)) {
  226. /* make sure it fits in the local buffer and that it is an odd number! */
  227. DEBUGF(infof(data, "invalid buffer size with Curl_rand_hex"));
  228. return CURLE_BAD_FUNCTION_ARGUMENT;
  229. }
  230. num--; /* save one for null-termination */
  231. result = Curl_rand(data, buffer, num/2);
  232. if(result)
  233. return result;
  234. Curl_hexencode(buffer, num/2, rnd, num + 1);
  235. return result;
  236. }
  237. /*
  238. * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random
  239. * alphanumerical chars PLUS a null-terminating byte.
  240. */
  241. static const char alnum[] =
  242. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  243. CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd,
  244. size_t num)
  245. {
  246. CURLcode result = CURLE_OK;
  247. const unsigned int alnumspace = sizeof(alnum) - 1;
  248. unsigned int r;
  249. DEBUGASSERT(num > 1);
  250. num--; /* save one for null-termination */
  251. while(num) {
  252. do {
  253. result = randit(data, &r, TRUE);
  254. if(result)
  255. return result;
  256. } while(r >= (UINT_MAX - UINT_MAX % alnumspace));
  257. *rnd++ = (unsigned char)alnum[r % alnumspace];
  258. num--;
  259. }
  260. *rnd = 0;
  261. return result;
  262. }