GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_cipher.cc Lines: 480 522 92.0 %
Date: 2022-02-12 04:14:26 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
3043
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
35
3043
  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
3043
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
39
2997
         mode == EVP_CIPH_CCM_MODE ||
40

7564
         mode == EVP_CIPH_GCM_MODE ||
41
4567
         IS_OCB_MODE(mode);
42
}
43
44
1303
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
45
1303
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
46
1303
  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
425
void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
55
425
  Environment* env = Environment::GetCurrent(args);
56
425
  CHECK(args[0]->IsObject());
57
850
  Local<Object> info = args[0].As<Object>();
58
59

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



423
  switch (mode) {
79
86
    case EVP_CIPH_CBC_MODE: mode_label = "cbc"; break;
80
36
    case EVP_CIPH_CCM_MODE: mode_label = "ccm"; break;
81
96
    case EVP_CIPH_CFB_MODE: mode_label = "cfb"; break;
82
30
    case EVP_CIPH_CTR_MODE: mode_label = "ctr"; break;
83
42
    case EVP_CIPH_ECB_MODE: mode_label = "ecb"; break;
84
27
    case EVP_CIPH_GCM_MODE: mode_label = "gcm"; break;
85
25
    case EVP_CIPH_OCB_MODE: mode_label = "ocb"; break;
86
36
    case EVP_CIPH_OFB_MODE: mode_label = "ofb"; break;
87
33
    case EVP_CIPH_WRAP_MODE: mode_label = "wrap"; break;
88
6
    case EVP_CIPH_XTS_MODE: mode_label = "xts"; break;
89
6
    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

844
  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
836
  if (mode_label != nullptr &&
143
418
      info->Set(
144
          env->context(),
145
          FIXED_ONE_BYTE_STRING(env->isolate(), "mode"),
146

2090
          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
836
  if (info->Set(
153
          env->context(),
154
          env->name_string(),
155
          OneByteString(
156
            env->isolate(),
157
1672
            OBJ_nid2sn(EVP_CIPHER_nid(cipher)))).IsNothing()) {
158
    return;
159
  }
160
161
836
  if (info->Set(
162
          env->context(),
163
          FIXED_ONE_BYTE_STRING(env->isolate(), "nid"),
164
1672
          Int32::New(env->isolate(), EVP_CIPHER_nid(cipher))).IsNothing()) {
165
    return;
166
  }
167
168
  // Stream ciphers do not have a meaningful block size
169
830
  if (mode != EVP_CIPH_STREAM_CIPHER &&
170
418
      info->Set(
171
          env->context(),
172
          FIXED_ONE_BYTE_STRING(env->isolate(), "blockSize"),
173

2066
          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
788
  if (iv_length != 0 &&
179
418
      info->Set(
180
          env->context(),
181
          FIXED_ONE_BYTE_STRING(env->isolate(), "ivLength"),
182

1898
          Int32::New(env->isolate(), iv_length)).IsNothing()) {
183
    return;
184
  }
185
186
836
  if (info->Set(
187
          env->context(),
188
          FIXED_ONE_BYTE_STRING(env->isolate(), "keyLength"),
189
1672
          Int32::New(env->isolate(), key_length)).IsNothing()) {
190
    return;
191
  }
192
193
836
  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
6
  MarkPopErrorOnReturn mark_pop_error_on_return;
239
3
  CipherPushContext ctx(env);
240
3
  EVP_CIPHER_do_all_sorted(
241
#if OPENSSL_VERSION_MAJOR >= 3
242
    array_push_back<EVP_CIPHER,
243
                    EVP_CIPHER_fetch,
244
                    EVP_CIPHER_free,
245
                    EVP_get_cipherbyname,
246
                    EVP_CIPHER_get0_name>,
247
#else
248
    array_push_back<EVP_CIPHER>,
249
#endif
250
    &ctx);
251
6
  args.GetReturnValue().Set(ctx.ToJSArray());
252
3
}
253
254
1203
CipherBase::CipherBase(Environment* env,
255
                       Local<Object> wrap,
256
1203
                       CipherKind kind)
257
    : BaseObject(env, wrap),
258
      ctx_(nullptr),
259
      kind_(kind),
260
      auth_tag_state_(kAuthTagUnknown),
261
      auth_tag_len_(kNoAuthTagLength),
262
1203
      pending_auth_failed_(false) {
263
1203
  MakeWeak();
264
1203
}
265
266
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
267
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
268
}
269
270
4378
void CipherBase::Initialize(Environment* env, Local<Object> target) {
271
4378
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
272
273
8756
  t->InstanceTemplate()->SetInternalFieldCount(
274
      CipherBase::kInternalFieldCount);
275
4378
  t->Inherit(BaseObject::GetConstructorTemplate(env));
276
277
4378
  env->SetProtoMethod(t, "init", Init);
278
4378
  env->SetProtoMethod(t, "initiv", InitIv);
279
4378
  env->SetProtoMethod(t, "update", Update);
280
4378
  env->SetProtoMethod(t, "final", Final);
281
4378
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
282
4378
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
283
4378
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
284
4378
  env->SetProtoMethod(t, "setAAD", SetAAD);
285
4378
  env->SetConstructorFunction(target, "CipherBase", t);
286
287
4378
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
288
4378
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
289
290
4378
  env->SetMethod(target, "publicEncrypt",
291
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
292
                                         EVP_PKEY_encrypt_init,
293
                                         EVP_PKEY_encrypt>);
294
4378
  env->SetMethod(target, "privateDecrypt",
295
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
296
                                         EVP_PKEY_decrypt_init,
297
                                         EVP_PKEY_decrypt>);
298
4378
  env->SetMethod(target, "privateEncrypt",
299
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
300
                                         EVP_PKEY_sign_init,
301
                                         EVP_PKEY_sign>);
302
4378
  env->SetMethod(target, "publicDecrypt",
303
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
304
                                         EVP_PKEY_verify_recover_init,
305
                                         EVP_PKEY_verify_recover>);
306
307
4378
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
308
309
13134
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
310
8756
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
311
4378
}
312
313
4936
void CipherBase::RegisterExternalReferences(
314
    ExternalReferenceRegistry* registry) {
315
4936
  registry->Register(New);
316
317
4936
  registry->Register(Init);
318
4936
  registry->Register(InitIv);
319
4936
  registry->Register(Update);
320
4936
  registry->Register(Final);
321
4936
  registry->Register(SetAutoPadding);
322
4936
  registry->Register(GetAuthTag);
323
4936
  registry->Register(SetAuthTag);
324
4936
  registry->Register(SetAAD);
325
326
4936
  registry->Register(GetSSLCiphers);
327
4936
  registry->Register(GetCiphers);
328
329
4936
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
330
                                             EVP_PKEY_encrypt_init,
331
                                             EVP_PKEY_encrypt>);
332
4936
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
333
                                             EVP_PKEY_decrypt_init,
334
                                             EVP_PKEY_decrypt>);
335
4936
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
336
                                             EVP_PKEY_sign_init,
337
                                             EVP_PKEY_sign>);
338
4936
  registry->Register(PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
339
                                             EVP_PKEY_verify_recover_init,
340
                                             EVP_PKEY_verify_recover>);
341
342
4936
  registry->Register(GetCipherInfo);
343
4936
}
344
345
1203
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
346
1203
  CHECK(args.IsConstructCall());
