GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_cipher.cc Lines: 479 521 91.9 %
Date: 2022-02-06 04:14:03 Branches: 325 425 76.5 %

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-inl.h"
10
#include "v8.h"
11
12
namespace node {
13
14
using v8::Array;
15
using v8::ArrayBuffer;
16
using v8::BackingStore;
17
using v8::FunctionCallbackInfo;
18
using v8::FunctionTemplate;
19
using v8::HandleScope;
20
using v8::Int32;
21
using v8::Local;
22
using v8::Object;
23
using v8::Uint32;
24
using v8::Value;
25
26
namespace crypto {
27
#ifdef OPENSSL_NO_OCB
28
# define IS_OCB_MODE(mode) false
29
#else
30
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
31
#endif
32
33
namespace {
34
2759
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
35
2759
  const int mode = EVP_CIPHER_mode(cipher);
36
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
37
  // but its mode is 0 which doesn't indicate
38
2759
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
39
2716
         mode == EVP_CIPH_CCM_MODE ||
40

6772
         mode == EVP_CIPH_GCM_MODE ||
41
4056
         IS_OCB_MODE(mode);
42
}
43
44
1281
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
45
1281
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
46
1281
  return IsSupportedAuthenticatedMode(cipher);
47
}
48
49
66
bool IsValidGCMTagLength(unsigned int tag_len) {
50


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

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



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

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

9
          if (check_len < 7 || check_len > 13)
121
2
            return;
122
7
          break;
123
16
        case EVP_CIPH_GCM_MODE:
124
          // Fall through
125
        case EVP_CIPH_OCB_MODE:
126
16
          if (!EVP_CIPHER_CTX_ctrl(
127
                  ctx.get(),
128
                  EVP_CTRL_AEAD_SET_IVLEN,
129
                  check_len,
130
                  nullptr)) {
131
1
            return;
132
          }
133
15
          break;
134
2
        default:
135
2
          if (check_len != iv_length)
136
1
            return;
137
      }
138
23
      iv_length = check_len;
139
    }
140
  }
141
142
750
  if (mode_label != nullptr &&
143
375
      info->Set(
144
          env->context(),
145
          FIXED_ONE_BYTE_STRING(env->isolate(), "mode"),
146

1875
          OneByteString(env->isolate(), mode_label)).IsNothing()) {
147
    return;
148
  }
149
150
  // OBJ_nid2sn(EVP_CIPHER_nid(cipher)) is used here instead of
151
  // EVP_CIPHER_name(cipher) for compatibility with BoringSSL.
152
750
  if (info->Set(
153
          env->context(),
154
          env->name_string(),
155
          OneByteString(
156
            env->isolate(),
157
1500
            OBJ_nid2sn(EVP_CIPHER_nid(cipher)))).IsNothing()) {
158
    return;
159
  }
160
161
750
  if (info->Set(
162
          env->context(),
163
          FIXED_ONE_BYTE_STRING(env->isolate(), "nid"),
164
1500
          Int32::New(env->isolate(), EVP_CIPHER_nid(cipher))).IsNothing()) {
165
    return;
166
  }
167
168
  // Stream ciphers do not have a meaningful block size
169
740
  if (mode != EVP_CIPH_STREAM_CIPHER &&
170
375
      info->Set(
171
          env->context(),
172
          FIXED_ONE_BYTE_STRING(env->isolate(), "blockSize"),
173

1835
          Int32::New(env->isolate(), block_length)).IsNothing()) {
174
    return;
175
  }
176
177
  // Ciphers that do not use an IV shouldn't report a length
178
700
  if (iv_length != 0 &&
179
375
      info->Set(
180
          env->context(),
181
          FIXED_ONE_BYTE_STRING(env->isolate(), "ivLength"),
182

1675
          Int32::New(env->isolate(), iv_length)).IsNothing()) {
183
    return;
184
  }
185
186
750
  if (info->Set(
187
          env->context(),
188
          FIXED_ONE_BYTE_STRING(env->isolate(), "keyLength"),
189
1500
          Int32::New(env->isolate(), key_length)).IsNothing()) {
190
    return;
191
  }
192
193
750
  args.GetReturnValue().Set(info);
194
}
195
}  // namespace
196
197
1
void CipherBase::GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
198
1
  Environment* env = Environment::GetCurrent(args);
199
200
2
  SSLCtxPointer ctx(SSL_CTX_new(TLS_method()));
201
1
  CHECK(ctx);
