GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keygen.h Lines: 74 91 81.3 %
Date: 2022-08-21 04:19:51 Branches: 28 39 71.8 %

Line Branch Exec Source
1
#ifndef SRC_CRYPTO_CRYPTO_KEYGEN_H_
2
#define SRC_CRYPTO_CRYPTO_KEYGEN_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
#include "async_wrap.h"
7
#include "base_object.h"
8
#include "crypto/crypto_keys.h"
9
#include "crypto/crypto_util.h"
10
#include "env.h"
11
#include "memory_tracker.h"
12
#include "v8.h"
13
14
namespace node {
15
namespace crypto {
16
namespace Keygen {
17
void Initialize(Environment* env, v8::Local<v8::Object> target);
18
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
19
}  // namespace Keygen
20
21
enum class KeyGenJobStatus {
22
  OK,
23
  FAILED
24
};
25
26
// A Base CryptoJob for generating secret keys or key pairs.
27
// The KeyGenTraits is largely responsible for the details of
28
// the implementation, while KeyGenJob handles the common
29
// mechanisms.
30
template <typename KeyGenTraits>
31
class KeyGenJob final : public CryptoJob<KeyGenTraits> {
32
 public:
33
  using AdditionalParams = typename KeyGenTraits::AdditionalParameters;
34
35
3299
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
36
3299
    Environment* env = Environment::GetCurrent(args);
37
3299
    CHECK(args.IsConstructCall());
38
39
3299
    CryptoJobMode mode = GetCryptoJobMode(args[0]);
40
41
3299
    unsigned int offset = 1;
42
43
3299
    AdditionalParams params;
44
6598
    if (KeyGenTraits::AdditionalConfig(mode, args, &offset, &params)
45
            .IsNothing()) {
46
      // The KeyGenTraits::AdditionalConfig is responsible for
47
      // calling an appropriate THROW_CRYPTO_* variant reporting
48
      // whatever error caused initialization to fail.
49
      return;
50
    }
51
52
3299
    new KeyGenJob<KeyGenTraits>(env, args.This(), mode, std::move(params));
53
  }
54
55
6200
  static void Initialize(
56
      Environment* env,
57
      v8::Local<v8::Object> target) {
58
6200
    CryptoJob<KeyGenTraits>::Initialize(New, env, target);
59
6200
  }
60
61
42856
  static void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
62
42856
    CryptoJob<KeyGenTraits>::RegisterExternalReferences(New, registry);
63
42856
  }
64
65
3299
  KeyGenJob(
66
      Environment* env,
67
      v8::Local<v8::Object> object,
68
      CryptoJobMode mode,
69
      AdditionalParams&& params)
70
      : CryptoJob<KeyGenTraits>(
71
            env,
72
            object,
73
            KeyGenTraits::Provider,
74
            mode,
75
3299
            std::move(params)) {}
76
77
3294
  void DoThreadPoolWork() override {
78
    // Make sure the CSPRNG is properly seeded so the results are secure.
79
3294
    CheckEntropy();
80
81
3294
    AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
82
83
3294
    switch (KeyGenTraits::DoKeyGen(AsyncWrap::env(), params)) {
84
3200
      case KeyGenJobStatus::OK:
85
3200
        status_ = KeyGenJobStatus::OK;
86
        // Success!
87
3200
        break;
88
94
      case KeyGenJobStatus::FAILED: {
89
94
        CryptoErrorStore* errors = CryptoJob<KeyGenTraits>::errors();
90
94
        errors->Capture();
91
94
        if (errors->Empty())
92
          errors->Insert(NodeCryptoError::KEY_GENERATION_JOB_FAILED);
93
      }
94
    }
95
3294
  }
96
97
3293
  v8::Maybe<bool> ToResult(
98
      v8::Local<v8::Value>* err,
99
      v8::Local<v8::Value>* result) override {
100
3293
    Environment* env = AsyncWrap::env();
101
3293
    CryptoErrorStore* errors = CryptoJob<KeyGenTraits>::errors();
102
3293
    AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
103
104
3293
    if (status_ == KeyGenJobStatus::OK) {
105
3199
      v8::Maybe<bool> ret = KeyGenTraits::EncodeKey(env, params, result);
106

6393
      if (ret.IsJust() && ret.FromJust()) {
107
6388
        *err = Undefined(env->isolate());
108
      }
109
3199
      return ret;
110
    }
111
112
94
    if (errors->Empty())
113
      errors->Capture();
114
94
    CHECK(!errors->Empty());
115
188
    *result = Undefined(env->isolate());
116
188
    return v8::Just(errors->ToException(env).ToLocal(err));
117
  }
118
119
  SET_SELF_SIZE(KeyGenJob)
120
121
 private:
122
  KeyGenJobStatus status_ = KeyGenJobStatus::FAILED;
123
};
124
125
// A Base KeyGenTraits for Key Pair generation algorithms.
126
template <typename KeyPairAlgorithmTraits>
127
struct KeyPairGenTraits final {
128
  using AdditionalParameters =
129
      typename KeyPairAlgorithmTraits::AdditionalParameters;
130
131
  static const AsyncWrap::ProviderType Provider =
132
      AsyncWrap::PROVIDER_KEYPAIRGENREQUEST;
133
  static constexpr const char* JobName = KeyPairAlgorithmTraits::JobName;
134
135
779
  static v8::Maybe<bool> AdditionalConfig(
136
      CryptoJobMode mode,
137
      const v8::FunctionCallbackInfo<v8::Value>& args,
138
      unsigned int* offset,
139
      AdditionalParameters* params) {
140
    // Notice that offset is a pointer. Each of the AdditionalConfig,
141
    // GetPublicKeyEncodingFromJs, and GetPrivateKeyEncodingFromJs
142
    // functions will update the value of the offset as they successfully
143
    // process input parameters. This allows each job to have a variable
144
    // number of input parameters specific to each job type.
145
1558
    if (KeyPairAlgorithmTraits::AdditionalConfig(mode, args, offset, params)
146
            .IsNothing()) {
147
4
      return v8::Just(false);
148
    }
149
150
775
    params->public_key_encoding = ManagedEVPPKey::GetPublicKeyEncodingFromJs(
151
        args,
152
        offset,
153
        kKeyContextGenerate);
154
155
775
    auto private_key_encoding =
156
        ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
157
            args,
158
            offset,
159
            kKeyContextGenerate);
160
161
775
    if (!private_key_encoding.IsEmpty())
162
774
      params->private_key_encoding = private_key_encoding.Release();
163
164
775
    return v8::Just(true);
165
  }
