Coverage Report

Created: 2025-09-05 10:05

/src/node/src/crypto/crypto_random.cc
Line
Count
Source (jump to first uncovered line)
1
#include "crypto/crypto_random.h"
2
#include "async_wrap-inl.h"
3
#include "crypto/crypto_util.h"
4
#include "env-inl.h"
5
#include "memory_tracker-inl.h"
6
#include "threadpoolwork-inl.h"
7
#include "v8.h"
8
9
#include <openssl/bn.h>
10
#include <openssl/rand.h>
11
12
namespace node {
13
14
using v8::ArrayBuffer;
15
using v8::BackingStore;
16
using v8::Boolean;
17
using v8::FunctionCallbackInfo;
18
using v8::Int32;
19
using v8::Just;
20
using v8::Local;
21
using v8::Maybe;
22
using v8::Nothing;
23
using v8::Object;
24
using v8::Uint32;
25
using v8::Value;
26
27
namespace crypto {
28
Maybe<bool> RandomBytesTraits::EncodeOutput(
29
    Environment* env,
30
    const RandomBytesConfig& params,
31
    ByteSource* unused,
32
18
    v8::Local<v8::Value>* result) {
33
18
  *result = v8::Undefined(env->isolate());
34
18
  return Just(!result->IsEmpty());
35
18
}
36
37
Maybe<bool> RandomBytesTraits::AdditionalConfig(
38
    CryptoJobMode mode,
39
    const FunctionCallbackInfo<Value>& args,
40
    unsigned int offset,
41
18
    RandomBytesConfig* params) {
42
18
  CHECK(IsAnyBufferSource(args[offset]));  // Buffer to fill
43
18
  CHECK(args[offset + 1]->IsUint32());  // Offset
44
18
  CHECK(args[offset + 2]->IsUint32());  // Size
45
46
18
  ArrayBufferOrViewContents<unsigned char> in(args[offset]);
47
48
18
  const uint32_t byte_offset = args[offset + 1].As<Uint32>()->Value();
49
18
  const uint32_t size = args[offset + 2].As<Uint32>()->Value();
50
18
  CHECK_GE(byte_offset + size, byte_offset);  // Overflow check.
51
18
  CHECK_LE(byte_offset + size, in.size());  // Bounds check.
52
53
18
  params->buffer = in.data() + byte_offset;
54
18
  params->size = size;
55
56
18
  return Just(true);
57
18
}
58
59
bool RandomBytesTraits::DeriveBits(
60
    Environment* env,
61
    const RandomBytesConfig& params,
62
18
    ByteSource* unused) {
63
18
  return CSPRNG(params.buffer, params.size).is_ok();
64
18
}
65
66
0
void RandomPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
67
0
  tracker->TrackFieldWithSize("prime", prime ? bits * 8 : 0);
68
0
}
69
70
Maybe<bool> RandomPrimeTraits::EncodeOutput(
71
    Environment* env,
72
    const RandomPrimeConfig& params,
73
    ByteSource* unused,
74
0
    v8::Local<v8::Value>* result) {
75
0
  size_t size = BN_num_bytes(params.prime.get());
76
0
  std::shared_ptr<BackingStore> store =
77
0
      ArrayBuffer::NewBackingStore(env->isolate(), size);
78
0
  CHECK_EQ(static_cast<int>(size),
79
0
           BN_bn2binpad(params.prime.get(),
80
0
                        reinterpret_cast<unsigned char*>(store->Data()),
81
0
                        size));
82
0
  *result = ArrayBuffer::New(env->isolate(), store);
83
0
  return Just(true);
84
0
}
85
86
Maybe<bool> RandomPrimeTraits::AdditionalConfig(
87
    CryptoJobMode mode,
88
    const FunctionCallbackInfo<Value>& args,
89
    unsigned int offset,
90
0
    RandomPrimeConfig* params) {
91
0
  ClearErrorOnReturn clear_error;
92
0
  Environment* env = Environment::GetCurrent(args);
93
0
  CHECK(args[offset]->IsUint32());  // Size
94
0
  CHECK(args[offset + 1]->IsBoolean());  // Safe
95
96
0
  const uint32_t size = args[offset].As<Uint32>()->Value();
97
0
  bool safe = args[offset + 1]->IsTrue();
98
99
0
  if (!args[offset + 2]->IsUndefined()) {
100
0
    ArrayBufferOrViewContents<unsigned char> add(args[offset + 2]);
101
0
    params->add.reset(BN_bin2bn(add.data(), add.size(), nullptr));
102
0
    if (!params->add) {
103
0
      THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
104
0
      return Nothing<bool>();
105
0
    }
106
0
  }
107
108
0
  if (!args[offset + 3]->IsUndefined()) {
109
0
    ArrayBufferOrViewContents<unsigned char> rem(args[offset + 3]);
110
0
    params->rem.reset(BN_bin2bn(rem.data(), rem.size(), nullptr));
111
0
    if (!params->rem) {
112
0
      THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
113
0
      return Nothing<bool>();
114
0
    }
115
0
  }
116
117
  // The JS interface already ensures that the (positive) size fits into an int.
118
0
  int bits = static_cast<int>(size);
119
0
  CHECK_GT(bits, 0);
120
121
0
  if (params->add) {
122
0
    if (BN_num_bits(params->add.get()) > bits) {
123
      // If we allowed this, the best case would be returning a static prime
124
      // that wasn't generated randomly. The worst case would be an infinite
125
      // loop within OpenSSL, blocking the main thread or one of the threads
126
      // in the thread pool.
127
0
      THROW_ERR_OUT_OF_RANGE(env, "invalid options.add");
128
0
      return Nothing<bool>();
129
0
    }
130
131
0
    if (params->rem) {
132
0
      if (BN_cmp(params->add.get(), params->rem.get()) != 1) {
133
        // This would definitely lead to an infinite loop if allowed since
134
        // OpenSSL does not check this condition.
135
0
        THROW_ERR_OUT_OF_RANGE(env, "invalid options.rem");
136
0
        return Nothing<bool>();
137
0
      }
138
0
    }
139
0
  }
140
141
0
  params->bits = bits;
142
0
  params->safe = safe;
143
0
  params->prime.reset(BN_secure_new());
144
0
  if (!params->prime) {
145
0
    THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
146
0
    return Nothing<bool>();
147
0
  }
148
149
0
  return Just(true);
150
0
}
151
152
bool RandomPrimeTraits::DeriveBits(Environment* env,
153
                                   const RandomPrimeConfig& params,
154
0
                                   ByteSource* unused) {
155
  // BN_generate_prime_ex() calls RAND_bytes_ex() internally.
156
  // Make sure the CSPRNG is properly seeded.
157
0
  CHECK(CSPRNG(nullptr, 0).is_ok());
158
159
0
  if (BN_generate_prime_ex(
160
0
          params.prime.get(),
161
0
          params.bits,
162
0
          params.safe ? 1 : 0,
163
0
          params.add.get(),
164
0
          params.rem.get(),
165
0
          nullptr) == 0) {
166
0
    return false;
167
0
  }
168
169
0
  return true;
170
0
}
171
172
0
void CheckPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
173
0
  tracker->TrackFieldWithSize(
174
0
      "prime", candidate ? BN_num_bytes(candidate.get()) : 0);
175
0
}
176
177
Maybe<bool> CheckPrimeTraits::AdditionalConfig(
178
    CryptoJobMode mode,
179
    const FunctionCallbackInfo<Value>& args,
180
    unsigned int offset,
181
0
    CheckPrimeConfig* params) {
182
0
  ArrayBufferOrViewContents<unsigned char> candidate(args[offset]);
183
184
0
  params->candidate =
185
0
      BignumPointer(BN_bin2bn(
186
0
          candidate.data(),
187
0
          candidate.size(),
188
0
          nullptr));
189
190
0
  CHECK(args[offset + 1]->IsInt32());  // Checks
191
0
  params->checks = args[offset + 1].As<Int32>()->Value();
192
0
  CHECK_GE(params->checks, 0);
193
194
0
  return Just(true);
195
0
}
196
197
bool CheckPrimeTraits::DeriveBits(
198
    Environment* env,
199
    const CheckPrimeConfig& params,
200
0
    ByteSource* out) {
201
202
0
  BignumCtxPointer ctx(BN_CTX_new());
203
204
0
  int ret = BN_is_prime_ex(
205
0
            params.candidate.get(),
206
0
            params.checks,
207
0
            ctx.get(),
208
0
            nullptr);
209
0
  if (ret < 0) return false;
210
0
  ByteSource::Builder buf(1);
211
0
  buf.data<char>()[0] = ret;
212
0
  *out = std::move(buf).release();
213
0
  return true;
214
0
}
215
216
Maybe<bool> CheckPrimeTraits::EncodeOutput(
217
    Environment* env,
218
    const CheckPrimeConfig& params,
219
    ByteSource* out,
220
0
    v8::Local<v8::Value>* result) {
221
0
  *result = Boolean::New(env->isolate(), out->data<char>()[0] != 0);
222
0
  return Just(true);
223
0
}
224
225
namespace Random {
226
8.21k
void Initialize(Environment* env, Local<Object> target) {
227
8.21k
  RandomBytesJob::Initialize(env, target);
228
8.21k
  RandomPrimeJob::Initialize(env, target);
229
8.21k
  CheckPrimeJob::Initialize(env, target);
230
8.21k
}
231
232
0
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
233
0
  RandomBytesJob::RegisterExternalReferences(registry);
234
0
  RandomPrimeJob::RegisterExternalReferences(registry);
235
0
  CheckPrimeJob::RegisterExternalReferences(registry);
236
0
}
237
}  // namespace Random
238
}  // namespace crypto
239
}  // namespace node