202
203
2
  SSLPointer ssl(SSL_new(ctx.get()));
204
1
  CHECK(ssl);
205
206
1
  STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl.get());
207
208
  // TLSv1.3 ciphers aren't listed by EVP. There are only 5, we could just
209
  // document them, but since there are only 5, easier to just add them manually
210
  // and not have to explain their absence in the API docs. They are lower-cased
211
  // because the docs say they will be.
212
  static const char* TLS13_CIPHERS[] = {
213
    "tls_aes_256_gcm_sha384",
214
    "tls_chacha20_poly1305_sha256",
215
    "tls_aes_128_gcm_sha256",
216
    "tls_aes_128_ccm_8_sha256",
217
    "tls_aes_128_ccm_sha256"
218
  };
219
220
1
  const int n = sk_SSL_CIPHER_num(ciphers);
221
1
  std::vector<Local<Value>> arr(n + arraysize(TLS13_CIPHERS));
222
223
61
  for (int i = 0; i < n; ++i) {
224
60
    const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
225
120
    arr[i] = OneByteString(env->isolate(), SSL_CIPHER_get_name(cipher));
226
  }
227
228
6
  for (unsigned i = 0; i < arraysize(TLS13_CIPHERS); ++i) {
229
5
    const char* name = TLS13_CIPHERS[i];
230
10
    arr[n + i] = OneByteString(env->isolate(), name);
231
  }
232
233
2
  args.GetReturnValue().Set(Array::New(env->isolate(), arr.data(), arr.size()));
234
1
}
235
236
3
void CipherBase::GetCiphers(const FunctionCallbackInfo<Value>& args) {
237
3
  Environment* env = Environment::GetCurrent(args);
238
3
  CipherPushContext ctx(env);
239
3
  EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &ctx);
240
6
  args.GetReturnValue().Set(ctx.ToJSArray());
241
3
}
242
243
1072
CipherBase::CipherBase(Environment* env,
244
                       Local<Object> wrap,
245
1072
                       CipherKind kind)
246
    : BaseObject(env, wrap),
247
      ctx_(nullptr),
248
      kind_(kind),
249
      auth_tag_state_(kAuthTagUnknown),
250
      auth_tag_len_(kNoAuthTagLength),
251
1072
      pending_auth_failed_(false) {
252
1072
  MakeWeak();
253
1072
}
254
255
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
256
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
257
}
258
259
4373
void CipherBase::Initialize(Environment* env, Local<Object> target) {
260
4373
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
261
262
8746
  t->InstanceTemplate()->SetInternalFieldCount(
263
      CipherBase::kInternalFieldCount);
264
4373
  t->Inherit(BaseObject::GetConstructorTemplate(env));
265
266
4373
  env->SetProtoMethod(t, "init", Init);
267
4373
  env->SetProtoMethod(t, "initiv", InitIv);
268
4373
  env->SetProtoMethod(t, "update", Update);
269
4373
  env->SetProtoMethod(t, "final", Final);
270
4373
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
271
4373
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
272
4373
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
273
4373
  env->SetProtoMethod(t, "setAAD", SetAAD);
274
4373
  env->SetConstructorFunction(target, "CipherBase", t);
275
276
4373
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
277
4373
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
278
279
4373
  env->SetMethod(target, "publicEncrypt",
280
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
281
                                         EVP_PKEY_encrypt_init,
282
                                         EVP_PKEY_encrypt>);
283
4373
  env->SetMethod(target, "privateDecrypt",
284
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
285
                                         EVP_PKEY_decrypt_init,
286
                                         EVP_PKEY_decrypt>);
287
4373
  env->SetMethod(target, "privateEncrypt",
288
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
289
                                         EVP_PKEY_sign_init,
290
                                         EVP_PKEY_sign>);
291
4373
  env->SetMethod(target, "publicDecrypt",
292
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
293
                                         EVP_PKEY_verify_recover_init,
294
                                         EVP_PKEY_verify_recover>);
295
296
4373
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
297
298
13119
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
299
8746
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
300
4373
}
301
302
4930
void CipherBase::RegisterExternalReferences(
303
    ExternalReferenceRegistry* registry) {
304
4930
  registry->Register(New);
305
306
4930
  registry->Register(Init);
307
4930
  registry->Register(InitIv);
308
4930
  registry->Register(Update);
309
4930
  registry->Register(Final);
310
4930
  registry->Register(SetAutoPadding);
311
4930
  registry->Register(GetAuthTag);
312
4930
  registry->Register(SetAuthTag);
313
4930
  registry->Register(SetAAD);
314
315
4930
  registry->Register(GetSSLCiphers);
316
4930
  registry->Register(GetCiphers);
317
318
4930
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
319
                                             EVP_PKEY_encrypt_init,
320
                                             EVP_PKEY_encrypt>);
