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_cipher.cc Lines: 448 492 91.1 %
Date: 2021-04-25 04:11:48 Branches: 435 619 70.3 %

Line Branch Exec Source
1
#include "crypto/crypto_cipher.h"
2
#include "crypto/crypto_util.h"
3
#include "allocated_buffer-inl.h"
4
#include "base_object-inl.h"
5
#include "env-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node_buffer.h"
8
#include "node_internals.h"
9
#include "node_process.h"
10
#include "v8.h"
11
12
namespace node {
13
14
using v8::Array;
15
using v8::FunctionCallbackInfo;
16
using v8::FunctionTemplate;
17
using v8::HandleScope;
18
using v8::Int32;
19
using v8::Local;
20
using v8::Object;
21
using v8::Uint32;
22
using v8::Value;
23
24
namespace crypto {
25
#ifdef OPENSSL_NO_OCB
26
# define IS_OCB_MODE(mode) false
27
#else
28
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
29
#endif
30
31
namespace {
32
3365
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
33
3365
  const int mode = EVP_CIPHER_mode(cipher);
34
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
35
  // but its mode is 0 which doesn't indicate
36
6687
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
37
6011
         mode == EVP_CIPH_CCM_MODE ||
38

7360
         mode == EVP_CIPH_GCM_MODE ||
39
4671
         IS_OCB_MODE(mode);
40
}
41
42
1485
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
43
1485
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
44
1485
  return IsSupportedAuthenticatedMode(cipher);
45
}
46
47
66
bool IsValidGCMTagLength(unsigned int tag_len) {
48


66
  return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16);
49
}
50
51
// Collects and returns information on the given cipher
52
382
void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
53
382
  Environment* env = Environment::GetCurrent(args);
54
764
  CHECK(args[0]->IsObject());
55
764
  Local<Object> info = args[0].As<Object>();
56
57

1498
  CHECK(args[1]->IsString() || args[1]->IsInt32());
58
59
  const EVP_CIPHER* cipher;
60
1146
  if (args[1]->IsString()) {
61
412
    Utf8Value name(env->isolate(), args[1]);
62
206
    cipher = EVP_get_cipherbyname(*name);
63
  } else {
64
528
    int nid = args[1].As<Int32>()->Value();
65
176
    cipher = EVP_get_cipherbyname(OBJ_nid2sn(nid));
66
  }
67
68
382
  if (cipher == nullptr)
69
9
    return;
70
71
380
  int mode = EVP_CIPHER_mode(cipher);
72
380
  int iv_length = EVP_CIPHER_iv_length(cipher);
73
380
  int key_length = EVP_CIPHER_key_length(cipher);
74
380
  int block_length = EVP_CIPHER_block_size(cipher);
75
380
  const char* mode_label = nullptr;
76



380
  switch (mode) {
77
101
    case EVP_CIPH_CBC_MODE: mode_label = "cbc"; break;
78
27
    case EVP_CIPH_CCM_MODE: mode_label = "ccm"; break;
79
80
    case EVP_CIPH_CFB_MODE: mode_label = "cfb"; break;
80
20
    case EVP_CIPH_CTR_MODE: mode_label = "ctr"; break;
81
40
    case EVP_CIPH_ECB_MODE: mode_label = "ecb"; break;
82
18
    case EVP_CIPH_GCM_MODE: mode_label = "gcm"; break;
83
22
    case EVP_CIPH_OCB_MODE: mode_label = "ocb"; break;
84
36
    case EVP_CIPH_OFB_MODE: mode_label = "ofb"; break;
85
22
    case EVP_CIPH_WRAP_MODE: mode_label = "wrap"; break;
86
4
    case EVP_CIPH_XTS_MODE: mode_label = "xts"; break;
87
10
    case EVP_CIPH_STREAM_CIPHER: mode_label = "stream"; break;
88
  }
89
90
  // If the testKeyLen and testIvLen arguments are specified,
91
  // then we will make an attempt to see if they are usable for
92
  // the cipher in question, returning undefined if they are not.
93
  // If they are, the info object will be returned with the values
94
  // given.
95

1516
  if (args[2]->IsInt32() || args[3]->IsInt32()) {
96
    // Test and input IV or key length to determine if it's acceptable.
97
    // If it is, then the getCipherInfo will succeed with the given
98
    // values.
99
53
    CipherCtxPointer ctx(EVP_CIPHER_CTX_new());
100
29
    if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr, 1))
101
      return;
102
103
58
    if (args[2]->IsInt32()) {
104
6
      int check_len = args[2].As<Int32>()->Value();
105
2
      if (!EVP_CIPHER_CTX_set_key_length(ctx.get(), check_len))
106
1
        return;
107
1
      key_length = check_len;
108
    }
