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_sig.cc Lines: 436 497 87.7 %
Date: 2021-02-11 04:11:15 Branches: 246 367 67.0 %

Line Branch Exec Source
1
#include "crypto/crypto_sig.h"
2
#include "crypto/crypto_ec.h"
3
#include "crypto/crypto_keys.h"
4
#include "crypto/crypto_util.h"
5
#include "allocated_buffer-inl.h"
6
#include "async_wrap-inl.h"
7
#include "base_object-inl.h"
8
#include "env-inl.h"
9
#include "memory_tracker-inl.h"
10
#include "threadpoolwork-inl.h"
11
#include "v8.h"
12
13
namespace node {
14
15
using v8::FunctionCallbackInfo;
16
using v8::FunctionTemplate;
17
using v8::HandleScope;
18
using v8::Int32;
19
using v8::Just;
20
using v8::Local;
21
using v8::Maybe;
22
using v8::Nothing;
23
using v8::Object;
24
using v8::Uint32;
25
using v8::Value;
26
27
namespace crypto {
28
namespace {
29
180
bool ValidateDSAParameters(EVP_PKEY* key) {
30
#ifdef NODE_FIPS_MODE
31
  /* Validate DSA2 parameters from FIPS 186-4 */
32
  if (FIPS_mode() && EVP_PKEY_DSA == EVP_PKEY_base_id(key)) {
33
    DSA* dsa = EVP_PKEY_get0_DSA(key);
34
    const BIGNUM* p;
35
    DSA_get0_pqg(dsa, &p, nullptr, nullptr);
36
    size_t L = BN_num_bits(p);
37
    const BIGNUM* q;
38
    DSA_get0_pqg(dsa, nullptr, &q, nullptr);
39
    size_t N = BN_num_bits(q);
40
41
    return (L == 1024 && N == 160) ||
42
           (L == 2048 && N == 224) ||
43
           (L == 2048 && N == 256) ||
44
           (L == 3072 && N == 256);
45
  }
46
#endif  // NODE_FIPS_MODE
47
48
180
  return true;
49
}
50
51
1504
bool ApplyRSAOptions(const ManagedEVPPKey& pkey,
52
                     EVP_PKEY_CTX* pkctx,
53
                     int padding,
54
                     const Maybe<int>& salt_len) {
55

3481
  if (EVP_PKEY_id(pkey.get()) == EVP_PKEY_RSA ||
56

1977
      EVP_PKEY_id(pkey.get()) == EVP_PKEY_RSA2 ||
57
473
      EVP_PKEY_id(pkey.get()) == EVP_PKEY_RSA_PSS) {
58
1206
    if (EVP_PKEY_CTX_set_rsa_padding(pkctx, padding) <= 0)
59
3
      return false;
60

2228
    if (padding == RSA_PKCS1_PSS_PADDING && salt_len.IsJust()) {
61
976
      if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, salt_len.FromJust()) <= 0)
62
6
        return false;
63
    }
64
  }
65
66
1495
  return true;
67
}
68
69
112
AllocatedBuffer Node_SignFinal(Environment* env,
70
                               EVPMDPointer&& mdctx,
71
                               const ManagedEVPPKey& pkey,
72
                               int padding,
73
                               Maybe<int> pss_salt_len) {
74
  unsigned char m[EVP_MAX_MD_SIZE];
75
  unsigned int m_len;
76
77
112
  if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len))
78
    return AllocatedBuffer();
79
80
112
  int signed_sig_len = EVP_PKEY_size(pkey.get());
81
112
  CHECK_GE(signed_sig_len, 0);
82
112
  size_t sig_len = static_cast<size_t>(signed_sig_len);
83
224
  AllocatedBuffer sig = AllocatedBuffer::AllocateManaged(env, sig_len);
84
112
  unsigned char* ptr = reinterpret_cast<unsigned char*>(sig.data());
85
86
224
  EVPKeyCtxPointer pkctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
87

224
  if (pkctx &&
88
336
      EVP_PKEY_sign_init(pkctx.get()) &&
89
216
      ApplyRSAOptions(pkey, pkctx.get(), padding, pss_salt_len) &&
90

314
      EVP_PKEY_CTX_set_signature_md(pkctx.get(), EVP_MD_CTX_md(mdctx.get())) &&
91
98
      EVP_PKEY_sign(pkctx.get(), ptr, &sig_len, m, m_len)) {
92
97
    sig.Resize(sig_len);
93
97
    return sig;
94
  }
95
96
15
  return AllocatedBuffer();