321
4930
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
322
                                             EVP_PKEY_decrypt_init,
323
                                             EVP_PKEY_decrypt>);
324
4930
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
325
                                             EVP_PKEY_sign_init,
326
                                             EVP_PKEY_sign>);
327
4930
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
328
                                             EVP_PKEY_verify_recover_init,
329
                                             EVP_PKEY_verify_recover>);
330
331
4930
  registry->Register(GetCipherInfo);
332
4930
}
333
334
1072
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
335
1072
  CHECK(args.IsConstructCall());
336
1072
  Environment* env = Environment::GetCurrent(args);
337

2144
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
338
1072
}
339
340
496
void CipherBase::CommonInit(const char* cipher_type,
341
                            const EVP_CIPHER* cipher,
342
                            const unsigned char* key,
343
                            int key_len,
344
                            const unsigned char* iv,
345
                            int iv_len,
346
                            unsigned int auth_tag_len) {
347
496
  CHECK(!ctx_);
348
496
  ctx_.reset(EVP_CIPHER_CTX_new());
349
350
496
  const int mode = EVP_CIPHER_mode(cipher);
351
496
  if (mode == EVP_CIPH_WRAP_MODE)
352
18
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
353
354
496
  const bool encrypt = (kind_ == kCipher);
355
496
  if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr,
356
                             nullptr, nullptr, encrypt)) {
357
    return ThrowCryptoError(env(), ERR_get_error(),
358
                            "Failed to initialize cipher");
359
  }
360
361
496
  if (IsSupportedAuthenticatedMode(cipher)) {
362
377
    CHECK_GE(iv_len, 0);
363
377
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
364
72
      return;
365
  }
366
367
424
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
368
1
    ctx_.reset();
369
1
    return THROW_ERR_CRYPTO_INVALID_KEYLEN(env());
370
  }
371
372
423
  if (1 != EVP_CipherInit_ex(ctx_.get(), nullptr, nullptr, key, iv, encrypt)) {
373
    return ThrowCryptoError(env(), ERR_get_error(),
374
                            "Failed to initialize cipher");
375
  }
376
}
377
378
89
void CipherBase::Init(const char* cipher_type,
379
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
380
                      unsigned int auth_tag_len) {
381
89
  HandleScope scope(env()->isolate());
382
89
  MarkPopErrorOnReturn mark_pop_error_on_return;
383
#if OPENSSL_VERSION_MAJOR >= 3
384
89
  if (EVP_default_properties_is_fips_enabled(nullptr)) {
385
#else
386
  if (FIPS_mode()) {
387
#endif
388
    return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
389
        "crypto.createCipher() is not supported in FIPS mode.");
390
  }
391
392
89
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
393
89
  if (cipher == nullptr)
394
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
395
396
  unsigned char key[EVP_MAX_KEY_LENGTH];
397
  unsigned char iv[EVP_MAX_IV_LENGTH];
398
399
89
  int key_len = EVP_BytesToKey(cipher,
400
                               EVP_md5(),
401
                               nullptr,
402
                               key_buf.data(),
403
89
                               key_buf.size(),
404
                               1,
405
                               key,
406
89
                               iv);
407
89
  CHECK_NE(key_len, 0);
408
409
89
  const int mode = EVP_CIPHER_mode(cipher);
410

89
  if (kind_ == kCipher && (mode == EVP_CIPH_CTR_MODE ||
411
43
                           mode == EVP_CIPH_GCM_MODE ||
412
                           mode == EVP_CIPH_CCM_MODE)) {
413
    // Ignore the return value (i.e. possible exception) because we are
414
    // not calling back into JS anyway.
415
    ProcessEmitWarning(env(),
416
                       "Use Cipheriv for counter mode of %s",
417
24
                       cipher_type);
418
  }
419
420
89
  CommonInit(cipher_type, cipher, key, key_len, iv,
421
             EVP_CIPHER_iv_length(cipher), auth_tag_len);
422
}
423
424
89
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
425
  CipherBase* cipher;
426
89
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
427
89
  Environment* env = Environment::GetCurrent(args);
428
429
89
  CHECK_GE(args.Length(), 3);
