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: 425 487 87.3 %
Date: 2021-01-16 04:10:54 Branches: 244 367 66.5 %

Line Branch Exec Source
1
#include "crypto/crypto_sig.h"
2
#include "crypto/crypto_ecdh.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
1485
bool ApplyRSAOptions(const ManagedEVPPKey& pkey,
52
                     EVP_PKEY_CTX* pkctx,
53
                     int padding,
54
                     const Maybe<int>& salt_len) {
55

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

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

2227
    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
1477
  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
1404
int GetDefaultSignPadding(const ManagedEVPPKey& key) {
100
1404
  return EVP_PKEY_id(key.get()) == EVP_PKEY_RSA_PSS ? RSA_PKCS1_PSS_PADDING :
101
1404
                                                      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
}  // namespace
227
228
728
SignBase::Error SignBase::Init(const char* sign_type) {
229
728
  CHECK_NULL(mdctx_);
230
  // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1
231
  // exposed through the public API.
232

1456
  if (strcmp(sign_type, "dss1") == 0 ||
233
728
      strcmp(sign_type, "DSS1") == 0) {
234
2
    sign_type = "SHA1";
235
  }
236
728
  const EVP_MD* md = EVP_get_digestbyname(sign_type);
237
728
  if (md == nullptr)
238
1
    return kSignUnknownDigest;
239
240
727
  mdctx_.reset(EVP_MD_CTX_new());
241

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

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

1164
  if (pkctx &&
446
1746
      EVP_PKEY_verify_init(pkctx.get()) > 0 &&
447

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

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

958
  if (!mdctx ||
630
479
      !EVP_DigestVerifyInit(mdctx.get(), &pkctx, md, nullptr, key.get())) {
631
    return crypto::CheckThrow(env, SignBase::Error::kSignInit);
632
  }
633
634
479
  if (!ApplyRSAOptions(key, pkctx, rsa_padding, rsa_salt_len))
635
    return crypto::CheckThrow(env, SignBase::Error::kSignPublicKey);
636
637
946
  ByteSource sig_bytes = ByteSource::Foreign(sig.data(), sig.size());
638
479
  if (dsa_sig_enc == kSigEncP1363) {
639
17
    sig_bytes = ConvertSignatureToDER(key, sig);
640
17
    if (!sig_bytes)
641
12
      return crypto::CheckThrow(env, SignBase::Error::kSignMalformedSignature);
642
  }
643
644
  bool verify_result;
645
934
  const int r = EVP_DigestVerify(
646
    mdctx.get(),
647
    sig_bytes.data<unsigned char>(),
648
    sig_bytes.size(),
649
467
    reinterpret_cast<const unsigned char*>(data.data()),
650
467
    data.size());
651
467
  switch (r) {
652
    case 1:
653
191
      verify_result = true;
654
191
      break;
655
    case 0:
656
276
      verify_result = false;
657
276
      break;
658
    default:
659
      return crypto::CheckThrow(env, SignBase::Error::kSignPublicKey);
660
  }
661
662
1401
  args.GetReturnValue().Set(verify_result);
663
}
664
665
246
SignConfiguration::SignConfiguration(SignConfiguration&& other) noexcept
666
246
    : job_mode(other.job_mode),
667
246
      mode(other.mode),
668
246
      key(std::move(other.key)),
669
246
      data(std::move(other.data)),
670
246
      signature(std::move(other.signature)),
671
246
      digest(other.digest),
672
246
      flags(other.flags),
673
246
      padding(other.padding),
674
2214
      salt_length(other.salt_length) {}
675
676
SignConfiguration& SignConfiguration::operator=(
677
    SignConfiguration&& other) noexcept {
678
  if (&other == this) return *this;
679
  this->~SignConfiguration();
680
  return *new (this) SignConfiguration(std::move(other));
681
}
682
683
void SignConfiguration::MemoryInfo(MemoryTracker* tracker) const {
684
  tracker->TrackField("key", key.get());
685
  if (job_mode == kCryptoJobAsync) {
686
    tracker->TrackFieldWithSize("data", data.size());
687
    tracker->TrackFieldWithSize("signature", signature.size());
688
  }
689
}
690
691
246
Maybe<bool> SignTraits::AdditionalConfig(
692
    CryptoJobMode mode,
693
    const FunctionCallbackInfo<Value>& args,
694
    unsigned int offset,
695
    SignConfiguration* params) {
696
246
  Environment* env = Environment::GetCurrent(args);
697
698
246
  params->job_mode = mode;
699
700
738
  CHECK(args[offset]->IsUint32());  // Sign Mode
701
738
  CHECK(args[offset + 1]->IsObject());  // Key
702
703
246
  params->mode =
704
1230
      static_cast<SignConfiguration::Mode>(args[offset].As<Uint32>()->Value());
705
706
  KeyObjectHandle* key;
707
492
  ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 1], Nothing<bool>());
708
246
  params->key = key->Data();
709
710
738
  ArrayBufferOrViewContents<char> data(args[offset + 2]);
711
246
  if (UNLIKELY(!data.CheckSizeInt32())) {
712
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
713
    return Nothing<bool>();
714
  }
715
  params->data = mode == kCryptoJobAsync
716
492
      ? data.ToCopy()
717
246
      : data.ToByteSource();
718
719
984
  if (args[offset + 3]->IsString()) {
720
738
    Utf8Value digest(env->isolate(), args[offset + 3]);
721
246
    params->digest = EVP_get_digestbyname(*digest);
722
246
    if (params->digest == nullptr) {
723
      THROW_ERR_CRYPTO_INVALID_DIGEST(env);
724
      return Nothing<bool>();
725
    }
726
  }
727
728
738
  if (args[offset + 4]->IsUint32()) {  // Salt length
729
82
    params->flags |= SignConfiguration::kHasSaltLength;
730
328
    params->salt_length = args[offset + 4].As<Uint32>()->Value();
731
  }
732
738
  if (args[offset + 5]->IsUint32()) {  // Padding
733
82
    params->flags |= SignConfiguration::kHasPadding;
734
328
    params->padding = args[offset + 5].As<Uint32>()->Value();
735
  }
736
737
246
  if (params->mode == SignConfiguration::kVerify) {
738
585
    ArrayBufferOrViewContents<char> signature(args[offset + 6]);
739
195
    if (UNLIKELY(!signature.CheckSizeInt32())) {
740
      THROW_ERR_OUT_OF_RANGE(env, "signature is too big");
741
      return Nothing<bool>();
742
    }
743
    // If this is an EC key (assuming ECDSA) we need to convert the
744
    // the signature from WebCrypto format into DER format...
745
195
    if (EVP_PKEY_id(params->key->GetAsymmetricKey().get()) == EVP_PKEY_EC) {
746
      params->signature =
747
130
          ConvertFromWebCryptoSignature(
748
130
              params->key->GetAsymmetricKey(),
749
195
              signature.ToByteSource());
750
    } else {
751
      params->signature = mode == kCryptoJobAsync
752

260
          ? signature.ToCopy()
753
130
          : signature.ToByteSource();
754
    }
755
  }
756
757
246
  return Just(true);
758
}
759
760
246
bool SignTraits::DeriveBits(
761
    Environment* env,
762
    const SignConfiguration& params,
763
    ByteSource* out) {
764
492
  EVPMDPointer context(EVP_MD_CTX_new());
765
246
  EVP_PKEY_CTX* ctx = nullptr;
766
767
246
  switch (params.mode) {
768
    case SignConfiguration::kSign:
769
51
      CHECK_EQ(params.key->GetKeyType(), kKeyTypePrivate);
770
153
      if (!EVP_DigestSignInit(
771
              context.get(),
772
              &ctx,
773
51
              params.digest,
774
              nullptr,
775
102
              params.key->GetAsymmetricKey().get())) {
776
        return false;
777
      }
778
51
      break;
779
    case SignConfiguration::kVerify:
780
195
      CHECK_EQ(params.key->GetKeyType(), kKeyTypePublic);
781
585
      if (!EVP_DigestVerifyInit(
782
              context.get(),
783
              &ctx,
784
195
              params.digest,
785
              nullptr,
786
390
              params.key->GetAsymmetricKey().get())) {
787
        return false;
788
      }
789
195
      break;
790
  }
791
792
246
  int padding = params.flags & SignConfiguration::kHasPadding
793
410
      ? params.padding
794
410
      : GetDefaultSignPadding(params.key->GetAsymmetricKey());
795
796
246
  Maybe<int> salt_length = params.flags & SignConfiguration::kHasSaltLength
797
246
      ? Just<int>(params.salt_length) : Nothing<int>();
798
799
737
  if (!ApplyRSAOptions(
800
492
          params.key->GetAsymmetricKey(),
801
          ctx,
802
          padding,
803
          salt_length)) {
804
    return false;
805
  }
806
807
246
  switch (params.mode) {
808
    case SignConfiguration::kSign: {
809
      size_t len;
810
102
      if (!EVP_DigestSignUpdate(
811
              context.get(),
812
              params.data.data<unsigned char>(),
813

102
              params.data.size()) ||
814
51
          !EVP_DigestSignFinal(context.get(), nullptr, &len)) {
815
        return false;
816
      }
817
51
      char* data = MallocOpenSSL<char>(len);
818
51
      ByteSource buf = ByteSource::Allocated(data, len);
819
51
      unsigned char* ptr = reinterpret_cast<unsigned char*>(data);
820
51
      if (!EVP_DigestSignFinal(context.get(), ptr, &len))
821
        return false;
822
823
      // If this is an EC key (assuming ECDSA) we have to
824
      // convert the signature in to the proper format.
825
51
      if (EVP_PKEY_id(params.key->GetAsymmetricKey().get()) == EVP_PKEY_EC) {
826
17
        *out = ConvertToWebCryptoSignature(params.key->GetAsymmetricKey(), buf);
827
      } else {
828
34
        buf.Resize(len);
829
34
        *out = std::move(buf);
830
      }
831
51
      break;
832
    }
833
    case SignConfiguration::kVerify: {
834
195
      char* data = MallocOpenSSL<char>(1);
835
195
      data[0] = 0;
836
195
      *out = ByteSource::Allocated(data, 1);
837
195
      if (!EVP_DigestVerifyUpdate(
838
              context.get(),
839
              params.data.data<unsigned char>(),
840
              params.data.size())) {
841
        return false;
842
      }
843
844
195
      if (EVP_DigestVerifyFinal(
845
              context.get(),
846
              params.signature.data<unsigned char>(),
847
              params.signature.size()) == 1) {
848
99
        data[0] = 1;
849
      }
850
    }
851
  }
852
853
246
  return true;
854
}
855
856
246
Maybe<bool> SignTraits::EncodeOutput(
857
    Environment* env,
858
    const SignConfiguration& params,
859
    ByteSource* out,
860
    Local<Value>* result) {
861
246
  switch (params.mode) {
862
    case SignConfiguration::kSign:
863
102
      *result = out->ToArrayBuffer(env);
864
51
      break;
865
    case SignConfiguration::kVerify:
866
390
      *result = out->get()[0] == 1
867
99
          ? v8::True(env->isolate())
868
486
          : v8::False(env->isolate());
869
195
      break;
870
    default:
871
      UNREACHABLE();
872
  }
873
246
  return Just(!result->IsEmpty());
874
}
875
876
}  // namespace crypto
877

13995
}  // namespace node