347
1203
  Environment* env = Environment::GetCurrent(args);
348

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

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

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

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

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

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


261
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher &&
584
54
        EVP_default_properties_is_fips_enabled(nullptr)) {
585
#else
586
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
587
#endif
588
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
589
          "CCM encryption not supported in FIPS mode");
590
      return false;
591
    }
592
593
    // Tell OpenSSL about the desired length.
594
207
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
595
                             nullptr)) {
596
48
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env());
597
48
      return false;
598
    }
599
600
    // Remember the given authentication tag length for later.
601
159
    auth_tag_len_ = auth_tag_len;
602
603
159
    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
327
  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
1125
bool CipherBase::IsAuthenticatedMode() const {
628
  // Check if this cipher operates in an AEAD mode that we support.
629
1125
  CHECK(ctx_);
630
1125
  return IsSupportedAuthenticatedMode(ctx_.get());
631
}
632
633
145
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
634
145
  Environment* env = Environment::GetCurrent(args);
635
  CipherBase* cipher;
636
205
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
637
638
  // Only callable after Final and if encrypting.
639
376
  if (cipher->ctx_ ||
640

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

292
      cipher->kind_ != kDecipher ||
658
97
      cipher->auth_tag_state_ != kAuthTagUnknown) {
659
8
    return args.GetReturnValue().Set(false);
660
  }
661
662
94
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
663
94
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
664
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
665
666
94
  unsigned int tag_len = auth_tag.size();
667
668
94
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
669
  bool is_valid;
670
94
  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
51
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
679
51
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
680
51
    is_valid = cipher->auth_tag_len_ == tag_len;