430
431
89
  const Utf8Value cipher_type(args.GetIsolate(), args[0]);
432
89
  ArrayBufferOrViewContents<unsigned char> key_buf(args[1]);
433
89
  if (!key_buf.CheckSizeInt32())
434
    return THROW_ERR_OUT_OF_RANGE(env, "password is too large");
435
436
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
437
  // represent a valid length at this point.
438
  unsigned int auth_tag_len;
439
89
  if (args[2]->IsUint32()) {
440
70
    auth_tag_len = args[2].As<Uint32>()->Value();
441
  } else {
442

162
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
443
54
    auth_tag_len = kNoAuthTagLength;
444
  }
445
446
89
  cipher->Init(*cipher_type, key_buf, auth_tag_len);
447
}
448
449
983
void CipherBase::InitIv(const char* cipher_type,
450
                        const ByteSource& key_buf,
451
                        const ArrayBufferOrViewContents<unsigned char>& iv_buf,
452
                        unsigned int auth_tag_len) {
453
983
  HandleScope scope(env()->isolate());
454
983
  MarkPopErrorOnReturn mark_pop_error_on_return;
455
456
983
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
457
983
  if (cipher == nullptr)
458
1
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
459
460
982
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
461
982
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
462
982
  const bool has_iv = iv_buf.size() > 0;
463
464
  // Throw if no IV was passed and the cipher requires an IV
465

982
  if (!has_iv && expected_iv_len != 0)
466
61
    return THROW_ERR_CRYPTO_INVALID_IV(env());
467
468
  // Throw if an IV was passed which does not match the cipher's fixed IV length
469
  // static_cast<int> for the iv_buf.size() is safe because we've verified
470
  // prior that the value is not larger than MAX_INT.
471
586
  if (!is_authenticated_mode &&
472

1507
      has_iv &&
473
577
      static_cast<int>(iv_buf.size()) != expected_iv_len) {
474
509
    return THROW_ERR_CRYPTO_INVALID_IV(env());
475
  }
476
477
412
  if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305) {
478
11
    CHECK(has_iv);
479
    // Check for invalid IV lengths, since OpenSSL does not under some
480
    // conditions:
481
    //   https://www.openssl.org/news/secadv/20190306.txt.
482
11
    if (iv_buf.size() > 12)
483
5
      return THROW_ERR_CRYPTO_INVALID_IV(env());
484
  }
485
486
814
  CommonInit(
487
      cipher_type,
488
      cipher,
489
      key_buf.data<unsigned char>(),
490
407
      key_buf.size(),
491
      iv_buf.data(),
492
407
      iv_buf.size(),
493
      auth_tag_len);
494
}
495
496
983
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
497
  CipherBase* cipher;
498
983
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
499
983
  Environment* env = cipher->env();
500
501
983
  CHECK_GE(args.Length(), 4);
502
503
983
  const Utf8Value cipher_type(env->isolate(), args[0]);
504
505
  // The argument can either be a KeyObjectHandle or a byte source
506
  // (e.g. ArrayBuffer, TypedArray, etc). Whichever it is, grab the
507
  // raw bytes and proceed...
508
983
  const ByteSource key_buf = ByteSource::FromSecretKeyBytes(env, args[1]);
509
510
983
  if (UNLIKELY(key_buf.size() > INT_MAX))
511
    return THROW_ERR_OUT_OF_RANGE(env, "key is too big");
512
513
983
  ArrayBufferOrViewContents<unsigned char> iv_buf;
514
1966
  if (!args[2]->IsNull())
515
977
    iv_buf = ArrayBufferOrViewContents<unsigned char>(args[2]);
516
517
983
  if (UNLIKELY(!iv_buf.CheckSizeInt32()))
518
    return THROW_ERR_OUT_OF_RANGE(env, "iv is too big");
519
520
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
521
  // represent a valid length at this point.
522
  unsigned int auth_tag_len;
523
983
  if (args[3]->IsUint32()) {
524
376
    auth_tag_len = args[3].As<Uint32>()->Value();
525
  } else {
526

2385
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
527
795
    auth_tag_len = kNoAuthTagLength;
528
  }
529
530
983
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
531
}
532
533
377
bool CipherBase::InitAuthenticated(
534
    const char* cipher_type,
535
    int iv_len,
536
    unsigned int auth_tag_len) {
537
377
  CHECK(IsAuthenticatedMode());
538
754
  MarkPopErrorOnReturn mark_pop_error_on_return;
539
540
377
  if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
541
                           EVP_CTRL_AEAD_SET_IVLEN,
542
                           iv_len,
543
                           nullptr)) {
544
    THROW_ERR_CRYPTO_INVALID_IV(env());
545
    return false;
546
  }