97
}
98
99
1422
int GetDefaultSignPadding(const ManagedEVPPKey& m_pkey) {
100
1422
  return EVP_PKEY_id(m_pkey.get()) == EVP_PKEY_RSA_PSS ? RSA_PKCS1_PSS_PADDING :
101
1422
                                                         RSA_PKCS1_PADDING;
102
}
103
104
24
unsigned int GetBytesOfRS(const ManagedEVPPKey& pkey) {
105
24
  int bits, base_id = EVP_PKEY_base_id(pkey.get());
106
107
24
  if (base_id == EVP_PKEY_DSA) {
108
9
    DSA* dsa_key = EVP_PKEY_get0_DSA(pkey.get());
109
    // Both r and s are computed mod q, so their width is limited by that of q.
110
9
    bits = BN_num_bits(DSA_get0_q(dsa_key));
111
15
  } else if (base_id == EVP_PKEY_EC) {
112
13
    EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(pkey.get());
113
13
    const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key);
114
13
    bits = EC_GROUP_order_bits(ec_group);
115
  } else {
116
2
    return kNoDsaSignature;
117
  }
118
119
22
  return (bits + 7) / 8;
120
}
121
122
// Returns the maximum size of each of the integers (r, s) of the DSA signature.
123
3
AllocatedBuffer ConvertSignatureToP1363(Environment* env,
124
                                        const ManagedEVPPKey& pkey,
125
                                        AllocatedBuffer&& signature) {
126
3
  unsigned int n = GetBytesOfRS(pkey);
127
3
  if (n == kNoDsaSignature)
128
1
    return std::move(signature);
129
130
  const unsigned char* sig_data =
131
2
      reinterpret_cast<unsigned char*>(signature.data());
132
133
4
  ECDSASigPointer asn1_sig(d2i_ECDSA_SIG(nullptr, &sig_data, signature.size()));
134
2
  if (!asn1_sig)
135
    return AllocatedBuffer();
136
137
4
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, 2 * n);
138
2
  unsigned char* data = reinterpret_cast<unsigned char*>(buf.data());
139
140
2
  const BIGNUM* r = ECDSA_SIG_get0_r(asn1_sig.get());
141
2
  const BIGNUM* s = ECDSA_SIG_get0_s(asn1_sig.get());
142
2
  CHECK_EQ(n, static_cast<unsigned int>(BN_bn2binpad(r, data, n)));
143
2
  CHECK_EQ(n, static_cast<unsigned int>(BN_bn2binpad(s, data + n, n)));
144
145
2
  return buf;
146
}
147
148
149
21
ByteSource ConvertSignatureToDER(
150
      const ManagedEVPPKey& pkey,
151
      const ArrayBufferOrViewContents<char>& signature) {
152
21
  unsigned int n = GetBytesOfRS(pkey);
153
21
  if (n == kNoDsaSignature)
154
1
    return signature.ToByteSource();
155
156
  const unsigned char* sig_data =
157
20
      reinterpret_cast<const  unsigned char*>(signature.data());
158
159
20
  if (signature.size() != 2 * n)
160
12
    return ByteSource();
161
162
16
  ECDSASigPointer asn1_sig(ECDSA_SIG_new());
163
8
  CHECK(asn1_sig);
164
8
  BIGNUM* r = BN_new();
165
8
  CHECK_NOT_NULL(r);
166
8
  BIGNUM* s = BN_new();
167
8
  CHECK_NOT_NULL(s);
168
8
  CHECK_EQ(r, BN_bin2bn(sig_data, n, r));
169
8
  CHECK_EQ(s, BN_bin2bn(sig_data + n, n, s));
170
8
  CHECK_EQ(1, ECDSA_SIG_set0(asn1_sig.get(), r, s));
171
172
8
  unsigned char* data = nullptr;
173
8
  int len = i2d_ECDSA_SIG(asn1_sig.get(), &data);
174
175
8
  if (len <= 0)
176
    return ByteSource();
177
178
8
  CHECK_NOT_NULL(data);
179
180
8
  return ByteSource::Allocated(reinterpret_cast<char*>(data), len);
181
}
182
183
1481
void CheckThrow(Environment* env, SignBase::Error error) {
184
1481
  HandleScope scope(env->isolate());
185
186

1481
  switch (error) {
187
    case SignBase::Error::kSignUnknownDigest:
188
2
      return THROW_ERR_CRYPTO_INVALID_DIGEST(env);
189
190
    case SignBase::Error::kSignNotInitialised:
191
      return THROW_ERR_CRYPTO_INVALID_STATE(env, "Not initialised");
192
193
    case SignBase::Error::kSignMalformedSignature:
194
12
      return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Malformed signature");
195
196
    case SignBase::Error::kSignInit:
197
    case SignBase::Error::kSignUpdate:
198
    case SignBase::Error::kSignPrivateKey:
199
    case SignBase::Error::kSignPublicKey:
200
      {
201
16
        unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
202
16
        if (err)
203
16
          return ThrowCryptoError(env, err);
204
        switch (error) {
205
          case SignBase::Error::kSignInit:
206
            return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
207
                "EVP_SignInit_ex failed");
208
          case SignBase::Error::kSignUpdate:
209
            return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
210
                "EVP_SignUpdate failed");
211
          case SignBase::Error::kSignPrivateKey:
212
            return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
213
                "PEM_read_bio_PrivateKey failed");
214
          case SignBase::Error::kSignPublicKey:
215
            return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
216
                "PEM_read_bio_PUBKEY failed");
