GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_cipher.cc Lines: 482 524 92.0 %
Date: 2022-03-23 03:15:06 Branches: 320 420 76.2 %

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
namespace {
28
4697
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
29
4697
  switch (EVP_CIPHER_mode(cipher)) {
30
1857
  case EVP_CIPH_CCM_MODE:
31
  case EVP_CIPH_GCM_MODE:
32
#ifndef OPENSSL_NO_OCB
33
  case EVP_CIPH_OCB_MODE:
34
#endif
35
1857
    return true;
36
1702
  case EVP_CIPH_STREAM_CIPHER:
37
1702
    return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305;
38
1138
  default:
39
1138
    return false;
40
  }
41
}
42
43
2409
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
44
2409
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
45
2409
  return IsSupportedAuthenticatedMode(cipher);
46
}
47
48
66
bool IsValidGCMTagLength(unsigned int tag_len) {
49


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

982
  CHECK(args[1]->IsString() || args[1]->IsInt32());
59
60
  const EVP_CIPHER* cipher;
61
850
  if (args[1]->IsString()) {
62
586
    Utf8Value name(env->isolate(), args[1]);
63
293
    cipher = EVP_get_cipherbyname(*name);
64
  } else {
65
264
    int nid = args[1].As<Int32>()->Value();
66
132
    cipher = EVP_get_cipherbynid(nid);
67
  }
68
69
425
  if (cipher == nullptr)
70
7
    return;
71
72
423
  int mode = EVP_CIPHER_mode(cipher);
73
423
  int iv_length = EVP_CIPHER_iv_length(cipher);
74
423
  int key_length = EVP_CIPHER_key_length(cipher);
75
423
  int block_length = EVP_CIPHER_block_size(cipher);
76
423
  const char* mode_label = nullptr;
77



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

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

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

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

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

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

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

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

162
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
453
54
    auth_tag_len = kNoAuthTagLength;
454
  }
455
456
89
  cipher->Init(*cipher_type, key_buf, auth_tag_len);
457
}
458
459
1388
void CipherBase::InitIv(const char* cipher_type,
460
                        const ByteSource& key_buf,
461
                        const ArrayBufferOrViewContents<unsigned char>& iv_buf,
462
                        unsigned int auth_tag_len) {
463
1388
  HandleScope scope(env()->isolate());
464
1388
  MarkPopErrorOnReturn mark_pop_error_on_return;
465
466
1388
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
467
1388
  if (cipher == nullptr)
468
1
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
469
470
1387
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
471
1387
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
472
1387
  const bool has_iv = iv_buf.size() > 0;
473
474
  // Throw if no IV was passed and the cipher requires an IV
475

1387
  if (!has_iv && expected_iv_len != 0)
476
61
    return THROW_ERR_CRYPTO_INVALID_IV(env());
477
478
  // Throw if an IV was passed which does not match the cipher's fixed IV length
479
  // static_cast<int> for the iv_buf.size() is safe because we've verified
480
  // prior that the value is not larger than MAX_INT.
481
695
  if (!is_authenticated_mode &&
482

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

2739
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
537
913
    auth_tag_len = kNoAuthTagLength;
538
  }
539
540
1388
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
541
}
542
543
673
bool CipherBase::InitAuthenticated(
544
    const char* cipher_type,
545
    int iv_len,
546
    unsigned int auth_tag_len) {
547
673
  CHECK(IsAuthenticatedMode());
548
1346
  MarkPopErrorOnReturn mark_pop_error_on_return;
549
550
673
  if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
551
                           EVP_CTRL_AEAD_SET_IVLEN,
552
                           iv_len,
553
                           nullptr)) {
554
    THROW_ERR_CRYPTO_INVALID_IV(env());
555
    return false;
556
  }
557
558
673
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
559
673
  if (mode == EVP_CIPH_GCM_MODE) {
560
184
    if (auth_tag_len != kNoAuthTagLength) {
561
24
      if (!IsValidGCMTagLength(auth_tag_len)) {
562
16
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
563
          env(),
564
          "Invalid authentication tag length: %u",
565
          auth_tag_len);
566
16
        return false;
567
      }
568
569
      // Remember the given authentication tag length for later.
570
8
      auth_tag_len_ = auth_tag_len;
571
    }