547
548
377
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
549
377
  if (mode == EVP_CIPH_GCM_MODE) {
550
175
    if (auth_tag_len != kNoAuthTagLength) {
551
24
      if (!IsValidGCMTagLength(auth_tag_len)) {
552
16
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
553
          env(),
554
          "Invalid authentication tag length: %u",
555
          auth_tag_len);
556
16
        return false;
557
      }
558
559
      // Remember the given authentication tag length for later.
560
8
      auth_tag_len_ = auth_tag_len;
561
    }
562
  } else {
563
202
    if (auth_tag_len == kNoAuthTagLength) {
564
8
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
565
        env(), "authTagLength required for %s", cipher_type);
566
8
      return false;
567
    }
568
569
    // TODO(tniessen) Support CCM decryption in FIPS mode
570
571
#if OPENSSL_VERSION_MAJOR >= 3
572


248
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher &&
573
54
        EVP_default_properties_is_fips_enabled(nullptr)) {
574
#else
575
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
576
#endif
577
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
578
          "CCM encryption not supported in FIPS mode");
579
      return false;
580
    }
581
582
    // Tell OpenSSL about the desired length.
583
194
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
584
                             nullptr)) {
585
48
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env());
586
48
      return false;
587
    }
588
589
    // Remember the given authentication tag length for later.
590
146
    auth_tag_len_ = auth_tag_len;
591
592
146
    if (mode == EVP_CIPH_CCM_MODE) {
593
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
594

81
      CHECK(iv_len >= 7 && iv_len <= 13);
595
81
      max_message_size_ = INT_MAX;
596
81
      if (iv_len == 12) max_message_size_ = 16777215;
597
81
      if (iv_len == 13) max_message_size_ = 65535;
598
    }
599
  }
600
601
305
  return true;
602
}
603
604
127
bool CipherBase::CheckCCMMessageLength(int message_len) {
605
127
  CHECK(ctx_);
606
127
  CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE);
607
608
127
  if (message_len > max_message_size_) {
609
4
    THROW_ERR_CRYPTO_INVALID_MESSAGELEN(env());
610
4
    return false;
611
  }
612
613
123
  return true;
614
}
615
616
1103
bool CipherBase::IsAuthenticatedMode() const {
617
  // Check if this cipher operates in an AEAD mode that we support.
618
1103
  CHECK(ctx_);
619
1103
  return IsSupportedAuthenticatedMode(ctx_.get());
620
}
621
622
145
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
623
145
  Environment* env = Environment::GetCurrent(args);
624
  CipherBase* cipher;
625
205
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
626
627
  // Only callable after Final and if encrypting.
628
376
  if (cipher->ctx_ ||
629

231
      cipher->kind_ != kCipher ||
630
86
      cipher->auth_tag_len_ == kNoAuthTagLength) {
631
60
    return;
632
  }
633
634
85
  args.GetReturnValue().Set(
635
170
      Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
636
          .FromMaybe(Local<Value>()));
637
}
638
639
98
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
640
  CipherBase* cipher;
641
111
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
642
98
  Environment* env = Environment::GetCurrent(args);
643
644
98
  if (!cipher->ctx_ ||
645
97
      !cipher->IsAuthenticatedMode() ||
646

292
      cipher->kind_ != kDecipher ||
647
97
      cipher->auth_tag_state_ != kAuthTagUnknown) {
648
8
    return args.GetReturnValue().Set(false);
649
  }
650
651
94
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
652
94
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
653
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
654
655
94
  unsigned int tag_len = auth_tag.size();
656
657
94
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
658
  bool is_valid;
659
94
  if (mode == EVP_CIPH_GCM_MODE) {
660
    // Restrict GCM tag lengths according to NIST 800-38d, page 9.
661
43
    is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
662

85
                cipher->auth_tag_len_ == tag_len) &&
663
42
               IsValidGCMTagLength(tag_len);
664
  } else {
665
    // At this point, the tag length is already known and must match the
666
    // length of the given authentication tag.
667
51
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
668
51
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
669
51
    is_valid = cipher->auth_tag_len_ == tag_len;
670
  }
671
672
94
  if (!is_valid) {
673
9
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
674
9
      env, "Invalid authentication tag length: %u", tag_len);