217
          default:
218
            ABORT();
219
        }
220
      }
221
222
    case SignBase::Error::kSignOk:
223
1451
      return;
224
  }
225
}
226
227
60
bool IsOneShot(const ManagedEVPPKey& key) {
228
60
  switch (EVP_PKEY_id(key.get())) {
229
    case EVP_PKEY_ED25519:
230
    case EVP_PKEY_ED448:
231
9
      return true;
232
    default:
233
51
      return false;
234
  }
235
}
236
}  // namespace
237
238
728
SignBase::Error SignBase::Init(const char* sign_type) {
239
728
  CHECK_NULL(mdctx_);
240
  // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1
241
  // exposed through the public API.
242

1456
  if (strcmp(sign_type, "dss1") == 0 ||
243
728
      strcmp(sign_type, "DSS1") == 0) {
244
2
    sign_type = "SHA1";
245
  }
246
728
  const EVP_MD* md = EVP_get_digestbyname(sign_type);
247
728
  if (md == nullptr)
248
1
    return kSignUnknownDigest;
249
250
727
  mdctx_.reset(EVP_MD_CTX_new());
251

727
  if (!mdctx_ || !EVP_DigestInit_ex(mdctx_.get(), md, nullptr)) {
252
    mdctx_.reset();
253
    return kSignInit;
254
  }
255
256
727
  return kSignOk;
257
}
258
259
724
SignBase::Error SignBase::Update(const char* data, size_t len) {
260
724
  if (mdctx_ == nullptr)
261
    return kSignNotInitialised;
262
724
  if (!EVP_DigestUpdate(mdctx_.get(), data, len))
263
    return kSignUpdate;
264
724
  return kSignOk;
265
}
266
267
728
SignBase::SignBase(Environment* env, Local<Object> wrap)
268
728
    : BaseObject(env, wrap) {}
269
270
void SignBase::MemoryInfo(MemoryTracker* tracker) const {
271
  tracker->TrackFieldWithSize("mdctx", mdctx_ ? kSizeOf_EVP_MD_CTX : 0);
272
}
273
274
139
Sign::Sign(Environment* env, Local<Object> wrap) : SignBase(env, wrap) {
275
139
  MakeWeak();
276
139
}
277
278
667
void Sign::Initialize(Environment* env, Local<Object> target) {
279
667
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
280
281
2001
  t->InstanceTemplate()->SetInternalFieldCount(
282
667
      SignBase::kInternalFieldCount);
283
1334
  t->Inherit(BaseObject::GetConstructorTemplate(env));
284
285
667
  env->SetProtoMethod(t, "init", SignInit);
286
667
  env->SetProtoMethod(t, "update", SignUpdate);
287
667
  env->SetProtoMethod(t, "sign", SignFinal);
288
289
667
  env->SetConstructorFunction(target, "Sign", t);
290
291
667
  env->SetMethod(target, "signOneShot", Sign::SignSync);
292
293
667
  SignJob::Initialize(env, target);
294
295
667
  constexpr int kSignJobModeSign = SignConfiguration::kSign;
296
667
  constexpr int kSignJobModeVerify = SignConfiguration::kVerify;
297
298
2668
  NODE_DEFINE_CONSTANT(target, kSignJobModeSign);
299
667
  NODE_DEFINE_CONSTANT(target, kSignJobModeVerify);
300
2001
  NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PSS_PADDING);
301
3335
}
302
4669
303
3474
void Sign::New(const FunctionCallbackInfo<Value>& args) {
304
1473
  Environment* env = Environment::GetCurrent(args);
305
139
  new Sign(env, args.This());
306
139
}
307
308
139
void Sign::SignInit(const FunctionCallbackInfo<Value>& args) {
309
139
  Environment* env = Environment::GetCurrent(args);
310
  Sign* sign;
311
139
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
312
313
278
  const node::Utf8Value sign_type(args.GetIsolate(), args[0]);
314
139
  crypto::CheckThrow(env, sign->Init(*sign_type));
315
}
316
317
125
void Sign::SignUpdate(const FunctionCallbackInfo<Value>& args) {
318
250
  Decode<Sign>(args, [](Sign* sign, const FunctionCallbackInfo<Value>& args,
319
375
                        const char* data, size_t size) {
320
125
    Environment* env = Environment::GetCurrent(args);
321
125
    if (UNLIKELY(size > INT_MAX))
322
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
323
125
    Error err = sign->Update(data, size);
324
125
    crypto::CheckThrow(sign->env(), err);
325
375
  });
326
125
}
327
328
112
Sign::SignResult Sign::SignFinal(
329
    const ManagedEVPPKey& pkey,
330
    int padding,
331
    const Maybe<int>& salt_len,
332
    DSASigEnc dsa_sig_enc) {
333
112
  if (!mdctx_)
334
    return SignResult(kSignNotInitialised);
335
336
224
  EVPMDPointer mdctx = std::move(mdctx_);
337
338
112
  if (!ValidateDSAParameters(pkey.get()))
339
    return SignResult(kSignPrivateKey);
340
341
  AllocatedBuffer buffer =
342
224
      Node_SignFinal(env(), std::move(mdctx), pkey, padding, salt_len);
343
112
  Error error = buffer.data() == nullptr ? kSignPrivateKey : kSignOk;
344

112
  if (error == kSignOk && dsa_sig_enc == kSigEncP1363) {
345
    buffer = ConvertSignatureToP1363(env(), pkey, std::move(buffer));
346
    CHECK_NOT_NULL(buffer.data());
347
  }
348
112
  return SignResult(error, std::move(buffer));
349
}
350
351
116
void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
352
116
  Environment* env = Environment::GetCurrent(args);