109
110
56
    if (args[3]->IsInt32()) {
111
81
      int check_len = args[3].As<Int32>()->Value();
112
      // For CCM modes, the IV may be between 7 and 13 bytes.
113
      // For GCM and OCB modes, we'll check by attempting to
114
      // set the value. For everything else, just check that
115
      // check_len == iv_length.
116
27
      switch (mode) {
117
        case EVP_CIPH_CCM_MODE:
118

9
          if (check_len < 7 || check_len > 13)
119
2
            return;
120
7
          break;
121
        case EVP_CIPH_GCM_MODE:
122
          // Fall through
123
        case EVP_CIPH_OCB_MODE:
124
16
          if (!EVP_CIPHER_CTX_ctrl(
125
                  ctx.get(),
126
                  EVP_CTRL_AEAD_SET_IVLEN,
127
                  check_len,
128
                  nullptr)) {
129
1
            return;
130
          }
131
15
          break;
132
        default:
133
2
          if (check_len != iv_length)
134
1
            return;
135
      }
136
23
      iv_length = check_len;
137
    }
138
  }
139
140

1125
  if (mode_label != nullptr &&
141
750
      info->Set(
142
          env->context(),
143
          FIXED_ONE_BYTE_STRING(env->isolate(), "mode"),
144
2250
          OneByteString(env->isolate(), mode_label)).IsNothing()) {
145
    return;
146
  }
147
148
1125
  if (info->Set(
149
          env->context(),
150
          env->name_string(),
151
1875
          OneByteString(env->isolate(), EVP_CIPHER_name(cipher))).IsNothing()) {
152
    return;
153
  }
154
155
1125
  if (info->Set(
156
          env->context(),
157
          FIXED_ONE_BYTE_STRING(env->isolate(), "nid"),
158
1875
          Int32::New(env->isolate(), EVP_CIPHER_nid(cipher))).IsNothing()) {
159
    return;
160
  }
161
162
  // Stream ciphers do not have a meaningful block size
163

1115
  if (mode != EVP_CIPH_STREAM_CIPHER &&
164
740
      info->Set(
165
          env->context(),
166
          FIXED_ONE_BYTE_STRING(env->isolate(), "blockSize"),
167
2200
          Int32::New(env->isolate(), block_length)).IsNothing()) {
168
    return;
169
  }
170
171
  // Ciphers that do not use an IV shouldn't report a length
172

1075
  if (iv_length != 0 &&
173
700
      info->Set(
174
          env->context(),
175
          FIXED_ONE_BYTE_STRING(env->isolate(), "ivLength"),
176
2000
          Int32::New(env->isolate(), iv_length)).IsNothing()) {
177
    return;
178
  }
179
180
1125
  if (info->Set(
181
          env->context(),
182
          FIXED_ONE_BYTE_STRING(env->isolate(), "keyLength"),
183
1875
          Int32::New(env->isolate(), key_length)).IsNothing()) {
184
    return;
185
  }
186
187
750
  args.GetReturnValue().Set(info);
188
}
189
}  // namespace
190
191
1
void CipherBase::GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
192
1
  Environment* env = Environment::GetCurrent(args);
193
194
2
  SSLCtxPointer ctx(SSL_CTX_new(TLS_method()));
195
1
  CHECK(ctx);
196
197
2
  SSLPointer ssl(SSL_new(ctx.get()));
198
1
  CHECK(ssl);
199
200
1
  STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl.get());
201
202
  // TLSv1.3 ciphers aren't listed by EVP. There are only 5, we could just
203
  // document them, but since there are only 5, easier to just add them manually
204
  // and not have to explain their absence in the API docs. They are lower-cased
205
  // because the docs say they will be.
206
  static const char* TLS13_CIPHERS[] = {
207
    "tls_aes_256_gcm_sha384",
208
    "tls_chacha20_poly1305_sha256",
209
    "tls_aes_128_gcm_sha256",
210
    "tls_aes_128_ccm_8_sha256",
211
    "tls_aes_128_ccm_sha256"
212
  };
213
214
1
  const int n = sk_SSL_CIPHER_num(ciphers);
215
2
  std::vector<Local<Value>> arr(n + arraysize(TLS13_CIPHERS));
216
217
61
  for (int i = 0; i < n; ++i) {
218
60
    const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
219
120
    arr[i] = OneByteString(env->isolate(), SSL_CIPHER_get_name(cipher));
220
  }
221
222
6
  for (unsigned i = 0; i < arraysize(TLS13_CIPHERS); ++i) {
223
5
    const char* name = TLS13_CIPHERS[i];
224
10
    arr[n + i] = OneByteString(env->isolate(), name);
225
  }