675
  }
676
677
85
  cipher->auth_tag_len_ = tag_len;
678
85
  cipher->auth_tag_state_ = kAuthTagKnown;
679
85
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
680
681
85
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
682
85
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
683
684
170
  args.GetReturnValue().Set(true);
685
}
686
687
196
bool CipherBase::MaybePassAuthTagToOpenSSL() {
688
196
  if (auth_tag_state_ == kAuthTagKnown) {
689
84
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
690
                             EVP_CTRL_AEAD_SET_TAG,
691
84
                             auth_tag_len_,
692
84
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
693
      return false;
694
    }
695
84
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
696
  }
697
196
  return true;
698
}
699
700
118
bool CipherBase::SetAAD(
701
    const ArrayBufferOrViewContents<unsigned char>& data,
702
    int plaintext_len) {
703

118
  if (!ctx_ || !IsAuthenticatedMode())
704
2
    return false;
705
232
  MarkPopErrorOnReturn mark_pop_error_on_return;
706
707
  int outlen;
708
116
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
709
710
  // When in CCM mode, we need to set the authentication tag and the plaintext
711
  // length in advance.
712
116
  if (mode == EVP_CIPH_CCM_MODE) {
713
55
    if (plaintext_len < 0) {
714
2
      THROW_ERR_MISSING_ARGS(env(),
715
          "options.plaintextLength required for CCM mode with AAD");
716
2
      return false;
717
    }
718
719
53
    if (!CheckCCMMessageLength(plaintext_len))
720
2
      return false;
721
722
51
    if (kind_ == kDecipher) {
723
26
      if (!MaybePassAuthTagToOpenSSL())
724
        return false;
725
    }
726
727
    // Specify the plaintext length.
728
51
    if (!EVP_CipherUpdate(ctx_.get(), nullptr, &outlen, nullptr, plaintext_len))
729
      return false;
730
  }
731
732
112
  return 1 == EVP_CipherUpdate(ctx_.get(),
733
                               nullptr,
734
                               &outlen,
735
                               data.data(),
736
224
                               data.size());
737
}
738
739
118
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
740
  CipherBase* cipher;
741
118
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
742
118
  Environment* env = Environment::GetCurrent(args);
743
744
118
  CHECK_EQ(args.Length(), 2);
745
118
  CHECK(args[1]->IsInt32());
746
236
  int plaintext_len = args[1].As<Int32>()->Value();
747
118
  ArrayBufferOrViewContents<unsigned char> buf(args[0]);
748
749
118
  if (UNLIKELY(!buf.CheckSizeInt32()))
750
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
751
236
  args.GetReturnValue().Set(cipher->SetAAD(buf, plaintext_len));
752
}
753
754
328
CipherBase::UpdateResult CipherBase::Update(
755
    const char* data,
756
    size_t len,
757
    std::unique_ptr<BackingStore>* out) {
758

328
  if (!ctx_ || len > INT_MAX)
759
    return kErrorState;
760
656
  MarkPopErrorOnReturn mark_pop_error_on_return;
761
762
328
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
763
764

328
  if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
765
2
    return kErrorMessageSize;
766
767
  // Pass the authentication tag to OpenSSL if possible. This will only happen
768
  // once, usually on the first update.
769

326
  if (kind_ == kDecipher && IsAuthenticatedMode())
770
85
    CHECK(MaybePassAuthTagToOpenSSL());
771
772
326
  int buf_len = len + EVP_CIPHER_CTX_block_size(ctx_.get());
773
  // For key wrapping algorithms, get output size by calling
774
  // EVP_CipherUpdate() with null output.
775


335
  if (kind_ == kCipher && mode == EVP_CIPH_WRAP_MODE &&
776
9
      EVP_CipherUpdate(ctx_.get(),
777
                       nullptr,
778
                       &buf_len,
779
                       reinterpret_cast<const unsigned char*>(data),
780
                       len) != 1) {
781
    return kErrorState;
782
  }
783
784
  {
785
326
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
786
326
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), buf_len);
787
  }
788
789
326
  int r = EVP_CipherUpdate(ctx_.get(),
790
326
                           static_cast<unsigned char*>((*out)->Data()),
791
                           &buf_len,
792
                           reinterpret_cast<const unsigned char*>(data),
793
                           len);
794
795
326
  CHECK_LE(static_cast<size_t>(buf_len), (*out)->ByteLength());
796
326
  if (buf_len == 0)
797
67
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
798
  else