353
  Sign* sign;
354
135
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
355
356
97
  ClearErrorOnReturn clear_error_on_return;
357
358
116
  unsigned int offset = 0;
359
213
  ManagedEVPPKey key = ManagedEVPPKey::GetPrivateKeyFromJs(args, &offset, true);
360
116
  if (!key)
361
4
    return;
362
363
112
  int padding = GetDefaultSignPadding(key);
364
448
  if (!args[offset]->IsUndefined()) {
365
63
    CHECK(args[offset]->IsInt32());
366
84
    padding = args[offset].As<Int32>()->Value();
367
  }
368
369
112
  Maybe<int> salt_len = Nothing<int>();
370
448
  if (!args[offset + 1]->IsUndefined()) {
371
162
    CHECK(args[offset + 1]->IsInt32());
372
216
    salt_len = Just<int>(args[offset + 1].As<Int32>()->Value());
373
  }
374
375
336
  CHECK(args[offset + 2]->IsInt32());
376
  DSASigEnc dsa_sig_enc =
377
448
      static_cast<DSASigEnc>(args[offset + 2].As<Int32>()->Value());
378
379
  SignResult ret = sign->SignFinal(
380
      key,
381
      padding,
382
      salt_len,
383
209
      dsa_sig_enc);
384
385
112
  if (ret.error != kSignOk)
386
15
    return crypto::CheckThrow(env, ret.error);
387
388
291
  args.GetReturnValue().Set(ret.signature.ToBuffer().FromMaybe(Local<Value>()));
389
}
390
391
589
Verify::Verify(Environment* env, Local<Object> wrap)
392
589
  : SignBase(env, wrap) {
393
589
  MakeWeak();
394
589
}
395
396
667
void Verify::Initialize(Environment* env, Local<Object> target) {
397
667
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
398
399
2001
  t->InstanceTemplate()->SetInternalFieldCount(
400
667
      SignBase::kInternalFieldCount);
401
1334
  t->Inherit(BaseObject::GetConstructorTemplate(env));
402
403
667
  env->SetProtoMethod(t, "init", VerifyInit);
404
667
  env->SetProtoMethod(t, "update", VerifyUpdate);
405
667
  env->SetProtoMethod(t, "verify", VerifyFinal);
406
407
667
  env->SetConstructorFunction(target, "Verify", t);
408
409
667
  env->SetMethod(target, "verifyOneShot", Verify::VerifySync);
410
667
}
411
412
589
void Verify::New(const FunctionCallbackInfo<Value>& args) {
413
589
  Environment* env = Environment::GetCurrent(args);
414
589
  new Verify(env, args.This());
415
589
}
416
417
589
void Verify::VerifyInit(const FunctionCallbackInfo<Value>& args) {
418
589
  Environment* env = Environment::GetCurrent(args);
419
  Verify* verify;
420
589
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
421
422
1178
  const node::Utf8Value verify_type(args.GetIsolate(), args[0]);
423
589
  crypto::CheckThrow(env, verify->Init(*verify_type));
424
}
425
426
599
void Verify::VerifyUpdate(const FunctionCallbackInfo<Value>& args) {
427
1198
  Decode<Verify>(args, [](Verify* verify,
428
                          const FunctionCallbackInfo<Value>& args,
429
1797
                          const char* data, size_t size) {
430
599
    Environment* env = Environment::GetCurrent(args);
431
599
    if (UNLIKELY(size > INT_MAX))
432
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
433
599
    Error err = verify->Update(data, size);
434
599
    crypto::CheckThrow(verify->env(), err);
435
1797
  });
436
599
}
437
438
582
SignBase::Error Verify::VerifyFinal(const ManagedEVPPKey& pkey,
439
                                    const ByteSource& sig,
440
                                    int padding,
441
                                    const Maybe<int>& saltlen,
442
                                    bool* verify_result) {
443
582
  if (!mdctx_)
444
    return kSignNotInitialised;
445
446
  unsigned char m[EVP_MAX_MD_SIZE];
447
  unsigned int m_len;
448
582
  *verify_result = false;
449
1164
  EVPMDPointer mdctx = std::move(mdctx_);
450
451
582
  if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len))
