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_keys.h Lines: 49 81 60.5 %
Date: 2021-06-04 04:12:13 Branches: 10 30 33.3 %

Line Branch Exec Source
1
#ifndef SRC_CRYPTO_CRYPTO_KEYS_H_
2
#define SRC_CRYPTO_CRYPTO_KEYS_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
#include "crypto/crypto_util.h"
7
#include "base_object.h"
8
#include "env.h"
9
#include "memory_tracker.h"
10
#include "node_buffer.h"
11
#include "node_worker.h"
12
#include "v8.h"
13
14
#include <openssl/evp.h>
15
16
#include <memory>
17
#include <string>
18
19
namespace node {
20
namespace crypto {
21
enum PKEncodingType {
22
  // RSAPublicKey / RSAPrivateKey according to PKCS#1.
23
  kKeyEncodingPKCS1,
24
  // PrivateKeyInfo or EncryptedPrivateKeyInfo according to PKCS#8.
25
  kKeyEncodingPKCS8,
26
  // SubjectPublicKeyInfo according to X.509.
27
  kKeyEncodingSPKI,
28
  // ECPrivateKey according to SEC1.
29
  kKeyEncodingSEC1
30
};
31
32
enum PKFormatType {
33
  kKeyFormatDER,
34
  kKeyFormatPEM
35
};
36
37
enum KeyType {
38
  kKeyTypeSecret,
39
  kKeyTypePublic,
40
  kKeyTypePrivate
41
};
42
43
enum KeyEncodingContext {
44
  kKeyContextInput,
45
  kKeyContextExport,
46
  kKeyContextGenerate
47
};
48
49
enum class ParseKeyResult {
50
  kParseKeyOk,
51
  kParseKeyNotRecognized,
52
  kParseKeyNeedPassphrase,
53
  kParseKeyFailed
54
};
55
56
2806
struct AsymmetricKeyEncodingConfig {
57
  bool output_key_object_ = false;
58
  PKFormatType format_ = kKeyFormatDER;
59
  v8::Maybe<PKEncodingType> type_ = v8::Nothing<PKEncodingType>();
60
};
61
62
using PublicKeyEncodingConfig = AsymmetricKeyEncodingConfig;
63
64
13099
struct PrivateKeyEncodingConfig : public AsymmetricKeyEncodingConfig {
65
  const EVP_CIPHER* cipher_;
66
  // The ByteSource alone is not enough to distinguish between "no passphrase"
67
  // and a zero-length passphrase (which can be a null pointer), therefore, we
68
  // use a NonCopyableMaybe.
69
  NonCopyableMaybe<ByteSource> passphrase_;
70
};
71
72
// This uses the built-in reference counter of OpenSSL to manage an EVP_PKEY
73
// which is slightly more efficient than using a shared pointer and easier to
74
// use.
75
14393
class ManagedEVPPKey : public MemoryRetainer {
76
 public:
77
4678
  ManagedEVPPKey() : mutex_(std::make_shared<Mutex>()) {}
78
  explicit ManagedEVPPKey(EVPKeyPointer&& pkey);
79
  ManagedEVPPKey(const ManagedEVPPKey& that);
80
  ManagedEVPPKey& operator=(const ManagedEVPPKey& that);
81
82
  operator bool() const;
83
  EVP_PKEY* get() const;
84
  Mutex* mutex() const;
85
86
  void MemoryInfo(MemoryTracker* tracker) const override;
87
  SET_MEMORY_INFO_NAME(ManagedEVPPKey)
88
  SET_SELF_SIZE(ManagedEVPPKey)
89
90
  static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
91
      const v8::FunctionCallbackInfo<v8::Value>& args,
92
      unsigned int* offset,
93
      KeyEncodingContext context);
94
95
  static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
96
      const v8::FunctionCallbackInfo<v8::Value>& args,
97
      unsigned int* offset,
98
      KeyEncodingContext context);
99
100
  static ManagedEVPPKey GetParsedKey(Environment* env,
101
                                     EVPKeyPointer&& pkey,
102
                                     ParseKeyResult ret,
103
                                     const char* default_msg);
104
105
  static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
106
    const v8::FunctionCallbackInfo<v8::Value>& args,
107
    unsigned int* offset);