799
259
    *out = BackingStore::Reallocate(env()->isolate(), std::move(*out), buf_len);
800
801
  // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
802
  // invalid. In that case, remember the error and throw in final().
803

326
  if (!r && kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
804
5
    pending_auth_failed_ = true;
805
5
    return kSuccess;
806
  }
807
321
  return r == 1 ? kSuccess : kErrorState;
808
}
809
810
328
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
811
328
  Decode<CipherBase>(args, [](CipherBase* cipher,
812
                              const FunctionCallbackInfo<Value>& args,
813
328
                              const char* data, size_t size) {
814
328
    std::unique_ptr<BackingStore> out;
815
328
    Environment* env = Environment::GetCurrent(args);
816
817
328
    if (UNLIKELY(size > INT_MAX))
818
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
819
820
328
    UpdateResult r = cipher->Update(data, size, &out);
821
822
328
    if (r != kSuccess) {
823
2
      if (r == kErrorState) {
824
        ThrowCryptoError(env, ERR_get_error(),
825
                         "Trying to add data in unsupported state");
826
      }
827
2
      return;
828
    }
829
830
326
    Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
831
652
    args.GetReturnValue().Set(
832
652
        Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
833
  });
834
328
}
835
836
18
bool CipherBase::SetAutoPadding(bool auto_padding) {
837
18
  if (!ctx_)
838
1
    return false;
839
17
  MarkPopErrorOnReturn mark_pop_error_on_return;
840
17
  return EVP_CIPHER_CTX_set_padding(ctx_.get(), auto_padding);
841
}
842
843
18
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
844
  CipherBase* cipher;
845
18
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
846
847

36
  bool b = cipher->SetAutoPadding(args.Length() < 1 || args[0]->IsTrue());
848
36
  args.GetReturnValue().Set(b);  // Possibly report invalid state failure
849
}
850
851
254
bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
852
254
  if (!ctx_)
853
    return false;
854
855
254
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
856
857
  {
858
254
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
859
508
    *out = ArrayBuffer::NewBackingStore(env()->isolate(),
860
508
        static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
861
  }
862
863

254
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get()))
864
85
    MaybePassAuthTagToOpenSSL();
865
866
  // In CCM mode, final() only checks whether authentication failed in update().
867
  // EVP_CipherFinal_ex must not be called and will fail.
868
  bool ok;
869

254
  if (kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
870
29
    ok = !pending_auth_failed_;
871
29
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
872
  } else {
873
225
    int out_len = (*out)->ByteLength();
874
225
    ok = EVP_CipherFinal_ex(ctx_.get(),
875
225
                            static_cast<unsigned char*>((*out)->Data()),
876
                            &out_len) == 1;
877
878
225
    CHECK_LE(static_cast<size_t>(out_len), (*out)->ByteLength());
879
225
    if (out_len > 0) {
880
      *out =
881
73
        BackingStore::Reallocate(env()->isolate(), std::move(*out), out_len);
882
    } else {
883
152
      *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
884
    }
885
886


225
    if (ok && kind_ == kCipher && IsAuthenticatedMode()) {
887
      // In GCM mode, the authentication tag length can be specified in advance,
888
      // but defaults to 16 bytes when encrypting. In CCM and OCB mode, it must
889
      // always be given by the user.
890
85
      if (auth_tag_len_ == kNoAuthTagLength) {
891
30
        CHECK(mode == EVP_CIPH_GCM_MODE);
892
30
        auth_tag_len_ = sizeof(auth_tag_);
893
      }
894
85
      ok = (1 == EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG,
895
85
                     auth_tag_len_,
896
85
                     reinterpret_cast<unsigned char*>(auth_tag_)));
897
    }
898
  }
899
900
254
  ctx_.reset();
901
902
254
  return ok;
903
}
904
905
258
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
906
258
  Environment* env = Environment::GetCurrent(args);
907
908
  CipherBase* cipher;
909
279
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
910
258
  if (cipher->ctx_ == nullptr)
911
4
    return THROW_ERR_CRYPTO_INVALID_STATE(env);
912
913
254
  std::unique_ptr<BackingStore> out;
914
915
  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
916
254
  const bool is_auth_mode = cipher->IsAuthenticatedMode();
917
254
  bool r = cipher->Final(&out);
918
919
254
  if (!r) {
920
17
    const char* msg = is_auth_mode
921
17
                          ? "Unsupported state or unable to authenticate data"
922
                          : "Unsupported state";
923
924
17
    return ThrowCryptoError(env, ERR_get_error(), msg);
925
  }
