GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/crypto/crypto_cipher.cc Lines: 449 493 91.1 %
Date: 2021-04-21 04:11:54 Branches: 435 619 70.3 %

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

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


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

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



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

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

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

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

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

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

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

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

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

2832
  if (!is_authenticated_mode &&
434

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

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


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

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

376
  if (cipher->ctx_ ||
592

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

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

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

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

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

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

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

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


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

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

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

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

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

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


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


158
  if (!ctx)
896
    return false;
897


158
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
898
1
    return false;
899


157
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
900
    return false;
901
902


157
  if (digest != nullptr) {
903


21
    if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), digest) <= 0)
904
      return false;
905
  }
906
907


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


4
    CHECK_NOT_NULL(label);
911


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


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


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


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


164
  if (!pkey)
955
4
    return;
956
957


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


160
  if (UNLIKELY(!buf.CheckSizeInt32()))
959
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
960
961
  uint32_t padding;
962


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


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


23
    if (digest == nullptr)
969


2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
970
  }
971
972


314
  ArrayBufferOrViewContents<unsigned char> oaep_label;
973


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


4
    if (UNLIKELY(!oaep_label.CheckSizeInt32()))
976
      return THROW_ERR_OUT_OF_RANGE(env, "oaep_label is too big");
977
  }
978
979


314
  AllocatedBuffer out;
980


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


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


312
    args.GetReturnValue().Set(result);
988
}
989
990
}  // namespace crypto
991

14310
}  // namespace node