108
109
  static ManagedEVPPKey GetPrivateKeyFromJs(
110
      const v8::FunctionCallbackInfo<v8::Value>& args,
111
      unsigned int* offset,
112
      bool allow_key_object);
113
114
  static v8::Maybe<bool> ToEncodedPublicKey(
115
      Environment* env,
116
      ManagedEVPPKey key,
117
      const PublicKeyEncodingConfig& config,
118
      v8::Local<v8::Value>* out);
119
120
  static v8::Maybe<bool> ToEncodedPrivateKey(
121
      Environment* env,
122
      ManagedEVPPKey key,
123
      const PrivateKeyEncodingConfig& config,
124
      v8::Local<v8::Value>* out);
125
126
 private:
127
  size_t size_of_private_key() const;
128
  size_t size_of_public_key() const;
129
130
  EVPKeyPointer pkey_;
131
  std::shared_ptr<Mutex> mutex_;
132
};
133
134
// Objects of this class can safely be shared among threads.
135
4262
class KeyObjectData : public MemoryRetainer {
136
 public:
137
  static std::shared_ptr<KeyObjectData> CreateSecret(ByteSource key);
138
139
  static std::shared_ptr<KeyObjectData> CreateAsymmetric(
140
      KeyType type,
141
      const ManagedEVPPKey& pkey);
142
143
  KeyType GetKeyType() const;
144
145
  // These functions allow unprotected access to the raw key material and should
146
  // only be used to implement cryptographic operations requiring the key.
147
  ManagedEVPPKey GetAsymmetricKey() const;
148
  const char* GetSymmetricKey() const;
149
  size_t GetSymmetricKeySize() const;
150
151
  void MemoryInfo(MemoryTracker* tracker) const override;
152
  SET_MEMORY_INFO_NAME(KeyObjectData)
153
  SET_SELF_SIZE(KeyObjectData)
154
155
 private:
156
  explicit KeyObjectData(ByteSource symmetric_key);
157
158
  KeyObjectData(
159
      KeyType type,
160
      const ManagedEVPPKey& pkey);
161
162
  const KeyType key_type_;
163
  const ByteSource symmetric_key_;
164
  const unsigned int symmetric_key_len_;
165
  const ManagedEVPPKey asymmetric_key_;
166
};
167
168
4296
class KeyObjectHandle : public BaseObject {
169
 public:
170
  static v8::Local<v8::Function> Initialize(Environment* env);
171
172
  static v8::MaybeLocal<v8::Object> Create(Environment* env,
173
                                           std::shared_ptr<KeyObjectData> data);
174
175
  // TODO(tniessen): track the memory used by OpenSSL types
176
  SET_NO_MEMORY_INFO()
177
  SET_MEMORY_INFO_NAME(KeyObjectHandle)
178
  SET_SELF_SIZE(KeyObjectHandle)
179
180
  const std::shared_ptr<KeyObjectData>& Data();
181
182
 protected:
183
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
184
185
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
186
  static void InitECRaw(const v8::FunctionCallbackInfo<v8::Value>& args);
187
  static void InitEDRaw(const v8::FunctionCallbackInfo<v8::Value>& args);
188
  static void InitJWK(const v8::FunctionCallbackInfo<v8::Value>& args);
189
  static void GetKeyDetail(const v8::FunctionCallbackInfo<v8::Value>& args);
190
191
  static void ExportJWK(const v8::FunctionCallbackInfo<v8::Value>& args);
192
193
  static void GetAsymmetricKeyType(
194
      const v8::FunctionCallbackInfo<v8::Value>& args);
195
  v8::Local<v8::Value> GetAsymmetricKeyType() const;
196
197
  static void GetSymmetricKeySize(
198
      const v8::FunctionCallbackInfo<v8::Value>& args);
199
200
  static void Export(const v8::FunctionCallbackInfo<v8::Value>& args);
201
202
  v8::MaybeLocal<v8::Value> ExportSecretKey() const;
203
  v8::MaybeLocal<v8::Value> ExportPublicKey(
204
      const PublicKeyEncodingConfig& config) const;
205
  v8::MaybeLocal<v8::Value> ExportPrivateKey(
206
      const PrivateKeyEncodingConfig& config) const;
207
208
  KeyObjectHandle(Environment* env,
209
                  v8::Local<v8::Object> wrap);
210
211
 private:
212
  std::shared_ptr<KeyObjectData> data_;
213
};
214
215
4250
class NativeKeyObject : public BaseObject {
216
 public:
217
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
218
219
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
220
  static void CreateNativeKeyObjectClass(
221
      const v8::FunctionCallbackInfo<v8::Value>& args);
222
223
  SET_NO_MEMORY_INFO()
224
  SET_MEMORY_INFO_NAME(NativeKeyObject)
225
  SET_SELF_SIZE(NativeKeyObject)
226
227
22
  class KeyObjectTransferData : public worker::TransferData {
228
   public:
229
11
    explicit KeyObjectTransferData(const std::shared_ptr<KeyObjectData>& data)
230
11
        : data_(data) {}
231
232
    BaseObjectPtr<BaseObject> Deserialize(
233
        Environment* env,
234
        v8::Local<v8::Context> context,
235
        std::unique_ptr<worker::TransferData> self) override;
236
237
    SET_MEMORY_INFO_NAME(KeyObjectTransferData)
238
    SET_SELF_SIZE(KeyObjectTransferData)
239
    SET_NO_MEMORY_INFO()
240
241
   private:
242
    std::shared_ptr<KeyObjectData> data_;
243
  };
244
245
  BaseObject::TransferMode GetTransferMode() const override;
246
  std::unique_ptr<worker::TransferData> CloneForMessaging() const override;
247
248
 private:
249
2125
  NativeKeyObject(Environment* env,
250
                  v8::Local<v8::Object> wrap,
251
                  const std::shared_ptr<KeyObjectData>& handle_data)
252
2125
    : BaseObject(env, wrap),
253
2125
      handle_data_(handle_data) {
254
2125
    MakeWeak();
255
2125
  }
256
257
  std::shared_ptr<KeyObjectData> handle_data_;
258
};
259
260
enum WebCryptoKeyFormat {
261
  kWebCryptoKeyFormatRaw,
262
  kWebCryptoKeyFormatPKCS8,
263
  kWebCryptoKeyFormatSPKI,
264
  kWebCryptoKeyFormatJWK
265
};
266
267
enum class WebCryptoKeyExportStatus {
268
  OK,
269
  INVALID_KEY_TYPE,
270
  FAILED
271
};
272
273
template <typename KeyExportTraits>
274
462
class KeyExportJob final : public CryptoJob<KeyExportTraits> {
275
 public:
276
  using AdditionalParams = typename KeyExportTraits::AdditionalParameters;
277
278
231
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
279
231
    Environment* env = Environment::GetCurrent(args);
280
231
    CHECK(args.IsConstructCall());
281
282
231
    CryptoJobMode mode = GetCryptoJobMode(args[0]);
283
284
462
    CHECK(args[1]->IsUint32());  // Export Type
285
462
    CHECK(args[2]->IsObject());  // KeyObject
286
287
    WebCryptoKeyFormat format =
288
693
        static_cast<WebCryptoKeyFormat>(args[1].As<v8::Uint32>()->Value());
289
290
    KeyObjectHandle* key;
291
231
    ASSIGN_OR_RETURN_UNWRAP(&key, args[2]);
292
293
231
    CHECK_NOT_NULL(key);
294
295
462
    AdditionalParams params;
296
462
    if (KeyExportTraits::AdditionalConfig(args, 3, &params).IsNothing()) {
297
      // The KeyExportTraits::AdditionalConfig is responsible for
298
      // calling an appropriate THROW_CRYPTO_* variant reporting
299
      // whatever error caused initialization to fail.
300
      return;
301
    }
302
303
231
    new KeyExportJob<KeyExportTraits>(
304
        env,
305
462
        args.This(),
306
        mode,
307
        key->Data(),
308
        format,
309
        std::move(params));
310
  }
