Coverage Report

Created: 2026-01-25 06:18

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