572
  } else {
573
489
    if (auth_tag_len == kNoAuthTagLength) {
574
8
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
575
        env(), "authTagLength required for %s", cipher_type);
576
8
      return false;
577
    }
578
579
    // TODO(tniessen) Support CCM decryption in FIPS mode
580
581
#if OPENSSL_VERSION_MAJOR >= 3
582


535
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher &&
583
54
        EVP_default_properties_is_fips_enabled(nullptr)) {
584
#else
585
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
586
#endif
587
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
588
          "CCM encryption not supported in FIPS mode");
589
      return false;
590
    }
591
592
    // Tell OpenSSL about the desired length.
593
481
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
594
                             nullptr)) {
595
50
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
596
          env(), "Invalid authentication tag length: %u", auth_tag_len);
597
50
      return false;
598
    }
599
600
    // Remember the given authentication tag length for later.
601
431
    auth_tag_len_ = auth_tag_len;
602
603
431
    if (mode == EVP_CIPH_CCM_MODE) {
604
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
605

90
      CHECK(iv_len >= 7 && iv_len <= 13);
606
90
      max_message_size_ = INT_MAX;
607
90
      if (iv_len == 12) max_message_size_ = 16777215;
608
90
      if (iv_len == 13) max_message_size_ = 65535;
609
    }
610
  }
611
612
599
  return true;
613
}
614
615
127
bool CipherBase::CheckCCMMessageLength(int message_len) {
616
127
  CHECK(ctx_);
617
127
  CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE);
618
619
127
  if (message_len > max_message_size_) {
620
4
    THROW_ERR_CRYPTO_INVALID_MESSAGELEN(env());
621
4
    return false;
622
  }
623
624
123
  return true;
625
}
626
627
1959
bool CipherBase::IsAuthenticatedMode() const {
628
  // Check if this cipher operates in an AEAD mode that we support.
629
1959
  CHECK(ctx_);
630
1959
  return IsSupportedAuthenticatedMode(ctx_.get());
631
}
632
633
161
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
634
161
  Environment* env = Environment::GetCurrent(args);
635
  CipherBase* cipher;
636
221
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
637
638
  // Only callable after Final and if encrypting.
639
424
  if (cipher->ctx_ ||
640

263
      cipher->kind_ != kCipher ||
641
102
      cipher->auth_tag_len_ == kNoAuthTagLength) {
642
60
    return;
643
  }
644
645
101
  args.GetReturnValue().Set(
646
202
      Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
647
          .FromMaybe(Local<Value>()));
648
}
649
650
354
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
651
  CipherBase* cipher;
652
607
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
653
354
  Environment* env = Environment::GetCurrent(args);
654
655
354
  if (!cipher->ctx_ ||
656
353
      !cipher->IsAuthenticatedMode() ||
657

1060
      cipher->kind_ != kDecipher ||
658
353
      cipher->auth_tag_state_ != kAuthTagUnknown) {
659
8
    return args.GetReturnValue().Set(false);
660
  }
661
662
350
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
663
350
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
664
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
665
666
350
  unsigned int tag_len = auth_tag.size();
667
668
350
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
669
  bool is_valid;
670
350
  if (mode == EVP_CIPH_GCM_MODE) {
671
    // Restrict GCM tag lengths according to NIST 800-38d, page 9.
672
43
    is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
673

85
                cipher->auth_tag_len_ == tag_len) &&
674
42
               IsValidGCMTagLength(tag_len);
675
  } else {
676
    // At this point, the tag length is already known and must match the
677
    // length of the given authentication tag.
678
307
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
679
307
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
680
307
    is_valid = cipher->auth_tag_len_ == tag_len;
681
  }
682
683
350
  if (!is_valid) {
684
249
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
685
249
      env, "Invalid authentication tag length: %u", tag_len);
