GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_random.cc Lines: 101 117 86.3 %
Date: 2022-10-31 03:21:21 Branches: 50 88 56.8 %

Line Branch Exec Source
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::False;
17
using v8::FunctionCallbackInfo;
18
using v8::Just;
19
using v8::Local;
20
using v8::Maybe;
21
using v8::Nothing;
22
using v8::Object;
23
using v8::True;
24
using v8::Uint32;
25
using v8::Value;
26
27
namespace crypto {
28
437
Maybe<bool> RandomBytesTraits::EncodeOutput(
29
    Environment* env,
30
    const RandomBytesConfig& params,
31
    ByteSource* unused,
32
    v8::Local<v8::Value>* result) {
33
874
  *result = v8::Undefined(env->isolate());
34
437
  return Just(!result->IsEmpty());
35
}
36
37
437
Maybe<bool> RandomBytesTraits::AdditionalConfig(
38
    CryptoJobMode mode,
39
    const FunctionCallbackInfo<Value>& args,
40
    unsigned int offset,
41
    RandomBytesConfig* params) {
42
437
  Environment* env = Environment::GetCurrent(args);
43

874
  CHECK(IsAnyByteSource(args[offset]));  // Buffer to fill
44

874
  CHECK(args[offset + 1]->IsUint32());  // Offset
45

874
  CHECK(args[offset + 2]->IsUint32());  // Size
46
47
874
  ArrayBufferOrViewContents<unsigned char> in(args[offset]);
48
49
1311
  const uint32_t byte_offset = args[offset + 1].As<Uint32>()->Value();
50
1311
  const uint32_t size = args[offset + 2].As<Uint32>()->Value();
51
437
  CHECK_GE(byte_offset + size, byte_offset);  // Overflow check.
52
437
  CHECK_LE(byte_offset + size, in.size());  // Bounds check.
53
54
437
  if (UNLIKELY(size > INT_MAX)) {
55
    THROW_ERR_OUT_OF_RANGE(env, "buffer is too large");
56
    return Nothing<bool>();
57
  }
58
59
437
  params->buffer = in.data() + byte_offset;
60
437
  params->size = size;
61
62
437
  return Just(true);
63
}
64
65
437
bool RandomBytesTraits::DeriveBits(
66
    Environment* env,
67
    const RandomBytesConfig& params,
68
    ByteSource* unused) {
69
437
  return CSPRNG(params.buffer, params.size).is_ok();
70
}
71
72
void RandomPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
73
  tracker->TrackFieldWithSize("prime", prime ? bits * 8 : 0);
74
}
75
76
15
Maybe<bool> RandomPrimeTraits::EncodeOutput(
77
    Environment* env,
78
    const RandomPrimeConfig& params,
79
    ByteSource* unused,
80
    v8::Local<v8::Value>* result) {
81
15
  size_t size = BN_num_bytes(params.prime.get());
82
  std::shared_ptr<BackingStore> store =
83
15
      ArrayBuffer::NewBackingStore(env->isolate(), size);
84
15
  BN_bn2binpad(
85
15
      params.prime.get(),
86
15
      reinterpret_cast<unsigned char*>(store->Data()),
87
      size);
88
30
  *result = ArrayBuffer::New(env->isolate(), store);
89
15
  return Just(true);
90
}
91
92
21
Maybe<bool> RandomPrimeTraits::AdditionalConfig(
93
    CryptoJobMode mode,
94
    const FunctionCallbackInfo<Value>& args,
95
    unsigned int offset,
96
    RandomPrimeConfig* params) {
97
21
  ClearErrorOnReturn clear_error;
98
21
  Environment* env = Environment::GetCurrent(args);
99

42
  CHECK(args[offset]->IsUint32());  // Size
100

42
  CHECK(args[offset + 1]->IsBoolean());  // Safe
101
102
63
  const uint32_t size = args[offset].As<Uint32>()->Value();
103
42
  bool safe = args[offset + 1]->IsTrue();
104
105

63
  if (!args[offset + 2]->IsUndefined()) {
106
24
    ArrayBufferOrViewContents<unsigned char> add(args[offset + 2]);
107
12
    params->add.reset(BN_bin2bn(add.data(), add.size(), nullptr));
108
12
    if (!params->add) {
109
      THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
110
      return Nothing<bool>();
111
    }
112
  }
113
114

63
  if (!args[offset + 3]->IsUndefined()) {
115
16
    ArrayBufferOrViewContents<unsigned char> rem(args[offset + 3]);
116
8
    params->rem.reset(BN_bin2bn(rem.data(), rem.size(), nullptr));
117
8
    if (!params->rem) {
118
      THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
119
      return Nothing<bool>();
120
    }
121
  }
122
123
  // The JS interface already ensures that the (positive) size fits into an int.
124
21
  int bits = static_cast<int>(size);
125
21
  CHECK_GT(bits, 0);
126
127
21
  if (params->add) {
128
12
    if (BN_num_bits(params->add.get()) > bits) {
129
      // If we allowed this, the best case would be returning a static prime
130
      // that wasn't generated randomly. The worst case would be an infinite
131
      // loop within OpenSSL, blocking the main thread or one of the threads
132
      // in the thread pool.
133
3
      THROW_ERR_OUT_OF_RANGE(env, "invalid options.add");
134
3
      return Nothing<bool>();
135
    }
136
137
9
    if (params->rem) {
138
7
      if (BN_cmp(params->add.get(), params->rem.get()) != 1) {
139
        // This would definitely lead to an infinite loop if allowed since
140
        // OpenSSL does not check this condition.
141
3
        THROW_ERR_OUT_OF_RANGE(env, "invalid options.rem");
142
3
        return Nothing<bool>();
143
      }
144
    }
145
  }
146
147
15
  params->bits = bits;
148
15
  params->safe = safe;
149
15
  params->prime.reset(BN_secure_new());
150
15
  if (!params->prime) {
151
    THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
152
    return Nothing<bool>();
153
  }
154
155
15
  return Just(true);
156
}
157
158
15
bool RandomPrimeTraits::DeriveBits(Environment* env,
159
                                   const RandomPrimeConfig& params,
160
                                   ByteSource* unused) {
161
  // BN_generate_prime_ex() calls RAND_bytes_ex() internally.
162
  // Make sure the CSPRNG is properly seeded.
163
15
  CHECK(CSPRNG(nullptr, 0).is_ok());
164
165
30
  if (BN_generate_prime_ex(
166
          params.prime.get(),
167
15
          params.bits,
168
15
          params.safe ? 1 : 0,
169
15
          params.add.get(),
170
15
          params.rem.get(),
171
15
          nullptr) == 0) {
172
    return false;
173
  }
174
175
15
  return true;
176
}
177
178
void CheckPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
179
  tracker->TrackFieldWithSize(
180
      "prime", candidate ? BN_num_bytes(candidate.get()) : 0);