926
927
237
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
928
474
  args.GetReturnValue().Set(
929
474
      Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
930
}
931
932
template <PublicKeyCipher::Operation operation,
933
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
934
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
935
312
bool PublicKeyCipher::Cipher(
936
    Environment* env,
937
    const ManagedEVPPKey& pkey,
938
    int padding,
939
    const EVP_MD* digest,
940
    const ArrayBufferOrViewContents<unsigned char>& oaep_label,
941
    const ArrayBufferOrViewContents<unsigned char>& data,
942
    std::unique_ptr<BackingStore>* out) {
943
624
  EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
944
312
  if (!ctx)
945
    return false;
946
312
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
947
2
    return false;
948
310
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
949
    return false;
950
951
310
  if (digest != nullptr) {
952
42
    if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), digest) <= 0)
953
      return false;
954
  }
955
956
310
  if (oaep_label.size() != 0) {
957
    // OpenSSL takes ownership of the label, so we need to create a copy.
958
8
    void* label = OPENSSL_memdup(oaep_label.data(), oaep_label.size());
959
8
    CHECK_NOT_NULL(label);
960
8
    if (0 >= EVP_PKEY_CTX_set0_rsa_oaep_label(ctx.get(),
961
                     static_cast<unsigned char*>(label),
962
8
                                      oaep_label.size())) {
963
      OPENSSL_free(label);
964
      return false;
965
    }
966
  }
967
968
310
  size_t out_len = 0;
969
310
  if (EVP_PKEY_cipher(
970
          ctx.get(),
971
          nullptr,
972
          &out_len,
973
          data.data(),
974
310
          data.size()) <= 0) {
975
    return false;
976
  }
977
978
  {
979
310
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
980
310
    *out = ArrayBuffer::NewBackingStore(env->isolate(), out_len);
981
  }
982
983
620
  if (EVP_PKEY_cipher(
984
          ctx.get(),
985
310
          static_cast<unsigned char*>((*out)->Data()),
986
          &out_len,
987
          data.data(),
988
310
          data.size()) <= 0) {
989
2
    return false;
990
  }
991
992
308
  CHECK_LE(out_len, (*out)->ByteLength());
993
308
  if (out_len > 0)
994
308
    *out = BackingStore::Reallocate(env->isolate(), std::move(*out), out_len);
995
  else
996
    *out = ArrayBuffer::NewBackingStore(env->isolate(), 0);
997
998
308
  return true;
999
}
1000
1001
template <PublicKeyCipher::Operation operation,
1002
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
1003
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
1004
162
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
1005
162
  MarkPopErrorOnReturn mark_pop_error_on_return;
1006
162
  Environment* env = Environment::GetCurrent(args);
1007
1008
162
  unsigned int offset = 0;
1009
162
  ManagedEVPPKey pkey =
1010
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
1011
162
  if (!pkey)
1012
4
    return;
1013
1014
316
  ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
1015
158
  if (UNLIKELY(!buf.CheckSizeInt32()))
1016
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
1017
1018
  uint32_t padding;
1019
474
  if (!args[offset + 1]->Uint32Value(env->context()).To(&padding)) return;
1020
1021
158
  const EVP_MD* digest = nullptr;
1022
474
  if (args[offset + 2]->IsString()) {
1023
46
    const Utf8Value oaep_str(env->isolate(), args[offset + 2]);
1024
23
    digest = EVP_get_digestbyname(*oaep_str);
1025
23
    if (digest == nullptr)
1026
2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
1027
  }
1028
1029
156
  ArrayBufferOrViewContents<unsigned char> oaep_label;
1030
468
  if (!args[offset + 3]->IsUndefined()) {
1031
8
    oaep_label = ArrayBufferOrViewContents<unsigned char>(args[offset + 3]);
1032
4
    if (UNLIKELY(!oaep_label.CheckSizeInt32()))
1033
      return THROW_ERR_OUT_OF_RANGE(env, "oaep_label is too big");
1034
  }
1035
1036
156
  std::unique_ptr<BackingStore> out;
1037
156
  if (!Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
1038
          env, pkey, padding, digest, oaep_label, buf, &out)) {
1039
2
    return ThrowCryptoError(env, ERR_get_error());
1040
  }
1041
1042
154
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
1043
308
  args.GetReturnValue().Set(
1044
308
      Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
1045
}
1046
1047
}  // namespace crypto
1048
}  // namespace node