166
167
774
  static KeyGenJobStatus DoKeyGen(
168
      Environment* env,
169
      AdditionalParameters* params) {
170
1548
    EVPKeyCtxPointer ctx = KeyPairAlgorithmTraits::Setup(params);
171
172
774
    if (!ctx)
173
      return KeyGenJobStatus::FAILED;
174
175
    // Generate the key
176
774
    EVP_PKEY* pkey = nullptr;
177
774
    if (!EVP_PKEY_keygen(ctx.get(), &pkey))
178
94
      return KeyGenJobStatus::FAILED;
179
180
680
    params->key = ManagedEVPPKey(EVPKeyPointer(pkey));
181
680
    return KeyGenJobStatus::OK;
182
  }
183
184
679
  static v8::Maybe<bool> EncodeKey(
185
      Environment* env,
186
      AdditionalParameters* params,
187
      v8::Local<v8::Value>* result) {
188
2037
    v8::Local<v8::Value> keys[2];
189
679
    if (params->key
190
679
            .ToEncodedPublicKey(env, params->public_key_encoding, &keys[0])
191

2032
            .IsNothing() ||
192
        params->key
193
674
            .ToEncodedPrivateKey(env, params->private_key_encoding, &keys[1])
194
1353
            .IsNothing()) {
195
5
      return v8::Nothing<bool>();
196
    }
197
674
    *result = v8::Array::New(env->isolate(), keys, arraysize(keys));
198
674
    return v8::Just(true);
199
  }
