Coverage Report

Created: 2025-08-26 07:08

/src/PROJ/curl/lib/rand.c
Line
Count
Source (jump to first uncovered line)
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
25
#include "curl_setup.h"
26
27
#include <limits.h>
28
29
#ifdef HAVE_FCNTL_H
30
#include <fcntl.h>
31
#endif
32
#ifdef HAVE_ARPA_INET_H
33
#include <arpa/inet.h>
34
#endif
35
36
#include <curl/curl.h>
37
#include "urldata.h"
38
#include "vtls/vtls.h"
39
#include "sendf.h"
40
#include "curlx/timeval.h"
41
#include "rand.h"
42
#include "escape.h"
43
44
/* The last 3 #include files should be in this order */
45
#include "curl_printf.h"
46
#include "curl_memory.h"
47
#include "memdebug.h"
48
49
#ifdef _WIN32
50
51
#if defined(_WIN32_WINNT) && _WIN32_WINNT >= _WIN32_WINNT_VISTA && \
52
  !defined(CURL_WINDOWS_UWP)
53
#  define HAVE_WIN_BCRYPTGENRANDOM
54
#  include <bcrypt.h>
55
#  ifdef _MSC_VER
56
#    pragma comment(lib, "bcrypt.lib")
57
#  endif
58
   /* Offered by mingw-w64 v3+. MS SDK v7.0A+. */
59
#  ifndef BCRYPT_USE_SYSTEM_PREFERRED_RNG
60
#  define BCRYPT_USE_SYSTEM_PREFERRED_RNG 0x00000002
61
#  endif
62
#  ifndef STATUS_SUCCESS
63
#  define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
64
#  endif
65
#elif defined(USE_WIN32_CRYPTO)
66
#  include <wincrypt.h>
67
#  ifdef _MSC_VER
68
#    pragma comment(lib, "advapi32.lib")
69
#  endif
70
#endif
71
72
CURLcode Curl_win32_random(unsigned char *entropy, size_t length)
73
{
74
  memset(entropy, 0, length);
75
76
#ifdef HAVE_WIN_BCRYPTGENRANDOM
77
  if(BCryptGenRandom(NULL, entropy, (ULONG)length,
78
                     BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS)
79
    return CURLE_FAILED_INIT;
80
81
  return CURLE_OK;
82
#elif defined(USE_WIN32_CRYPTO)
83
  {
84
    HCRYPTPROV hCryptProv = 0;
85
86
    if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
87
                            CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
88
      return CURLE_FAILED_INIT;
89
90
    if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) {
91
      CryptReleaseContext(hCryptProv, 0UL);
92
      return CURLE_FAILED_INIT;
93
    }
94
95
    CryptReleaseContext(hCryptProv, 0UL);
96
  }
97
  return CURLE_OK;
98
#else
99
  return CURLE_NOT_BUILT_IN;
100
#endif
101
}
102
#endif
103
104
#ifndef USE_SSL
105
/* ---- possibly non-cryptographic version following ---- */
106
static CURLcode weak_random(struct Curl_easy *data,
107
                            unsigned char *entropy,
108
                            size_t length) /* always 4, size of int */
109
{
110
  unsigned int r;
111
  DEBUGASSERT(length == sizeof(int));
112
113
  /* Trying cryptographically secure functions first */
114
#ifdef _WIN32
115
  (void)data;
116
  {
117
    CURLcode result = Curl_win32_random(entropy, length);
118
    if(result != CURLE_NOT_BUILT_IN)
119
      return result;
120
  }
121
#endif
122
123
#ifdef HAVE_ARC4RANDOM
124
  (void)data;
125
  r = (unsigned int)arc4random();
126
  memcpy(entropy, &r, length);
127
#else
128
  infof(data, "WARNING: using weak random seed");
129
  {
130
    static unsigned int randseed;
131
    static bool seeded = FALSE;
132
    unsigned int rnd;
133
    if(!seeded) {
134
      struct curltime now = curlx_now();
135
      randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
136
      randseed = randseed * 1103515245 + 12345;
137
      randseed = randseed * 1103515245 + 12345;
138
      randseed = randseed * 1103515245 + 12345;
139
      seeded = TRUE;
140
    }
141
142
    /* Return an unsigned 32-bit pseudo-random number. */
143
    r = randseed = randseed * 1103515245 + 12345;
144
    rnd = (r << 16) | ((r >> 16) & 0xFFFF);
145
    memcpy(entropy, &rnd, length);
146
  }
147
#endif
148
  return CURLE_OK;
149
}
150
#endif
151
152
#ifdef USE_SSL
153
0
#define _random(x,y,z) Curl_ssl_random(x,y,z)
154
#else
155
#define _random(x,y,z) weak_random(x,y,z)
156
#endif
157
158
static CURLcode randit(struct Curl_easy *data, unsigned int *rnd,
159
                       bool env_override)
