Coverage Report

Created: 2025-10-10 06:31

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