226
227
3
  args.GetReturnValue().Set(Array::New(env->isolate(), arr.data(), arr.size()));
228
1
}
229
230
3
void CipherBase::GetCiphers(const FunctionCallbackInfo<Value>& args) {
231
3
  Environment* env = Environment::GetCurrent(args);
232
6
  CipherPushContext ctx(env);
233
3
  EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &ctx);
234
9
  args.GetReturnValue().Set(ctx.ToJSArray());
235
3
}
236
237
1273
CipherBase::CipherBase(Environment* env,
238
                       Local<Object> wrap,
239
1273
                       CipherKind kind)
240
    : BaseObject(env, wrap),
241
      ctx_(nullptr),
242
      kind_(kind),
243
      auth_tag_state_(kAuthTagUnknown),
244
      auth_tag_len_(kNoAuthTagLength),
245
1273
      pending_auth_failed_(false) {
246
1273
  MakeWeak();
247
1273
}
248
249
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
250
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
251
}
252
253
4100
void CipherBase::Initialize(Environment* env, Local<Object> target) {
254
4100
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
255
256
12300
  t->InstanceTemplate()->SetInternalFieldCount(
257
4100
      CipherBase::kInternalFieldCount);
258
8200
  t->Inherit(BaseObject::GetConstructorTemplate(env));
259
260
4100
  env->SetProtoMethod(t, "init", Init);
261
4100
  env->SetProtoMethod(t, "initiv", InitIv);
262
4100
  env->SetProtoMethod(t, "update", Update);
263
4100
  env->SetProtoMethod(t, "final", Final);
264
4100
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
265
4100
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
266
4100
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
267
4100
  env->SetProtoMethod(t, "setAAD", SetAAD);
268
4100
  env->SetConstructorFunction(target, "CipherBase", t);
269
270
4100
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
271
4100
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
272
273
  env->SetMethod(target, "publicEncrypt",
274
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
275
                                         EVP_PKEY_encrypt_init,
276
4100
                                         EVP_PKEY_encrypt>);
277
  env->SetMethod(target, "privateDecrypt",
278
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
279
                                         EVP_PKEY_decrypt_init,
280
4100
                                         EVP_PKEY_decrypt>);
281
  env->SetMethod(target, "privateEncrypt",
282
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
283
                                         EVP_PKEY_sign_init,
284
4100
                                         EVP_PKEY_sign>);
285
  env->SetMethod(target, "publicDecrypt",
286
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
287
                                         EVP_PKEY_verify_recover_init,
288
4100
                                         EVP_PKEY_verify_recover>);
289
290
4100
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
291
292
8200
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
293
4100
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
294
12300
}
295
8200
296
13573
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
297
9473
  CHECK(args.IsConstructCall());
298
1273
  Environment* env = Environment::GetCurrent(args);
299
3819
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
300
1273
}
301
302
697
void CipherBase::CommonInit(const char* cipher_type,
303
                            const EVP_CIPHER* cipher,
304
                            const unsigned char* key,
305
                            int key_len,
306
                            const unsigned char* iv,
307
                            int iv_len,
308
                            unsigned int auth_tag_len) {
309
697
  CHECK(!ctx_);
310
697
  ctx_.reset(EVP_CIPHER_CTX_new());
311
312
697
  const int mode = EVP_CIPHER_mode(cipher);
313
697
  if (mode == EVP_CIPH_WRAP_MODE)
314
18
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
315
316
697
  const bool encrypt = (kind_ == kCipher);
317
697
  if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr,
318
                             nullptr, nullptr, encrypt)) {
319
    return ThrowCryptoError(env(), ERR_get_error(),
320
                            "Failed to initialize cipher");
321
  }
322
323
697
  if (IsSupportedAuthenticatedMode(cipher)) {
324
576
    CHECK_GE(iv_len, 0);
325
576
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
326
72
      return;
327
  }
328
329
625
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
330
1
    ctx_.reset();
331
1
    return THROW_ERR_CRYPTO_INVALID_KEYLEN(env());
332
  }
333
334
624
  if (1 != EVP_CipherInit_ex(ctx_.get(), nullptr, nullptr, key, iv, encrypt)) {
335
    return ThrowCryptoError(env(), ERR_get_error(),
336
                            "Failed to initialize cipher");
337
  }