181
}
182
183
24
Maybe<bool> CheckPrimeTraits::AdditionalConfig(
184
    CryptoJobMode mode,
185
    const FunctionCallbackInfo<Value>& args,
186
    unsigned int offset,
187
    CheckPrimeConfig* params) {
188
24
  Environment* env = Environment::GetCurrent(args);
189
190
48
  ArrayBufferOrViewContents<unsigned char> candidate(args[offset]);
191
192
  params->candidate =
193
48
      BignumPointer(BN_bin2bn(
194
24
          candidate.data(),
195
24
          candidate.size(),
196
24
          nullptr));
197
198

48
  CHECK(args[offset + 1]->IsUint32());  // Checks
199
200
72
  const int checks = static_cast<int>(args[offset + 1].As<Uint32>()->Value());
201
24
  if (checks < 0) {
202
    THROW_ERR_OUT_OF_RANGE(env, "invalid options.checks");
203
    return Nothing<bool>();
204
  }
205
206
24
  params->checks = checks;
207
208
24
  return Just(true);
209
}
210
211
24
bool CheckPrimeTraits::DeriveBits(
212
    Environment* env,
213
    const CheckPrimeConfig& params,
214
    ByteSource* out) {
215
216
48
  BignumCtxPointer ctx(BN_CTX_new());
217
218
48
  int ret = BN_is_prime_ex(
219
24
            params.candidate.get(),
220
24
            params.checks,
221
            ctx.get(),
222
            nullptr);
223
24
  if (ret < 0) return false;
224
24
  ByteSource::Builder buf(1);
225
24
  buf.data<char>()[0] = ret;
226
24
  *out = std::move(buf).release();
227
24
  return true;
228
}
229
230
24
Maybe<bool> CheckPrimeTraits::EncodeOutput(
231
    Environment* env,
232
    const CheckPrimeConfig& params,
233
    ByteSource* out,
234
    v8::Local<v8::Value>* result) {
235
24
  *result = out->data<char>()[0] ? True(env->isolate()) : False(env->isolate());
236
24
  return Just(true);
237
}
238
239
namespace Random {
240
785
void Initialize(Environment* env, Local<Object> target) {
241
785
  RandomBytesJob::Initialize(env, target);
242
785
  RandomPrimeJob::Initialize(env, target);
243
785
  CheckPrimeJob::Initialize(env, target);
244
785
}
245
246
5581
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
247
5581
  RandomBytesJob::RegisterExternalReferences(registry);
248
5581
  RandomPrimeJob::RegisterExternalReferences(registry);
249
5581
  CheckPrimeJob::RegisterExternalReferences(registry);
250
5581
}
251
}  // namespace Random
252
}  // namespace crypto
253
}  // namespace node