686
  }
687
688
101
  cipher->auth_tag_len_ = tag_len;
689
101
  cipher->auth_tag_state_ = kAuthTagKnown;
690
101
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
691
692
101
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
693
101
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
694
695
202
  args.GetReturnValue().Set(true);
696
}
697
698
468
bool CipherBase::MaybePassAuthTagToOpenSSL() {
699
468
  if (auth_tag_state_ == kAuthTagKnown) {
700
100
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
701
                             EVP_CTRL_AEAD_SET_TAG,
702
100
                             auth_tag_len_,
703
100
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
704
      return false;
705
    }
706
100
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
707
  }
708
468
  return true;
709
}
710
711
118
bool CipherBase::SetAAD(
712
    const ArrayBufferOrViewContents<unsigned char>& data,
713
    int plaintext_len) {
714

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

600
  if (!ctx_ || len > INT_MAX)
770
    return kErrorState;
771
1200
  MarkPopErrorOnReturn mark_pop_error_on_return;
772
773
600
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
774
775

600
  if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
776
2
    return kErrorMessageSize;
777
778
  // Pass the authentication tag to OpenSSL if possible. This will only happen
779
  // once, usually on the first update.
780

598
  if (kind_ == kDecipher && IsAuthenticatedMode())
781
341
    CHECK(MaybePassAuthTagToOpenSSL());
782
783
598
  int buf_len = len + EVP_CIPHER_CTX_block_size(ctx_.get());
784
  // For key wrapping algorithms, get output size by calling
785
  // EVP_CipherUpdate() with null output.
786


607
  if (kind_ == kCipher && mode == EVP_CIPH_WRAP_MODE &&
787
9
      EVP_CipherUpdate(ctx_.get(),
788
                       nullptr,
789
                       &buf_len,
790
                       reinterpret_cast<const unsigned char*>(data),
791
                       len) != 1) {
792
    return kErrorState;
793
  }
794
795
  {
796
598
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
797
598
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), buf_len);
798
  }
799
800
598
  int r = EVP_CipherUpdate(ctx_.get(),
801
598
                           static_cast<unsigned char*>((*out)->Data()),
802
                           &buf_len,
803
                           reinterpret_cast<const unsigned char*>(data),
804
                           len);
805
806
598
  CHECK_LE(static_cast<size_t>(buf_len), (*out)->ByteLength());
807
598
  if (buf_len == 0)
808
67
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
809
  else
810
531
    *out = BackingStore::Reallocate(env()->isolate(), std::move(*out), buf_len);
811
812
  // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
813
  // invalid. In that case, remember the error and throw in final().
814

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

36
  bool b = cipher->SetAutoPadding(args.Length() < 1 || args[0]->IsTrue());
859
36
  args.GetReturnValue().Set(b);  // Possibly report invalid state failure
860
}
861
862
286
bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
863
286
  if (!ctx_)
864
    return false;
865
866
286
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
867
868
  {
869
286
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
870
572
    *out = ArrayBuffer::NewBackingStore(env()->isolate(),
871
572
        static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
872
  }
873
874

286
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get()))
875
101
    MaybePassAuthTagToOpenSSL();
876
877
  // In CCM mode, final() only checks whether authentication failed in update().
878
  // EVP_CipherFinal_ex must not be called and will fail.
879
  bool ok;
880

286
  if (kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
881
29
    ok = !pending_auth_failed_;
882
29
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
883
  } else {
884
257
    int out_len = (*out)->ByteLength();
885
257
    ok = EVP_CipherFinal_ex(ctx_.get(),
886
257
                            static_cast<unsigned char*>((*out)->Data()),
887
                            &out_len) == 1;
888
889
257
    CHECK_LE(static_cast<size_t>(out_len), (*out)->ByteLength());
890
257
    if (out_len > 0) {
891
      *out =
892
73
        BackingStore::Reallocate(env()->isolate(), std::move(*out), out_len);
893
    } else {
894
184
      *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
895
    }
896
897


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