338
}
339
340
89
void CipherBase::Init(const char* cipher_type,
341
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
342
                      unsigned int auth_tag_len) {
343
178
  HandleScope scope(env()->isolate());
344
178
  MarkPopErrorOnReturn mark_pop_error_on_return;
345
#if OPENSSL_VERSION_MAJOR >= 3
346
  if (EVP_default_properties_is_fips_enabled(nullptr)) {
347
#else
348
89
  if (FIPS_mode()) {
349
#endif
350
    return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
351
        "crypto.createCipher() is not supported in FIPS mode.");
352
  }
353
354
89
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
355
89
  if (cipher == nullptr)
356
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
357
358
  unsigned char key[EVP_MAX_KEY_LENGTH];
359
  unsigned char iv[EVP_MAX_IV_LENGTH];
360
361
89
  int key_len = EVP_BytesToKey(cipher,
362
                               EVP_md5(),
363
                               nullptr,
364
                               key_buf.data(),
365
89
                               key_buf.size(),
366
                               1,
367
                               key,
368
89
                               iv);
369
89
  CHECK_NE(key_len, 0);
370
371
89
  const int mode = EVP_CIPHER_mode(cipher);
372

89
  if (kind_ == kCipher && (mode == EVP_CIPH_CTR_MODE ||
373
43
                           mode == EVP_CIPH_GCM_MODE ||
374
                           mode == EVP_CIPH_CCM_MODE)) {
375
    // Ignore the return value (i.e. possible exception) because we are
376
    // not calling back into JS anyway.
377
    ProcessEmitWarning(env(),
378
                       "Use Cipheriv for counter mode of %s",
379
24
                       cipher_type);
380
  }
381
382
89
  CommonInit(cipher_type, cipher, key, key_len, iv,
383
89
             EVP_CIPHER_iv_length(cipher), auth_tag_len);
384
}
385
386
89
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
387
  CipherBase* cipher;
388
89
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
389
89
  Environment* env = Environment::GetCurrent(args);
390
391
89
  CHECK_GE(args.Length(), 3);
392
393
178
  const Utf8Value cipher_type(args.GetIsolate(), args[0]);
394
178
  ArrayBufferOrViewContents<unsigned char> key_buf(args[1]);
395
89
  if (!key_buf.CheckSizeInt32())
396
    return THROW_ERR_OUT_OF_RANGE(env, "password is too large");
397
398
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
399
  // represent a valid length at this point.
400
  unsigned int auth_tag_len;
401
178
  if (args[2]->IsUint32()) {
402
105
    auth_tag_len = args[2].As<Uint32>()->Value();
403
  } else {
404

270
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
405
54
    auth_tag_len = kNoAuthTagLength;
406
  }
407
408
89
  cipher->Init(*cipher_type, key_buf, auth_tag_len);
409
}
410
411
1184
void CipherBase::InitIv(const char* cipher_type,
412
                        const ByteSource& key_buf,
413
                        const ArrayBufferOrViewContents<unsigned char>& iv_buf,
414
                        unsigned int auth_tag_len) {
415
1792
  HandleScope scope(env()->isolate());
416
1792
  MarkPopErrorOnReturn mark_pop_error_on_return;
417
418
1184
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
419
1184
  if (cipher == nullptr)
420
1
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
421
422
1183
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
423
1183
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
424
1183
  const bool has_iv = iv_buf.size() > 0;
425
426
  // Throw if no IV was passed and the cipher requires an IV
427

1183
  if (!has_iv && expected_iv_len != 0)
428
61
    return THROW_ERR_CRYPTO_INVALID_IV(env());
429
430
  // Throw if an IV was passed which does not match the cipher's fixed IV length
431
  // static_cast<int> for the iv_buf.size() is safe because we've verified
432
  // prior that the value is not larger than MAX_INT.
433

2832
  if (!is_authenticated_mode &&
434

1699
      has_iv &&
435
577
      static_cast<int>(iv_buf.size()) != expected_iv_len) {
436
509
    return THROW_ERR_CRYPTO_INVALID_IV(env());
437
  }
438
439
613
  if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305) {
440
11
    CHECK(has_iv);
441
    // Check for invalid IV lengths, since OpenSSL does not under some
442
    // conditions:
443
    //   https://www.openssl.org/news/secadv/20190306.txt.
444
11
    if (iv_buf.size() > 12)
445
5
      return THROW_ERR_CRYPTO_INVALID_IV(env());
446
  }
447
448
1216
  CommonInit(
449
      cipher_type,
450
      cipher,
451
      key_buf.data<unsigned char>(),
452
608
      key_buf.size(),
453
      iv_buf.data(),
454
608
      iv_buf.size(),
455
608
      auth_tag_len);
456
}
457
458
1184
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
459
  CipherBase* cipher;
460
1184
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
461
1184
  Environment* env = cipher->env();
462
463
1184
  CHECK_GE(args.Length(), 4);
464
465
2368
  const Utf8Value cipher_type(env->isolate(), args[0]);
466
467
  // The argument can either be a KeyObjectHandle or a byte source
468
  // (e.g. ArrayBuffer, TypedArray, etc). Whichever it is, grab the