681
  }
682
683
94
  if (!is_valid) {
684
9
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
685
9
      env, "Invalid authentication tag length: %u", tag_len);
686
  }
687
688
85
  cipher->auth_tag_len_ = tag_len;
689
85
  cipher->auth_tag_state_ = kAuthTagKnown;
690
85
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
691
692
85
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
693
85
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
694
695
170
  args.GetReturnValue().Set(true);
696
}
697
698
196
bool CipherBase::MaybePassAuthTagToOpenSSL() {
699
196
  if (auth_tag_state_ == kAuthTagKnown) {
700
84
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
701
                             EVP_CTRL_AEAD_SET_TAG,
702
84
                             auth_tag_len_,
703
84
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
704
      return false;
705
    }
706
84
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
707
  }
708
196
  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
328
CipherBase::UpdateResult CipherBase::Update(
766
    const char* data,
767
    size_t len,
768
    std::unique_ptr<BackingStore>* out) {
769

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

328
  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

326
  if (kind_ == kDecipher && IsAuthenticatedMode())
781
85
    CHECK(MaybePassAuthTagToOpenSSL());
782
783
326
  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


335
  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
326
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
797
326
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), buf_len);
798
  }
799
800
326
  int r = EVP_CipherUpdate(ctx_.get(),
801
326
                           static_cast<unsigned char*>((*out)->Data()),
802
                           &buf_len,
803
                           reinterpret_cast<const unsigned char*>(data),
804
                           len);
805
806
326
  CHECK_LE(static_cast<size_t>(buf_len), (*out)->ByteLength());
807
326
  if (buf_len == 0)
808
67
    *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
809
  else
810
259
    *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

326
  if (!r && kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
815
5
    pending_auth_failed_ = true;
816
5
    return kSuccess;
817
  }
818
321
  return r == 1 ? kSuccess : kErrorState;
819
}
820
821
328
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
822
328
  Decode<CipherBase>(args, [](CipherBase* cipher,
823
                              const FunctionCallbackInfo<Value>& args,
824
328
                              const char* data, size_t size) {
825
328
    std::unique_ptr<BackingStore> out;
826
328
    Environment* env = Environment::GetCurrent(args);
827
828
328
    if (UNLIKELY(size > INT_MAX))
829
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
830
831
328
    UpdateResult r = cipher->Update(data, size, &out);
832
833
328
    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
326
    Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
842
652
    args.GetReturnValue().Set(
843
652
        Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
844
  });
845
328
}
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
254
bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
863
254
  if (!ctx_)
864
    return false;
865
866
254
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
867
868
  {
869
254
    NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
870
508
    *out = ArrayBuffer::NewBackingStore(env()->isolate(),
871
508
        static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
872
  }
873
874

254
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get()))
875
85
    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

254
  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
225
    int out_len = (*out)->ByteLength();
885
225
    ok = EVP_CipherFinal_ex(ctx_.get(),
886
225
                            static_cast<unsigned char*>((*out)->Data()),
887
                            &out_len) == 1;
888
889
225
    CHECK_LE(static_cast<size_t>(out_len), (*out)->ByteLength());
890
225
    if (out_len > 0) {
891
      *out =
892
73
        BackingStore::Reallocate(env()->isolate(), std::move(*out), out_len);
893
    } else {
894
152
      *out = ArrayBuffer::NewBackingStore(env()->isolate(), 0);
895
    }
896
897


225
    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
85
      if (auth_tag_len_ == kNoAuthTagLength) {
902
30
        CHECK(mode == EVP_CIPH_GCM_MODE);
903
30
        auth_tag_len_ = sizeof(auth_tag_);
904
      }
905
85
      ok = (1 == EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG,
906
85
                     auth_tag_len_,
907
85
                     reinterpret_cast<unsigned char*>(auth_tag_)));
908
    }
909
  }
910
911
254
  ctx_.reset();
912
913
254
  return ok;
914
}
915
916
258
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
917
258
  Environment* env = Environment::GetCurrent(args);
918
919
  CipherBase* cipher;
920
279
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
921
258
  if (cipher->ctx_ == nullptr)
922
4
    return THROW_ERR_CRYPTO_INVALID_STATE(env);
923
924
254
  std::unique_ptr<BackingStore> out;
925
926
  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
927
254
  const bool is_auth_mode = cipher->IsAuthenticatedMode();
928
254
  bool r = cipher->Final(&out);
929
930
254
  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
237
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
939
474
  args.GetReturnValue().Set(
940
474
      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