Coverage Report

Created: 2025-07-11 06:33

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