469
  // raw bytes and proceed...
470
2368
  const ByteSource key_buf = ByteSource::FromSecretKeyBytes(env, args[1]);
471
472
1184
  if (UNLIKELY(key_buf.size() > INT_MAX))
473
    return THROW_ERR_OUT_OF_RANGE(env, "key is too big");
474
475
2368
  ArrayBufferOrViewContents<unsigned char> iv_buf;
476
3552
  if (!args[2]->IsNull())
477
1178
    iv_buf = ArrayBufferOrViewContents<unsigned char>(args[2]);
478
479
1184
  if (UNLIKELY(!iv_buf.CheckSizeInt32()))
480
    return THROW_ERR_OUT_OF_RANGE(env, "iv is too big");
481
482
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
483
  // represent a valid length at this point.
484
  unsigned int auth_tag_len;
485
2368
  if (args[3]->IsUint32()) {
486
564
    auth_tag_len = args[3].As<Uint32>()->Value();
487
  } else {
488

4980
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
489
996
    auth_tag_len = kNoAuthTagLength;
490
  }
491
492
1184
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
493
}
494
495
576
bool CipherBase::InitAuthenticated(
496
    const char* cipher_type,
497
    int iv_len,
498
    unsigned int auth_tag_len) {
499
576
  CHECK(IsAuthenticatedMode());
500
1152
  MarkPopErrorOnReturn mark_pop_error_on_return;
501
502
576
  if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
503
                           EVP_CTRL_AEAD_SET_IVLEN,
504
                           iv_len,
505
                           nullptr)) {
506
    THROW_ERR_CRYPTO_INVALID_IV(env());
507
    return false;
508
  }
509
510
576
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
511
576
  if (mode == EVP_CIPH_GCM_MODE) {
512
374
    if (auth_tag_len != kNoAuthTagLength) {
513
24
      if (!IsValidGCMTagLength(auth_tag_len)) {
514
16
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
515
          env(),
516
          "Invalid authentication tag length: %u",
517
16
          auth_tag_len);
518
16
        return false;
519
      }
520
521
      // Remember the given authentication tag length for later.
522
8
      auth_tag_len_ = auth_tag_len;
523
    }
524
  } else {
525
202
    if (auth_tag_len == kNoAuthTagLength) {
526
8
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
527
8
        env(), "authTagLength required for %s", cipher_type);
528
8
      return false;
529
    }
530
531
    // TODO(tniessen) Support CCM decryption in FIPS mode
532
533
#if OPENSSL_VERSION_MAJOR >= 3
534
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher &&
535
        EVP_default_properties_is_fips_enabled(nullptr)) {
536
#else
537


194
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
538
#endif
539
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
540
          "CCM encryption not supported in FIPS mode");
541
      return false;
542
    }
543
544
    // Tell OpenSSL about the desired length.
545
194
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
546
                             nullptr)) {
547
48
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env());
548
48
      return false;
549
    }
550
551
    // Remember the given authentication tag length for later.
552
146
    auth_tag_len_ = auth_tag_len;
553
554
146
    if (mode == EVP_CIPH_CCM_MODE) {
555
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
556

81
      CHECK(iv_len >= 7 && iv_len <= 13);
557
81
      max_message_size_ = INT_MAX;
558
81
      if (iv_len == 12) max_message_size_ = 16777215;
559
81
      if (iv_len == 13) max_message_size_ = 65535;
560
    }
561
  }
562
563
504
  return true;
564
}
565
566
127
bool CipherBase::CheckCCMMessageLength(int message_len) {
567
127
  CHECK(ctx_);
568
127
  CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE);
569
570
127
  if (message_len > max_message_size_) {
571
4
    THROW_ERR_CRYPTO_INVALID_MESSAGELEN(env());
572
4
    return false;
573
  }
574
575
123
  return true;
576
}
577
578
1306
bool CipherBase::IsAuthenticatedMode() const {
579
  // Check if this cipher operates in an AEAD mode that we support.
580
1306
  CHECK(ctx_);
581
1306
  return IsSupportedAuthenticatedMode(ctx_.get());
582
}
583
584
145
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
585
145
  Environment* env = Environment::GetCurrent(args);
586
  CipherBase* cipher;
587
205
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
588
589
  // Only callable after Final and if encrypting.
590

376
  if (cipher->ctx_ ||
591

231
      cipher->kind_ != kCipher ||
592
86
      cipher->auth_tag_len_ == kNoAuthTagLength) {
593
60
    return;
594
  }
595
596
255
  args.GetReturnValue().Set(
597
170
      Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
598
          .FromMaybe(Local<Value>()));
599
}
600
601
98
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
602
  CipherBase* cipher;
