Repository navigation
Expand file tree
/
Copy pathcrypto_random.cc
More file actions
285 lines (245 loc) Β· 9.38 KB
/
Copy pathcrypto_random.cc
File metadata and controls
285 lines (245 loc) Β· 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#include "crypto/crypto_random.h"
#include "async_wrap-inl.h"
#include "crypto/crypto_util.h"
#include "env-inl.h"
#include "memory_tracker-inl.h"
#include "ncrypto.h"
#include "threadpoolwork-inl.h"
#include "v8.h"
#include <compare>
namespace node {
using ncrypto::BignumPointer;
using ncrypto::ClearErrorOnReturn;
using ncrypto::DataPointer;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::Boolean;
using v8::FunctionCallbackInfo;
using v8::Int32;
using v8::JustVoid;
using v8::Local;
using v8::Maybe;
using v8::MaybeLocal;
using v8::Nothing;
using v8::Object;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
namespace crypto {
namespace {
bool IsImmutableBufferSource(Local<Value> buffer) {
if (buffer->IsArrayBufferView()) {
return buffer.As<ArrayBufferView>()->Buffer()->IsImmutable();
}
return buffer->IsArrayBuffer() && buffer.As<ArrayBuffer>()->IsImmutable();
}
BignumPointer::PrimeCheckCallback getPrimeCheckCallback(Environment* env) {
// The callback is used to check if the operation should be stopped.
// Currently, the only check we perform is if env->is_stopping()
// is true.
return [env](int a, int b) -> bool { return !env->is_stopping(); };
}
} // namespace
MaybeLocal<Value> RandomBytesTraits::EncodeOutput(
Environment* env, const RandomBytesConfig& params, ByteSource* unused) {
return Undefined(env->isolate());
}
Maybe<void> RandomBytesTraits::AdditionalConfig(
CryptoJobMode mode,
const FunctionCallbackInfo<Value>& args,
unsigned int offset,
RandomBytesConfig* params) {
CHECK(IsAnyBufferSource(args[offset])); // Buffer to fill
CHECK(args[offset + 1]->IsUint32()); // Offset
CHECK(args[offset + 2]->IsUint32()); // Size
if (IsImmutableBufferSource(args[offset])) {
THROW_ERR_INVALID_ARG_VALUE(
Environment::GetCurrent(args),
"The 'buf' argument must not be backed by an immutable ArrayBuffer");
return Nothing<void>();
}
ArrayBufferOrViewContents<unsigned char> in(args[offset]);
const uint32_t byte_offset = args[offset + 1].As<Uint32>()->Value();
const uint32_t size = args[offset + 2].As<Uint32>()->Value();
CHECK_GE(byte_offset + size, byte_offset); // Overflow check.
CHECK_LE(byte_offset + size, in.size()); // Bounds check.
params->buffer = in.data() + byte_offset;
params->size = size;
return JustVoid();
}
bool RandomBytesTraits::DeriveBits(Environment* env,
const RandomBytesConfig& params,
ByteSource* unused,
CryptoJobMode mode,
CryptoErrorStore* errors) {
return ncrypto::CSPRNG(params.buffer, params.size);
}
void RandomPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackFieldWithSize("prime", prime ? bits * 8 : 0);
}
MaybeLocal<Value> RandomPrimeTraits::EncodeOutput(
Environment* env, const RandomPrimeConfig& params, ByteSource* unused) {
size_t size = params.prime.byteLength();
auto store = ArrayBuffer::NewBackingStore(env->isolate(), size);
CHECK_EQ(size,
BignumPointer::EncodePaddedInto(
params.prime.get(),
reinterpret_cast<unsigned char*>(store->Data()),
size));
return ArrayBuffer::New(env->isolate(), std::move(store));
}
Maybe<void> RandomPrimeTraits::AdditionalConfig(
CryptoJobMode mode,
const FunctionCallbackInfo<Value>& args,
unsigned int offset,
RandomPrimeConfig* params) {
ClearErrorOnReturn clear_error;
Environment* env = Environment::GetCurrent(args);
CHECK(args[offset]->IsUint32()); // Size
CHECK(args[offset + 1]->IsBoolean()); // Safe
const uint32_t size = args[offset].As<Uint32>()->Value();
bool safe = args[offset + 1]->IsTrue();
if (!args[offset + 2]->IsUndefined()) {
ArrayBufferOrViewContents<unsigned char> add(args[offset + 2]);
params->add.reset(add.data(), add.size());
if (!params->add) [[unlikely]] {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
return Nothing<void>();
}
}
if (!args[offset + 3]->IsUndefined()) {
ArrayBufferOrViewContents<unsigned char> rem(args[offset + 3]);
params->rem.reset(rem.data(), rem.size());
if (!params->rem) [[unlikely]] {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
return Nothing<void>();
}
}
// The JS interface already ensures that the (positive) size fits into an int.
int bits = static_cast<int>(size);
CHECK_GT(bits, 0);
if (params->add) {
if (BignumPointer::GetBitCount(params->add.get()) > bits) [[unlikely]] {
// If we allowed this, the best case would be returning a static prime
// that wasn't generated randomly. The worst case would be an infinite
// loop within OpenSSL, blocking the main thread or one of the threads
// in the thread pool.
THROW_ERR_OUT_OF_RANGE(env, "invalid options.add");
return Nothing<void>();
}
if (params->rem && params->add <= params->rem) [[unlikely]] {
// This would definitely lead to an infinite loop if allowed since
// OpenSSL does not check this condition.
THROW_ERR_OUT_OF_RANGE(env, "invalid options.rem");
return Nothing<void>();
}
}
params->bits = bits;
params->safe = safe;
params->prime = BignumPointer::NewSecure();
if (!params->prime) [[unlikely]] {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
return Nothing<void>();
}
return JustVoid();
}
bool RandomPrimeTraits::DeriveBits(Environment* env,
const RandomPrimeConfig& params,
ByteSource* unused,
CryptoJobMode mode,
CryptoErrorStore* errors) {
return params.prime.generate(
BignumPointer::PrimeConfig{
.bits = params.bits,
.safe = params.safe,
.add = params.add,
.rem = params.rem,
},
getPrimeCheckCallback(env));
}
void CheckPrimeConfig::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackFieldWithSize("prime", candidate ? candidate.byteLength() : 0);
}
Maybe<void> CheckPrimeTraits::AdditionalConfig(
CryptoJobMode mode,
const FunctionCallbackInfo<Value>& args,
unsigned int offset,
CheckPrimeConfig* params) {
ArrayBufferOrViewContents<unsigned char> candidate(args[offset]);
params->candidate = BignumPointer(candidate.data(), candidate.size());
if (!params->candidate) {
ThrowCryptoError(
Environment::GetCurrent(args), ERR_get_error(), "BignumPointer");
return Nothing<void>();
}
CHECK(args[offset + 1]->IsInt32()); // Checks
params->checks = args[offset + 1].As<Int32>()->Value();
CHECK_GE(params->checks, 0);
return JustVoid();
}
bool CheckPrimeTraits::DeriveBits(Environment* env,
const CheckPrimeConfig& params,
ByteSource* out,
CryptoJobMode mode,
CryptoErrorStore* errors) {
int ret = params.candidate.isPrime(params.checks, getPrimeCheckCallback(env));
if (ret < 0) [[unlikely]]
return false;
auto buf = DataPointer::Alloc(1);
static_cast<char*>(buf.get())[0] = ret;
*out = ByteSource::Allocated(buf.release());
return true;
}
MaybeLocal<Value> CheckPrimeTraits::EncodeOutput(Environment* env,
const CheckPrimeConfig& params,
ByteSource* out) {
return Boolean::New(env->isolate(), out->data<char>()[0] != 0);
}
namespace Random {
static void RandomFillSync(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(IsAnyBufferSource(args[0])); // Buffer to fill
CHECK(args[1]->IsUint32()); // Offset
CHECK(args[2]->IsUint32()); // Size
if (IsImmutableBufferSource(args[0])) {
return THROW_ERR_INVALID_ARG_VALUE(
env,
"The 'buf' argument must not be backed by an immutable ArrayBuffer");
}
ArrayBufferOrViewContents<unsigned char> in(args[0]);
const uint32_t byte_offset = args[1].As<Uint32>()->Value();
const uint32_t size = args[2].As<Uint32>()->Value();
CHECK_GE(byte_offset + size, byte_offset); // Overflow check.
CHECK_LE(byte_offset + size, in.size()); // Bounds check.
env->PrintSyncTrace();
if (ERR_peek_error() != 0) ERR_clear_error();
if (ncrypto::CSPRNG(in.data() + byte_offset, size)) {
if (ERR_peek_error() != 0) ERR_clear_error();
return;
}
CryptoErrorStore errors;
errors.Capture();
if (errors.Empty()) {
errors.Insert(NodeCryptoError::DERIVING_BITS_FAILED);
errors.SetNodeErrorCode("ERR_CRYPTO_OPERATION_FAILED");
}
Local<Value> exception;
if (errors.ToException(env).ToLocal(&exception)) {
env->isolate()->ThrowException(exception);
}
}
void Initialize(Environment* env, Local<Object> target) {
SetMethod(env->context(), target, "randomFillSync", RandomFillSync);
RandomBytesJob::Initialize(env, target);
RandomPrimeJob::Initialize(env, target);
CheckPrimeJob::Initialize(env, target);
}
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(RandomFillSync);
RandomBytesJob::RegisterExternalReferences(registry);
RandomPrimeJob::RegisterExternalReferences(registry);
CheckPrimeJob::RegisterExternalReferences(registry);
}
} // namespace Random
} // namespace crypto
} // namespace node