452
    return kSignPublicKey;
453
454
1164
  EVPKeyCtxPointer pkctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
455

1164
  if (pkctx &&
456
1746
      EVP_PKEY_verify_init(pkctx.get()) > 0 &&
457

1746
      ApplyRSAOptions(pkey, pkctx.get(), padding, saltlen) &&
458
582
      EVP_PKEY_CTX_set_signature_md(pkctx.get(),
459
                                    EVP_MD_CTX_md(mdctx.get())) > 0) {
460
582
    const unsigned char* s = reinterpret_cast<const unsigned char*>(sig.get());
461
582
    const int r = EVP_PKEY_verify(pkctx.get(), s, sig.size(), m, m_len);
462
582
    *verify_result = r == 1;
463
  }
464
465
582
  return kSignOk;
466
}
467
468
582
void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
469
582
  Environment* env = Environment::GetCurrent(args);
470
582
  ClearErrorOnReturn clear_error_on_return;
471
472
  Verify* verify;
473
582
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
474
475
582
  unsigned int offset = 0;
476
  ManagedEVPPKey pkey =
477
1164
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
478
582
  if (!pkey)
479
    return;
480
481
1746
  ArrayBufferOrViewContents<char> hbuf(args[offset]);
482
582
  if (UNLIKELY(!hbuf.CheckSizeInt32()))
483
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
484
485
582
  int padding = GetDefaultSignPadding(pkey);
486
2328
  if (!args[offset + 1]->IsUndefined()) {
487
1116
    CHECK(args[offset + 1]->IsInt32());
488
1488
    padding = args[offset + 1].As<Int32>()->Value();
489
  }
490
491
582
  Maybe<int> salt_len = Nothing<int>();
492
2328
  if (!args[offset + 2]->IsUndefined()) {
493
1386
    CHECK(args[offset + 2]->IsInt32());
494
1848
    salt_len = Just<int>(args[offset + 2].As<Int32>()->Value());
495
  }
496
497
1746
  CHECK(args[offset + 3]->IsInt32());
498
  DSASigEnc dsa_sig_enc =
499
2328
      static_cast<DSASigEnc>(args[offset + 3].As<Int32>()->Value());
500
501
1164
  ByteSource signature = hbuf.ToByteSource();
502
582
  if (dsa_sig_enc == kSigEncP1363) {
503
4
    signature = ConvertSignatureToDER(pkey, hbuf);
504
4
    if (signature.get() == nullptr)
505
      return crypto::CheckThrow(env, Error::kSignMalformedSignature);
506
  }
507
508
  bool verify_result;
509
582
  Error err = verify->VerifyFinal(pkey, signature, padding,
510
582
                                  salt_len, &verify_result);
511
582
  if (err != kSignOk)
512
    return crypto::CheckThrow(env, err);
513
1746
  args.GetReturnValue().Set(verify_result);
514
}
515
516
77
void Sign::SignSync(const FunctionCallbackInfo<Value>& args) {
517
66
  ClearErrorOnReturn clear_error_on_return;
518
77
  Environment* env = Environment::GetCurrent(args);
519
520
77
  unsigned int offset = 0;
521
143
  ManagedEVPPKey key = ManagedEVPPKey::GetPrivateKeyFromJs(args, &offset, true);
522
77
  if (!key)
523
9
    return;
524
525
68
  if (!ValidateDSAParameters(key.get()))
526
    return crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey);
527
528
202
  ArrayBufferOrViewContents<char> data(args[offset]);
529
68
  if (UNLIKELY(!data.CheckSizeInt32()))
530
    return THROW_ERR_OUT_OF_RANGE(env, "data is too big");
531
532
  const EVP_MD* md;
533
272
  if (args[offset + 1]->IsNullOrUndefined()) {
534
16
    md = nullptr;
535
  } else {
536
155
    const node::Utf8Value sign_type(args.GetIsolate(), args[offset + 1]);
537
52
    md = EVP_get_digestbyname(*sign_type);
538
52
    if (md == nullptr)
539
1
      return crypto::CheckThrow(env, SignBase::Error::kSignUnknownDigest);
540
  }
541
542
67
  int rsa_padding = GetDefaultSignPadding(key);
543
268
  if (!args[offset + 2]->IsUndefined()) {
544
57
    CHECK(args[offset + 2]->IsInt32());
545
76
    rsa_padding = args[offset + 2].As<Int32>()->Value();
546
  }
547
548
67
  Maybe<int> rsa_salt_len = Nothing<int>();
549
268
  if (!args[offset + 3]->IsUndefined()) {
550
54
    CHECK(args[offset + 3]->IsInt32());
551
72
    rsa_salt_len = Just<int>(args[offset + 3].As<Int32>()->Value());
552
  }
553
554
201
  CHECK(args[offset + 4]->IsInt32());