603
111
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
604
98
  Environment* env = Environment::GetCurrent(args);
605
606

293
  if (!cipher->ctx_ ||
607
194
      !cipher->IsAuthenticatedMode() ||
608

292
      cipher->kind_ != kDecipher ||
609
97
      cipher->auth_tag_state_ != kAuthTagUnknown) {
610
8
    return args.GetReturnValue().Set(false);
611
  }
612
613
179
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
614
94
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
615
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
616
617
94
  unsigned int tag_len = auth_tag.size();
618
619
94
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
620
  bool is_valid;
621
94
  if (mode == EVP_CIPH_GCM_MODE) {
622
    // Restrict GCM tag lengths according to NIST 800-38d, page 9.
623
91
    is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
624

85
                cipher->auth_tag_len_ == tag_len) &&
625
42
               IsValidGCMTagLength(tag_len);
626
  } else {
627
    // At this point, the tag length is already known and must match the
628
    // length of the given authentication tag.
629
51
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
630
51
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
631
51
    is_valid = cipher->auth_tag_len_ == tag_len;
632
  }
633
634
94
  if (!is_valid) {
635
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
636
9
      env, "Invalid authentication tag length: %u", tag_len);
637
  }
638
639
85
  cipher->auth_tag_len_ = tag_len;
640
85
  cipher->auth_tag_state_ = kAuthTagKnown;
641
85
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
642
643
85
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
644
85
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
645
646
170
  args.GetReturnValue().Set(true);
647
}
648
649
196
bool CipherBase::MaybePassAuthTagToOpenSSL() {
650
196
  if (auth_tag_state_ == kAuthTagKnown) {
651
168
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
652
                             EVP_CTRL_AEAD_SET_TAG,
653
84
                             auth_tag_len_,
654
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
655
      return false;
656
    }
657
84
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
658
  }
659
196
  return true;
660
}
661
662
118
bool CipherBase::SetAAD(
663
    const ArrayBufferOrViewContents<unsigned char>& data,
664
    int plaintext_len) {
665

118
  if (!ctx_ || !IsAuthenticatedMode())
666
2
    return false;
667
232
  MarkPopErrorOnReturn mark_pop_error_on_return;
668
669
  int outlen;
670
116
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
671
672
  // When in CCM mode, we need to set the authentication tag and the plaintext
673
  // length in advance.
674
116
  if (mode == EVP_CIPH_CCM_MODE) {
675
55
    if (plaintext_len < 0) {
676
2
      THROW_ERR_MISSING_ARGS(env(),
677
2
          "options.plaintextLength required for CCM mode with AAD");
678
2
      return false;
679
    }
680
681
53
    if (!CheckCCMMessageLength(plaintext_len))
682
2
      return false;
683
684
51
    if (kind_ == kDecipher) {
685
26
      if (!MaybePassAuthTagToOpenSSL())
686
        return false;
687
    }
688
689
    // Specify the plaintext length.
690
51
    if (!EVP_CipherUpdate(ctx_.get(), nullptr, &outlen, nullptr, plaintext_len))
691
      return false;
692
  }
693
694
112
  return 1 == EVP_CipherUpdate(ctx_.get(),
695
                               nullptr,
696
                               &outlen,
697
                               data.data(),
698
224
                               data.size());
699
}
700
701
118
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
702
  CipherBase* cipher;
703
118
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
704
118
  Environment* env = Environment::GetCurrent(args);
705
706
118
  CHECK_EQ(args.Length(), 2);
707
236
  CHECK(args[1]->IsInt32());
708
354
  int plaintext_len = args[1].As<Int32>()->Value();
709
236
  ArrayBufferOrViewContents<unsigned char> buf(args[0]);
710
711
118
  if (UNLIKELY(!buf.CheckSizeInt32()))
712
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
713
354
  args.GetReturnValue().Set(cipher->SetAAD(buf, plaintext_len));
