Coverage Report

Created: 2026-01-17 06:25

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