311
312
16676
  static void Initialize(
313
      Environment* env,
314
      v8::Local<v8::Object> target) {
315
16676
    CryptoJob<KeyExportTraits>::Initialize(New, env, target);
316
16676
  }
317
318
231
  KeyExportJob(
319
      Environment* env,
320
      v8::Local<v8::Object> object,
321
      CryptoJobMode mode,
322
      std::shared_ptr<KeyObjectData> key,
323
      WebCryptoKeyFormat format,
324
      AdditionalParams&& params)
325
      : CryptoJob<KeyExportTraits>(
326
            env,
327
            object,
328
            AsyncWrap::PROVIDER_KEYEXPORTREQUEST,
329
            mode,
330
231
            std::move(params)),
331
        key_(key),
332
231
        format_(format) {}
333
334
  WebCryptoKeyFormat format() const { return format_; }
335
336
231
  void DoThreadPoolWork() override {
337
    const WebCryptoKeyExportStatus status =
338
693
        KeyExportTraits::DoExport(
339
            key_,
340
            format_,
341
231
            *CryptoJob<KeyExportTraits>::params(),
342
231
            &out_);
343
231
    if (status == WebCryptoKeyExportStatus::OK) {
344
      // Success!
345
231
      return;
346
    }
347
    CryptoErrorStore* errors = CryptoJob<KeyExportTraits>::errors();
348
    errors->Capture();
349
    if (errors->Empty()) {
350
      switch (status) {
351
        case WebCryptoKeyExportStatus::OK:
352
          UNREACHABLE();
353
          break;
354
        case WebCryptoKeyExportStatus::INVALID_KEY_TYPE:
355
          errors->Insert(NodeCryptoError::INVALID_KEY_TYPE);
356
          break;
357
        case WebCryptoKeyExportStatus::FAILED:
358
          errors->Insert(NodeCryptoError::CIPHER_JOB_FAILED);
359
          break;
360
      }
361
    }
362
  }