714
}
715
716
330
CipherBase::UpdateResult CipherBase::Update(
717
    const char* data,
718
    size_t len,
719
    AllocatedBuffer* out) {
720

330
  if (!ctx_ || len > INT_MAX)
721
    return kErrorState;
722
660
  MarkPopErrorOnReturn mark_pop_error_on_return;
723
724
330
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
725
726

330
  if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
727
2
    return kErrorMessageSize;
728
729
  // Pass the authentication tag to OpenSSL if possible. This will only happen
730
  // once, usually on the first update.
731

328
  if (kind_ == kDecipher && IsAuthenticatedMode())
732
85
    CHECK(MaybePassAuthTagToOpenSSL());
733
734
328
  int buf_len = len + EVP_CIPHER_CTX_block_size(ctx_.get());
735
  // For key wrapping algorithms, get output size by calling
736
  // EVP_CipherUpdate() with null output.
737


337
  if (kind_ == kCipher && mode == EVP_CIPH_WRAP_MODE &&
738
9
      EVP_CipherUpdate(ctx_.get(),
739
                       nullptr,
740
                       &buf_len,
741
                       reinterpret_cast<const unsigned char*>(data),
742
                       len) != 1) {
743
    return kErrorState;
744
  }
745
746
328
  *out = AllocatedBuffer::AllocateManaged(env(), buf_len);
747
656
  int r = EVP_CipherUpdate(ctx_.get(),
748
328
                           reinterpret_cast<unsigned char*>(out->data()),
749
                           &buf_len,
750
                           reinterpret_cast<const unsigned char*>(data),
751
328
                           len);
752
753
328
  CHECK_LE(static_cast<size_t>(buf_len), out->size());
754
328
  out->Resize(buf_len);
755
756
  // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
757
  // invalid. In that case, remember the error and throw in final().
758

328
  if (!r && kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
759
5
    pending_auth_failed_ = true;
760
5
    return kSuccess;
761
  }
762
323
  return r == 1 ? kSuccess : kErrorState;
763
}
764
765
330
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
766
660
  Decode<CipherBase>(args, [](CipherBase* cipher,
767
                              const FunctionCallbackInfo<Value>& args,
768
990
                              const char* data, size_t size) {
769
658
    AllocatedBuffer out;
770
330
    Environment* env = Environment::GetCurrent(args);
771
772
330
    if (UNLIKELY(size > INT_MAX))
773
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
774
775
330
    UpdateResult r = cipher->Update(data, size, &out);
776
777
330
    if (r != kSuccess) {
778
2
      if (r == kErrorState) {
779
        ThrowCryptoError(env, ERR_get_error(),
780
                         "Trying to add data in unsupported state");
781
      }
782
2
      return;
783
    }
784
785

328
    CHECK(out.data() != nullptr || out.size() == 0);
786
984
    args.GetReturnValue().Set(out.ToBuffer().FromMaybe(Local<Value>()));
787
990
  });
788
330
}
789
790
18
bool CipherBase::SetAutoPadding(bool auto_padding) {
791
18
  if (!ctx_)
792
1
    return false;
793
34
  MarkPopErrorOnReturn mark_pop_error_on_return;
794
17
  return EVP_CIPHER_CTX_set_padding(ctx_.get(), auto_padding);
795
}
796
797
18
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
798
  CipherBase* cipher;
799
18
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
800
801

54
  bool b = cipher->SetAutoPadding(args.Length() < 1 || args[0]->IsTrue());
802
54
  args.GetReturnValue().Set(b);  // Possibly report invalid state failure
803
}
804
805
256
bool CipherBase::Final(AllocatedBuffer* out) {
806
256
  if (!ctx_)
807
    return false;
808
809
256
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
810
811
512
  *out = AllocatedBuffer::AllocateManaged(
812
      env(),
813
512
      static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
814
815

256
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get())) {
816
85
    MaybePassAuthTagToOpenSSL();
817
  }
818
819
  // In CCM mode, final() only checks whether authentication failed in update().
820
  // EVP_CipherFinal_ex must not be called and will fail.
821
  bool ok;
822

256
  if (kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
823
29
    ok = !pending_auth_failed_;
824
29
    *out = AllocatedBuffer::AllocateManaged(env(), 0);  // Empty buffer.
825
  } else {
826
227
    int out_len = out->size();
827
227
    ok = EVP_CipherFinal_ex(ctx_.get(),
828
227
                            reinterpret_cast<unsigned char*>(out->data()),
829
                            &out_len) == 1;
830
831
227
    if (out_len >= 0)
832
227
      out->Resize(out_len);
833
    else
834
      *out = AllocatedBuffer();  // *out will not be used.
835
836


227
    if (ok && kind_ == kCipher && IsAuthenticatedMode()) {
837
      // In GCM mode, the authentication tag length can be specified in advance,
838
      // but defaults to 16 bytes when encrypting. In CCM and OCB mode, it must
839
      // always be given by the user.
840
85
      if (auth_tag_len_ == kNoAuthTagLength) {
841
30
        CHECK(mode == EVP_CIPH_GCM_MODE);
842
30
        auth_tag_len_ = sizeof(auth_tag_);
843
      }
844
170
      ok = (1 == EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG,
845
85
                     auth_tag_len_,
846
                     reinterpret_cast<unsigned char*>(auth_tag_)));
847
    }
848
  }
849
850
256
  ctx_.reset();
851
852
256
  return ok;
853
}
854
855
260
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
856
260
  Environment* env = Environment::GetCurrent(args);