160
0
{
161
#ifdef DEBUGBUILD
162
  if(env_override) {
163
    char *force_entropy = getenv("CURL_ENTROPY");
164
    if(force_entropy) {
165
      static unsigned int randseed;
166
      static bool seeded = FALSE;
167
168
      if(!seeded) {
169
        unsigned int seed = 0;
170
        size_t elen = strlen(force_entropy);
171
        size_t clen = sizeof(seed);
172
        size_t min = elen < clen ? elen : clen;
173
        memcpy((char *)&seed, force_entropy, min);
174
        randseed = ntohl(seed);
175
        seeded = TRUE;
176
      }
177
      else
178
        randseed++;
179
      *rnd = randseed;
180
      return CURLE_OK;
181
    }
182
  }
183
#else
184
0
  (void)env_override;
185
0
#endif
186
187
  /* data may be NULL! */
188
0
  return _random(data, (unsigned char *)rnd, sizeof(*rnd));
189
0
}
190
191
/*
192
 * Curl_rand() stores 'num' number of random unsigned characters in the buffer
193
 * 'rnd' points to.
194
 *
195
 * If libcurl is built without TLS support or arc4random, this function will
196
 * use "weak" random.
197
 *
198
 * When built *with* TLS support, it will return error if it cannot provide
199
 * strong random values.
200
 *
201
 * NOTE: 'data' may be passed in as NULL when coming from external API without
202
 * easy handle!
203
 *
204
 */
205
206
CURLcode Curl_rand_bytes(struct Curl_easy *data,
207
#ifdef DEBUGBUILD
208
                         bool env_override,
209
#endif
210
                         unsigned char *rnd, size_t num)
211
0
{
212
0
  CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
213
0
#ifndef DEBUGBUILD
214
0
  const bool env_override = FALSE;
215
0
#endif
216
217
0
  DEBUGASSERT(num);
218
219
0
  while(num) {
220
0
    unsigned int r;
221
0
    size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int);
222
223
0
    result = randit(data, &r, env_override);
224
0
    if(result)
225
0
      return result;
226
227
0
    while(left) {
228
0
      *rnd++ = (unsigned char)(r & 0xFF);
229
0
      r >>= 8;
230
0
      --num;
231
0
      --left;
232
0
    }
233
0
  }
234
235
0
  return result;
236
0
}
237
238
/*
239
 * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random
240
 * hexadecimal digits PLUS a null-terminating byte. It must be an odd number
241
 * size.
242
 */
243
244
CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd,
245
                       size_t num)
246
0
{
247
0
  CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
248
0
  unsigned char buffer[128];
249
0
  DEBUGASSERT(num > 1);
250
251
#ifdef __clang_analyzer__
252
  /* This silences a scan-build warning about accessing this buffer with
253
     uninitialized memory. */
254
  memset(buffer, 0, sizeof(buffer));
255
#endif
256
257
0
  if((num/2 >= sizeof(buffer)) || !(num&1)) {
258
    /* make sure it fits in the local buffer and that it is an odd number! */
259
0
    DEBUGF(infof(data, "invalid buffer size with Curl_rand_hex"));
260
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
261
0
  }
262
263
0
  num--; /* save one for null-termination */
264
265
0
  result = Curl_rand(data, buffer, num/2);
266
0
  if(result)
267
0
    return result;
268
269
0
  Curl_hexencode(buffer, num/2, rnd, num + 1);
270
0
  return result;
271
0
}
272
273
/*
274
 * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random
275
 * alphanumerical chars PLUS a null-terminating byte.
276
 */
277
278
static const char alnum[] =
279
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
280
281
CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd,
282
                         size_t num)
283
0
{
284
0
  CURLcode result = CURLE_OK;
285
0
  const unsigned int alnumspace = sizeof(alnum) - 1;
286
0
  unsigned int r;
287
0
  DEBUGASSERT(num > 1);
288
289
0
  num--; /* save one for null-termination */
290
291
0
  while(num) {
292
0
    do {
293
0
      result = randit(data, &r, TRUE);
294
0
      if(result)
295
0
        return result;
296
0
    } while(r >= (UINT_MAX - UINT_MAX % alnumspace));
297
298
0
    *rnd++ = (unsigned char)alnum[r % alnumspace];
299
0
    num--;
300
0
  }
301
0
  *rnd = 0;
302
303
0
  return result;
304
0
}