555
  DSASigEnc dsa_sig_enc =
556
268
      static_cast<DSASigEnc>(args[offset + 4].As<Int32>()->Value());
557
558
67
  EVP_PKEY_CTX* pkctx = nullptr;
559
133
  EVPMDPointer mdctx(EVP_MD_CTX_new());
560
561

134
  if (!mdctx ||
562
67
      !EVP_DigestSignInit(mdctx.get(), &pkctx, md, nullptr, key.get())) {
563
    return crypto::CheckThrow(env, SignBase::Error::kSignInit);
564
  }
565
566
67
  if (!ApplyRSAOptions(key, pkctx, rsa_padding, rsa_salt_len))
567
1
    return crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey);
568
569
  const unsigned char* input =
570
66
    reinterpret_cast<const unsigned char*>(data.data());
571
  size_t sig_len;
572
66
  if (!EVP_DigestSign(mdctx.get(), nullptr, &sig_len, input, data.size()))
573
    return crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey);
574
575
132
  AllocatedBuffer signature = AllocatedBuffer::AllocateManaged(env, sig_len);
576
132
  if (!EVP_DigestSign(mdctx.get(),
577
66
                      reinterpret_cast<unsigned char*>(signature.data()),
578
                      &sig_len,
579
                      input,
580
                      data.size())) {
581
    return crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey);
582
  }
583
584
66
  signature.Resize(sig_len);
585
586
66
  if (dsa_sig_enc == kSigEncP1363) {
587
3
    signature = ConvertSignatureToP1363(env, key, std::move(signature));
588
  }
589
590
198
  args.GetReturnValue().Set(signature.ToBuffer().FromMaybe(Local<Value>()));
591
}
592
593
479
void Verify::VerifySync(const FunctionCallbackInfo<Value>& args) {
594
467
  ClearErrorOnReturn clear_error_on_return;
595
479
  Environment* env = Environment::GetCurrent(args);
596
597
479
  unsigned int offset = 0;
598
  ManagedEVPPKey key =
599
946
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
600
479
  if (!key)
601
    return;
602
603
1425
  ArrayBufferOrViewContents<char> sig(args[offset]);
604
1425
  ArrayBufferOrViewContents<char> data(args[offset + 1]);
605
606
479
  if (UNLIKELY(!sig.CheckSizeInt32()))
607
    return THROW_ERR_OUT_OF_RANGE(env, "sig is too big");
608
479
  if (UNLIKELY(!data.CheckSizeInt32()))
609
    return THROW_ERR_OUT_OF_RANGE(env, "data is too big");
610
611
  const EVP_MD* md;
612
1916
  if (args[offset + 2]->IsNullOrUndefined()) {
613
20
    md = nullptr;
614
  } else {
615
1377
    const node::Utf8Value sign_type(args.GetIsolate(), args[offset + 2]);
616
459
    md = EVP_get_digestbyname(*sign_type);
617
459
    if (md == nullptr)
618
      return crypto::CheckThrow(env, SignBase::Error::kSignUnknownDigest);
619
  }
620
621
479
  int rsa_padding = GetDefaultSignPadding(key);
622
1916
  if (!args[offset + 3]->IsUndefined()) {
623
1080
    CHECK(args[offset + 3]->IsInt32());
624
1440
    rsa_padding = args[offset + 3].As<Int32>()->Value();
625
  }
626
627
479
  Maybe<int> rsa_salt_len = Nothing<int>();
628
1916
  if (!args[offset + 4]->IsUndefined()) {
629
1080
    CHECK(args[offset + 4]->IsInt32());
630
1440
    rsa_salt_len = Just<int>(args[offset + 4].As<Int32>()->Value());
631
  }
632
633
1437
  CHECK(args[offset + 5]->IsInt32());
634
  DSASigEnc dsa_sig_enc =
635
1916
      static_cast<DSASigEnc>(args[offset + 5].As<Int32>()->Value());
636
637
479
  EVP_PKEY_CTX* pkctx = nullptr;
638
946
  EVPMDPointer mdctx(EVP_MD_CTX_new());
639

958
  if (!mdctx ||
640
479
      !EVP_DigestVerifyInit(mdctx.get(), &pkctx, md, nullptr, key.get())) {
641
    return crypto::CheckThrow(env, SignBase::Error::kSignInit);
642
  }
643
644
479
  if (!ApplyRSAOptions(key, pkctx, rsa_padding, rsa_salt_len))
645
    return crypto::CheckThrow(env, SignBase::Error::kSignPublicKey);
646
647
946
  ByteSource sig_bytes = ByteSource::Foreign(sig.data(), sig.size());
648
479
  if (dsa_sig_enc == kSigEncP1363) {
649
17
    sig_bytes = ConvertSignatureToDER(key, sig);
650
17
    if (!sig_bytes)
651
12
      return crypto::CheckThrow(env, SignBase::Error::kSignMalformedSignature);
652
  }
653
654
  bool verify_result;
655
934
  const int r = EVP_DigestVerify(
656
    mdctx.get(),
657
    sig_bytes.data<unsigned char>(),
658
    sig_bytes.size(),
659
467
    reinterpret_cast<const unsigned char*>(data.data()),
660
467
    data.size());
661
467
  switch (r) {
662
    case 1:
663
191
      verify_result = true;
664
191
      break;
665
    case 0:
666
276
      verify_result = false;
667
276
      break;
668
    default:
669
      return crypto::CheckThrow(env, SignBase::Error::kSignPublicKey);
670
  }
671
672
1401
  args.GetReturnValue().Set(verify_result);
673
}
674
675
264
SignConfiguration::SignConfiguration(SignConfiguration&& other) noexcept
676
264
    : job_mode(other.job_mode),