363
364
231
  v8::Maybe<bool> ToResult(
365
      v8::Local<v8::Value>* err,
366
      v8::Local<v8::Value>* result) override {
367
231
    Environment* env = AsyncWrap::env();
368
231
    CryptoErrorStore* errors = CryptoJob<KeyExportTraits>::errors();
369
231
    if (out_.size() > 0) {
370
231
      CHECK(errors->Empty());
371
462
      *err = v8::Undefined(env->isolate());
372
462
      *result = out_.ToArrayBuffer(env);
373
231
      return v8::Just(!result->IsEmpty());
374
    }
375
376
    if (errors->Empty())
377
      errors->Capture();
378
    CHECK(!errors->Empty());
379
    *result = v8::Undefined(env->isolate());
380
    return v8::Just(errors->ToException(env).ToLocal(err));
381
  }
382
383
  SET_SELF_SIZE(KeyExportJob)
384
  void MemoryInfo(MemoryTracker* tracker) const override {
385
    tracker->TrackFieldWithSize("out", out_.size());
386
    CryptoJob<KeyExportTraits>::MemoryInfo(tracker);
387
  }
388
389
 private:
390
  std::shared_ptr<KeyObjectData> key_;
391
  WebCryptoKeyFormat format_;
392
  ByteSource out_;
393
};
394
395
WebCryptoKeyExportStatus PKEY_SPKI_Export(
396
    KeyObjectData* key_data,
397
    ByteSource* out);
398
399
WebCryptoKeyExportStatus PKEY_PKCS8_Export(
400
    KeyObjectData* key_data,
401
    ByteSource* out);
402
403
namespace Keys {
404
void Initialize(Environment* env, v8::Local<v8::Object> target);
405
}  // namespace Keys
406
407
}  // namespace crypto
408
}  // namespace node
409
410
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
411
#endif  // SRC_CRYPTO_CRYPTO_KEYS_H_