857
858
  CipherBase* cipher;
859
281
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
860
260
  if (cipher->ctx_ == nullptr)
861
4
    return THROW_ERR_CRYPTO_INVALID_STATE(env);
862
863
495
  AllocatedBuffer out;
864
865
  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
866
256
  const bool is_auth_mode = cipher->IsAuthenticatedMode();
867
256
  bool r = cipher->Final(&out);
868
869
256
  if (!r) {
870
    const char* msg = is_auth_mode
871
17
                          ? "Unsupported state or unable to authenticate data"
872
17
                          : "Unsupported state";
873
874
17
    return ThrowCryptoError(env, ERR_get_error(), msg);
875
  }
876
877
717
  args.GetReturnValue().Set(out.ToBuffer().FromMaybe(Local<Value>()));
878
}
879
880
template <PublicKeyCipher::Operation operation,
881
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
882
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
883
158
bool PublicKeyCipher::Cipher(
884
    Environment* env,
885
    const ManagedEVPPKey& pkey,
886
    int padding,
887
    const EVP_MD* digest,
888
    const ArrayBufferOrViewContents<unsigned char>& oaep_label,
889
    const ArrayBufferOrViewContents<unsigned char>& data,
890
    AllocatedBuffer* out) {
891
316
  EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
892


158
  if (!ctx)
893
    return false;
894


158
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
895
1
    return false;
896


157
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
897
    return false;
898
899


157
  if (digest != nullptr) {
900


21
    if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), digest) <= 0)
901
      return false;
902
  }
903
904


157
  if (oaep_label.size() != 0) {
905
    // OpenSSL takes ownership of the label, so we need to create a copy.
906
4
    void* label = OPENSSL_memdup(oaep_label.data(), oaep_label.size());
907


4
    CHECK_NOT_NULL(label);
908


4
    if (0 >= EVP_PKEY_CTX_set0_rsa_oaep_label(ctx.get(),
909
                reinterpret_cast<unsigned char*>(label),
910
                                      oaep_label.size())) {
911
      OPENSSL_free(label);
912
      return false;
913
    }
914
  }
915
916
157
  size_t out_len = 0;
917


157
  if (EVP_PKEY_cipher(
918
          ctx.get(),
919
          nullptr,
920
          &out_len,
921
          data.data(),
922
          data.size()) <= 0) {
923
    return false;
924
  }
925
926
157
  *out = AllocatedBuffer::AllocateManaged(env, out_len);
927
928


314
  if (EVP_PKEY_cipher(
929
          ctx.get(),
930
157
          reinterpret_cast<unsigned char*>(out->data()),
931
          &out_len,
932
          data.data(),
933
          data.size()) <= 0) {
934
1
    return false;
935
  }
936
937
156
  out->Resize(out_len);
938
156
  return true;
939
}
940
941
template <PublicKeyCipher::Operation operation,
942
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
943
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
944
164
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
945
320
  MarkPopErrorOnReturn mark_pop_error_on_return;
946
164
  Environment* env = Environment::GetCurrent(args);
947
948
164
  unsigned int offset = 0;
949
  ManagedEVPPKey pkey =
950


320
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
951


164
  if (!pkey)
952
4
    return;
953
954


476
  ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
955


160
  if (UNLIKELY(!buf.CheckSizeInt32()))
956
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
957
958
  uint32_t padding;
959


640
  if (!args[offset + 1]->Uint32Value(env->context()).To(&padding)) return;
960
961
160
  const EVP_MD* digest = nullptr;
962


640
  if (args[offset + 2]->IsString()) {
963
67
    const Utf8Value oaep_str(env->isolate(), args[offset + 2]);
964
23
    digest = EVP_get_digestbyname(*oaep_str);
965


23
    if (digest == nullptr)
966


2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
967
  }
968
969


314
  ArrayBufferOrViewContents<unsigned char> oaep_label;
970


632
  if (!args[offset + 3]->IsUndefined()) {
971
8
    oaep_label = ArrayBufferOrViewContents<unsigned char>(args[offset + 3]);
972


4
    if (UNLIKELY(!oaep_label.CheckSizeInt32()))
973
      return THROW_ERR_OUT_OF_RANGE(env, "oaep_label is too big");
974
  }
975
976


314
  AllocatedBuffer out;
977


158
  if (!Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
978
          env, pkey, padding, digest, oaep_label, buf, &out)) {
979
2
    return ThrowCryptoError(env, ERR_get_error());
980
  }
981
982
  Local<Value> result;
983


312
  if (out.ToBuffer().ToLocal(&result))
984


312
    args.GetReturnValue().Set(result);
985
}
986
987
}  // namespace crypto
988

14316
}  // namespace node