677
264
      mode(other.mode),
678
264
      key(std::move(other.key)),
679
264
      data(std::move(other.data)),
680
264
      signature(std::move(other.signature)),
681
264
      digest(other.digest),
682
264
      flags(other.flags),
683
264
      padding(other.padding),
684
2376
      salt_length(other.salt_length) {}
685
686
SignConfiguration& SignConfiguration::operator=(
687
    SignConfiguration&& other) noexcept {
688
  if (&other == this) return *this;
689
  this->~SignConfiguration();
690
  return *new (this) SignConfiguration(std::move(other));
691
}
692
693
void SignConfiguration::MemoryInfo(MemoryTracker* tracker) const {
694
  tracker->TrackField("key", key.get());
695
  if (job_mode == kCryptoJobAsync) {
696
    tracker->TrackFieldWithSize("data", data.size());
697
    tracker->TrackFieldWithSize("signature", signature.size());
698
  }
699
}
700
701
264
Maybe<bool> SignTraits::AdditionalConfig(
702
    CryptoJobMode mode,
703
    const FunctionCallbackInfo<Value>& args,
704
    unsigned int offset,
705
    SignConfiguration* params) {
706
264
  Environment* env = Environment::GetCurrent(args);
707
708
264
  params->job_mode = mode;
709
710
792
  CHECK(args[offset]->IsUint32());  // Sign Mode
711
792
  CHECK(args[offset + 1]->IsObject());  // Key
712
713
264
  params->mode =
714
1320
      static_cast<SignConfiguration::Mode>(args[offset].As<Uint32>()->Value());
715
716
  KeyObjectHandle* key;
717
528
  ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 1], Nothing<bool>());
718
264
  params->key = key->Data();
719
720
792
  ArrayBufferOrViewContents<char> data(args[offset + 2]);
721
264
  if (UNLIKELY(!data.CheckSizeInt32())) {
722
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
723
    return Nothing<bool>();
724
  }
725
  params->data = mode == kCryptoJobAsync
726
528
      ? data.ToCopy()
727
264
      : data.ToByteSource();
728
729
1056
  if (args[offset + 3]->IsString()) {
730
738
    Utf8Value digest(env->isolate(), args[offset + 3]);
731
246
    params->digest = EVP_get_digestbyname(*digest);
732
246
    if (params->digest == nullptr) {
733
      THROW_ERR_CRYPTO_INVALID_DIGEST(env);
734
      return Nothing<bool>();
735
    }
736
  }
737
738
792
  if (args[offset + 4]->IsUint32()) {  // Salt length
739
82
    params->flags |= SignConfiguration::kHasSaltLength;
740
328
    params->salt_length = args[offset + 4].As<Uint32>()->Value();
741
  }
742
792
  if (args[offset + 5]->IsUint32()) {  // Padding
743
82
    params->flags |= SignConfiguration::kHasPadding;
744
328
    params->padding = args[offset + 5].As<Uint32>()->Value();
745
  }
746
747
264
  if (params->mode == SignConfiguration::kVerify) {
748
612
    ArrayBufferOrViewContents<char> signature(args[offset + 6]);
749
204
    if (UNLIKELY(!signature.CheckSizeInt32())) {
750
      THROW_ERR_OUT_OF_RANGE(env, "signature is too big");
751
      return Nothing<bool>();
752
    }
753
    // If this is an EC key (assuming ECDSA) we need to convert the
754
    // the signature from WebCrypto format into DER format...
755
408
    ManagedEVPPKey m_pkey = params->key->GetAsymmetricKey();
756
408
    Mutex::ScopedLock lock(*m_pkey.mutex());
757
204
    if (EVP_PKEY_id(m_pkey.get()) == EVP_PKEY_EC) {
758
      params->signature =
759
65
          ConvertFromWebCryptoSignature(m_pkey, signature.ToByteSource());
760
    } else {
761
      params->signature = mode == kCryptoJobAsync
762
278
          ? signature.ToCopy()
763
139
          : signature.ToByteSource();
764
    }
765
  }
766
767
264
  return Just(true);
