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