200
};
201
202
struct SecretKeyGenConfig final : public MemoryRetainer {
203
  size_t length;  // Expressed a a number of bits
204
  char* out = nullptr;  // Placeholder for the generated key bytes
205
206
  void MemoryInfo(MemoryTracker* tracker) const override;
207
  SET_MEMORY_INFO_NAME(SecretKeyGenConfig)
208
  SET_SELF_SIZE(SecretKeyGenConfig)
209
};
210
211
struct SecretKeyGenTraits final {
212
  using AdditionalParameters = SecretKeyGenConfig;
213
  static const AsyncWrap::ProviderType Provider =
214
      AsyncWrap::PROVIDER_KEYGENREQUEST;
215
  static constexpr const char* JobName = "SecretKeyGenJob";
216
217
  static v8::Maybe<bool> AdditionalConfig(
218
      CryptoJobMode mode,
219
      const v8::FunctionCallbackInfo<v8::Value>& args,
220
      unsigned int* offset,
221
      SecretKeyGenConfig* params);
222
223
  static KeyGenJobStatus DoKeyGen(
224
      Environment* env,
225
      SecretKeyGenConfig* params);
226
227
  static v8::Maybe<bool> EncodeKey(
228
      Environment* env,
229
      SecretKeyGenConfig* params,
230
      v8::Local<v8::Value>* result);
231
};
232
233
template <typename AlgorithmParams>
234
struct KeyPairGenConfig final : public MemoryRetainer {
235
  PublicKeyEncodingConfig public_key_encoding;
236
  PrivateKeyEncodingConfig private_key_encoding;
237
  ManagedEVPPKey key;
238
  AlgorithmParams params;
239
240
779
  KeyPairGenConfig() = default;
241
3114
  ~KeyPairGenConfig() {
242
3114
    Mutex::ScopedLock priv_lock(*key.mutex());
243
  }
244
245
779
  explicit KeyPairGenConfig(KeyPairGenConfig&& other) noexcept
246
      : public_key_encoding(other.public_key_encoding),
247
        private_key_encoding(
248
            std::forward<PrivateKeyEncodingConfig>(
249
779
                other.private_key_encoding)),
250
779
        key(std::move(other.key)),
251
779
        params(std::move(other.params)) {}
252
253
  KeyPairGenConfig& operator=(KeyPairGenConfig&& other) noexcept {
254
    if (&other == this) return *this;
255
    this->~KeyPairGenConfig();
256
    return *new (this) KeyPairGenConfig(std::move(other));
257
  }
258
259
  void MemoryInfo(MemoryTracker* tracker) const override {
260
    tracker->TrackField("key", key);
261
    if (!private_key_encoding.passphrase_.IsEmpty()) {
262
      tracker->TrackFieldWithSize("private_key_encoding.passphrase",
263
                                  private_key_encoding.passphrase_->size());
264
    }
265
    tracker->TrackField("params", params);
266
  }
267
268
  SET_MEMORY_INFO_NAME(KeyPairGenConfig)
269
  SET_SELF_SIZE(KeyPairGenConfig)
270
};
271
272
struct NidKeyPairParams final : public MemoryRetainer {
273
  int id;
274
  SET_NO_MEMORY_INFO()
275
  SET_MEMORY_INFO_NAME(NidKeyPairParams)
276
  SET_SELF_SIZE(NidKeyPairParams)
277
};
278
279
using NidKeyPairGenConfig = KeyPairGenConfig<NidKeyPairParams>;
280
281
struct NidKeyPairGenTraits final {
282
  using AdditionalParameters = NidKeyPairGenConfig;
283
  static constexpr const char* JobName = "NidKeyPairGenJob";
284
285
  static EVPKeyCtxPointer Setup(NidKeyPairGenConfig* params);
286
287
  static v8::Maybe<bool> AdditionalConfig(
288
      CryptoJobMode mode,
289
      const v8::FunctionCallbackInfo<v8::Value>& args,
290
      unsigned int* offset,
291
      NidKeyPairGenConfig* params);
292
};
293
294
using NidKeyPairGenJob = KeyGenJob<KeyPairGenTraits<NidKeyPairGenTraits>>;
295
using SecretKeyGenJob = KeyGenJob<SecretKeyGenTraits>;
296
}  // namespace crypto
297
}  // namespace node
298
299
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
300
#endif  // SRC_CRYPTO_CRYPTO_KEYGEN_H_
301