GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/crypto/crypto_keygen.h Lines: 3 85 3.5 %
Date: 2021-02-19 04:08:54 Branches: 0 64 0.0 %

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 "crypto/crypto_keys.h"
7
#include "crypto/crypto_util.h"
8
#include "allocated_buffer.h"
9
#include "async_wrap.h"
10
#include "base_object.h"
11
#include "env.h"
12
#include "memory_tracker.h"
13
#include "v8.h"
14
15
namespace node {
16
namespace crypto {
17
namespace Keygen {
18
void Initialize(Environment* env, v8::Local<v8::Object> target);
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
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
36
    Environment* env = Environment::GetCurrent(args);
37
    CHECK(args.IsConstructCall());
38
39
    CryptoJobMode mode = GetCryptoJobMode(args[0]);
40
41
    unsigned int offset = 1;
42
43
    AdditionalParams params;
44
    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
    new KeyGenJob<KeyGenTraits>(env, args.This(), mode, std::move(params));
53
  }
54
55
12
  static void Initialize(
56
      Environment* env,
57
      v8::Local<v8::Object> target) {
58
12
    CryptoJob<KeyGenTraits>::Initialize(New, env, target);
59
12
  }
60
61
  KeyGenJob(
62
      Environment* env,
63
      v8::Local<v8::Object> object,
64
      CryptoJobMode mode,
65
      AdditionalParams&& params)
66
      : CryptoJob<KeyGenTraits>(
67
            env,
68
            object,
69
            KeyGenTraits::Provider,
70
            mode,
71
            std::move(params)) {}
72
73
  void DoThreadPoolWork() override {
74
    // Make sure the the CSPRNG is properly seeded so the results are secure
75
    CheckEntropy();
76
77
    AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
78
79
    switch (KeyGenTraits::DoKeyGen(AsyncWrap::env(), params)) {
80
      case KeyGenJobStatus::OK:
81
        status_ = KeyGenJobStatus::OK;
82
        // Success!
83
        break;
84
      case KeyGenJobStatus::FAILED: {
85
        CryptoErrorVector* errors = CryptoJob<KeyGenTraits>::errors();
86
        errors->Capture();
87
        if (errors->empty())
88
          errors->push_back(std::string("Key generation job failed"));
89
      }
90
    }
91
  }
92
93
  v8::Maybe<bool> ToResult(
94
      v8::Local<v8::Value>* err,
95
      v8::Local<v8::Value>* result) override {
96
    Environment* env = AsyncWrap::env();
97
    CryptoErrorVector* errors = CryptoJob<KeyGenTraits>::errors();
98
    AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
99
    if (status_ == KeyGenJobStatus::OK &&
100
        LIKELY(!KeyGenTraits::EncodeKey(env, params, result).IsNothing())) {
101
      *err = Undefined(env->isolate());
102
      return v8::Just(true);
103
    }
104
105
    if (errors->empty())
106
      errors->Capture();
107
    CHECK(!errors->empty());
108
    *result = Undefined(env->isolate());
109
    return v8::Just(errors->ToException(env).ToLocal(err));
110
  }
111
112
  SET_SELF_SIZE(KeyGenJob);
113
114
 private:
115
  KeyGenJobStatus status_ = KeyGenJobStatus::FAILED;
116
};
117
118
// A Base KeyGenTraits for Key Pair generation algorithms.
119
template <typename KeyPairAlgorithmTraits>
120
struct KeyPairGenTraits final {
121
  using AdditionalParameters =
122
      typename KeyPairAlgorithmTraits::AdditionalParameters;
123
124
  static const AsyncWrap::ProviderType Provider =
125
      AsyncWrap::PROVIDER_KEYPAIRGENREQUEST;
126
  static constexpr const char* JobName = KeyPairAlgorithmTraits::JobName;
127
128
  static v8::Maybe<bool> AdditionalConfig(
129
      CryptoJobMode mode,
130
      const v8::FunctionCallbackInfo<v8::Value>& args,
131
      unsigned int* offset,
132
      AdditionalParameters* params) {
133
    // Notice that offset is a pointer. Each of the AdditionalConfig,
134
    // GetPublicKeyEncodingFromJs, and GetPrivateKeyEncodingFromJs
135
    // functions will update the value of the offset as they successfully
136
    // process input parameters. This allows each job to have a variable
137
    // number of input parameters specific to each job type.
138
    if (KeyPairAlgorithmTraits::AdditionalConfig(mode, args, offset, params)
139
            .IsNothing()) {
140
      return v8::Just(false);
141
    }
142
143
    params->public_key_encoding = ManagedEVPPKey::GetPublicKeyEncodingFromJs(
144
        args,
145
        offset,
146
        kKeyContextGenerate);
147
148
    auto private_key_encoding =
149
        ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
150
            args,
151
            offset,
152
            kKeyContextGenerate);
153
154
    if (!private_key_encoding.IsEmpty())
155
      params->private_key_encoding = private_key_encoding.Release();
156
157
    return v8::Just(true);
158
  }
159
160
  static KeyGenJobStatus DoKeyGen(
161
      Environment* env,
162
      AdditionalParameters* params) {
163
    EVPKeyCtxPointer ctx = KeyPairAlgorithmTraits::Setup(params);
164
165
    if (!ctx)
166
      return KeyGenJobStatus::FAILED;
167
168
    // Generate the key
169
    EVP_PKEY* pkey = nullptr;
170
    if (!EVP_PKEY_keygen(ctx.get(), &pkey))
171
      return KeyGenJobStatus::FAILED;
172
173
    params->key = ManagedEVPPKey(EVPKeyPointer(pkey));
174
    return KeyGenJobStatus::OK;
175
  }
176
177
  static v8::Maybe<bool> EncodeKey(
178
      Environment* env,
179
      AdditionalParameters* params,
180
      v8::Local<v8::Value>* result) {
181
    v8::Local<v8::Value> keys[2];
182
    if (ManagedEVPPKey::ToEncodedPublicKey(
183
            env,
184
            std::move(params->key),
185
            params->public_key_encoding,
186
            &keys[0]).IsNothing() ||
187
        ManagedEVPPKey::ToEncodedPrivateKey(
188
            env,
189
            std::move(params->key),
190
            params->private_key_encoding,
191
            &keys[1]).IsNothing()) {
192
      return v8::Nothing<bool>();
193
    }
194
    *result = v8::Array::New(env->isolate(), keys, arraysize(keys));
195
    return v8::Just(true);
196
  }
197
};
198
199
struct SecretKeyGenConfig final : public MemoryRetainer {
200
  size_t length;  // Expressed a a number of bits
201
  char* out = nullptr;  // Placeholder for the generated key bytes
202
203
  void MemoryInfo(MemoryTracker* tracker) const override;
204
  SET_MEMORY_INFO_NAME(SecretKeyGenConfig)
205
  SET_SELF_SIZE(SecretKeyGenConfig)
206
};
207
208
struct SecretKeyGenTraits final {
209
  using AdditionalParameters = SecretKeyGenConfig;
210
  static const AsyncWrap::ProviderType Provider =
211
      AsyncWrap::PROVIDER_KEYGENREQUEST;
212
  static constexpr const char* JobName = "SecretKeyGenJob";
213
214
  static v8::Maybe<bool> AdditionalConfig(
215
      CryptoJobMode mode,
216
      const v8::FunctionCallbackInfo<v8::Value>& args,
217
      unsigned int* offset,
218
      SecretKeyGenConfig* params);
219
220
  static KeyGenJobStatus DoKeyGen(
221
      Environment* env,
222
      SecretKeyGenConfig* params);
223
224
  static v8::Maybe<bool> EncodeKey(
225
      Environment* env,
226
      SecretKeyGenConfig* params,
227
      v8::Local<v8::Value>* result);
228
};
229
230
template <typename AlgorithmParams>
231
struct KeyPairGenConfig final : public MemoryRetainer {
232
  PublicKeyEncodingConfig public_key_encoding;
233
  PrivateKeyEncodingConfig private_key_encoding;
234
  ManagedEVPPKey key;
235
  AlgorithmParams params;
236
237
  KeyPairGenConfig() = default;
238
239
  explicit KeyPairGenConfig(KeyPairGenConfig&& other) noexcept
240
      : public_key_encoding(other.public_key_encoding),
241
        private_key_encoding(
242
            std::forward<PrivateKeyEncodingConfig>(
243
                other.private_key_encoding)),
244
        key(std::move(other.key)),
245
        params(std::move(other.params)) {}
246
247
  KeyPairGenConfig& operator=(KeyPairGenConfig&& other) noexcept {
248
    if (&other == this) return *this;
249
    this->~KeyPairGenConfig();
250
    return *new (this) KeyPairGenConfig(std::move(other));
251
  }
252
253
  void MemoryInfo(MemoryTracker* tracker) const override {
254
    tracker->TrackField("key", key);
255
    if (!private_key_encoding.passphrase_.IsEmpty()) {
256
      tracker->TrackFieldWithSize("private_key_encoding.passphrase",
257
                                  private_key_encoding.passphrase_->size());
258
    }
259
    tracker->TrackField("params", params);
260
  }
261
262
  SET_MEMORY_INFO_NAME(KeyPairGenConfig)
263
  SET_SELF_SIZE(KeyPairGenConfig)
264
};
265
266
struct NidKeyPairParams final : public MemoryRetainer {
267
  int id;
268
  SET_NO_MEMORY_INFO()
269
  SET_MEMORY_INFO_NAME(NidKeyPairParams)
270
  SET_SELF_SIZE(NidKeyPairParams)
271
};
272
273
using NidKeyPairGenConfig = KeyPairGenConfig<NidKeyPairParams>;
274
275
struct NidKeyPairGenTraits final {
276
  using AdditionalParameters = NidKeyPairGenConfig;
277
  static constexpr const char* JobName = "NidKeyPairGenJob";
278
279
  static EVPKeyCtxPointer Setup(NidKeyPairGenConfig* params);
280
281
  static v8::Maybe<bool> AdditionalConfig(
282
      CryptoJobMode mode,
283
      const v8::FunctionCallbackInfo<v8::Value>& args,
284
      unsigned int* offset,
285
      NidKeyPairGenConfig* params);
286
};
287
288
using NidKeyPairGenJob = KeyGenJob<KeyPairGenTraits<NidKeyPairGenTraits>>;
289
using SecretKeyGenJob = KeyGenJob<SecretKeyGenTraits>;
290
}  // namespace crypto
291
}  // namespace node
292
293
#endif  // !defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
294
#endif  // SRC_CRYPTO_CRYPTO_KEYGEN_H_
295