768
}
769
770
264
bool SignTraits::DeriveBits(
771
    Environment* env,
772
    const SignConfiguration& params,
773
    ByteSource* out) {
774
528
  EVPMDPointer context(EVP_MD_CTX_new());
775
264
  EVP_PKEY_CTX* ctx = nullptr;
776
777
528
  ManagedEVPPKey m_pkey = params.key->GetAsymmetricKey();
778
528
  Mutex::ScopedLock lock(*m_pkey.mutex());
779
264
  switch (params.mode) {
780
    case SignConfiguration::kSign:
781
60
      CHECK_EQ(params.key->GetKeyType(), kKeyTypePrivate);
782
120
      if (!EVP_DigestSignInit(
783
              context.get(),
784
              &ctx,
785
60
              params.digest,
786
              nullptr,
787
              m_pkey.get())) {
788
        return false;
789
      }
790
60
      break;
791
    case SignConfiguration::kVerify:
792
204
      CHECK_EQ(params.key->GetKeyType(), kKeyTypePublic);
793
408
      if (!EVP_DigestVerifyInit(
794
              context.get(),
795
              &ctx,
796
204
              params.digest,
797
              nullptr,
798
              m_pkey.get())) {
799
        return false;
800
      }
801
204
      break;
802
  }
803
804
264
  int padding = params.flags & SignConfiguration::kHasPadding
805
264
      ? params.padding
806
264
      : GetDefaultSignPadding(m_pkey);
807
808
264
  Maybe<int> salt_length = params.flags & SignConfiguration::kHasSaltLength
809
264
      ? Just<int>(params.salt_length) : Nothing<int>();
810
811
264
  if (!ApplyRSAOptions(
812
          m_pkey,
813
          ctx,
814
          padding,
815
          salt_length)) {
816
    return false;
817
  }
818
819
264
  switch (params.mode) {
820
    case SignConfiguration::kSign: {
821
      size_t len;
822
60
      unsigned char* data = nullptr;
823
60
      if (IsOneShot(params.key->GetAsymmetricKey())) {
824
9
        EVP_DigestSign(
825
            context.get(),
826
            nullptr,
827
            &len,
828
            params.data.data<unsigned char>(),
829
9
            params.data.size());
830
9
        data = MallocOpenSSL<unsigned char>(len);
831
9
        EVP_DigestSign(
832
            context.get(),
833
            data,
834
            &len,
835
            params.data.data<unsigned char>(),
836
9
            params.data.size());
837
        ByteSource buf =
838
18
            ByteSource::Allocated(reinterpret_cast<char*>(data), len);
839
9
        *out = std::move(buf);
840
      } else {
841
102
        if (!EVP_DigestSignUpdate(
842
                context.get(),
843
                params.data.data<unsigned char>(),
844

102
                params.data.size()) ||
845
51
            !EVP_DigestSignFinal(context.get(), nullptr, &len)) {
846
          return false;
847
        }
848
51
        data = MallocOpenSSL<unsigned char>(len);
849
        ByteSource buf =
850
102
            ByteSource::Allocated(reinterpret_cast<char*>(data), len);
851
51
        if (!EVP_DigestSignFinal(context.get(), data, &len))
852
          return false;
853
854
        // If this is an EC key (assuming ECDSA) we have to
855
        // convert the signature in to the proper format.
856
51
        if (EVP_PKEY_id(params.key->GetAsymmetricKey().get()) == EVP_PKEY_EC) {
857
34
          *out = ConvertToWebCryptoSignature(
858
51
              params.key->GetAsymmetricKey(), buf);
859
        } else {
860
34
          buf.Resize(len);
861
34
          *out = std::move(buf);
862
        }
863
      }
864
60
      break;
865
    }
866
    case SignConfiguration::kVerify: {
867
204
      char* data = MallocOpenSSL<char>(1);
868
204
      data[0] = 0;
869
204
      *out = ByteSource::Allocated(data, 1);
870
204
      if (EVP_DigestVerify(
871
              context.get(),
872
              params.signature.data<unsigned char>(),
873
              params.signature.size(),
874
              params.data.data<unsigned char>(),
875
              params.data.size()) == 1) {
876
108
        data[0] = 1;
877
      }
878
    }
879
  }
880
881
264
  return true;
882
}
883
884
264
Maybe<bool> SignTraits::EncodeOutput(
885
    Environment* env,
886
    const SignConfiguration& params,
887
    ByteSource* out,
888
    Local<Value>* result) {
889
264
  switch (params.mode) {
890
    case SignConfiguration::kSign:
891
120
      *result = out->ToArrayBuffer(env);
892
60
      break;
893
    case SignConfiguration::kVerify:
894
408
      *result = out->get()[0] == 1
895
108
          ? v8::True(env->isolate())
896
504
          : v8::False(env->isolate());
897
204
      break;
898
    default:
899
      UNREACHABLE();
900
  }
901
264
  return Just(!result->IsEmpty());
902
}
903
904
}  // namespace crypto
905

14097
}  // namespace node