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: 446 485 92.0 %
Date: 2021-01-16 04:10:54 Branches: 429 611 70.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.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
3356
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
33
3356
  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
6669
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
37
6002
         mode == EVP_CIPH_CCM_MODE ||
38

7351
         mode == EVP_CIPH_GCM_MODE ||
39
4662
         IS_OCB_MODE(mode);
40
}
41
42
1479
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
43
1479
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
44
1479
  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
1271
CipherBase::CipherBase(Environment* env,
238
                       Local<Object> wrap,
239
1271
                       CipherKind kind)
240
    : BaseObject(env, wrap),
241
      ctx_(nullptr),
242
      kind_(kind),
243
      auth_tag_state_(kAuthTagUnknown),
244
      auth_tag_len_(kNoAuthTagLength),
245
1271
      pending_auth_failed_(false) {
246
1271
  MakeWeak();
247
1271
}
248
249
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
250
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
251
}
252
253
663
void CipherBase::Initialize(Environment* env, Local<Object> target) {
254
663
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
255
256
1989
  t->InstanceTemplate()->SetInternalFieldCount(
257
663
      CipherBase::kInternalFieldCount);
258
1326
  t->Inherit(BaseObject::GetConstructorTemplate(env));
259
260
663
  env->SetProtoMethod(t, "init", Init);
261
663
  env->SetProtoMethod(t, "initiv", InitIv);
262
663
  env->SetProtoMethod(t, "update", Update);
263
663
  env->SetProtoMethod(t, "final", Final);
264
663
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
265
663
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
266
663
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
267
663
  env->SetProtoMethod(t, "setAAD", SetAAD);
268
663
  env->SetConstructorFunction(target, "CipherBase", t);
269
270
663
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
271
663
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
272
273
  env->SetMethod(target, "publicEncrypt",
274
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
275
                                         EVP_PKEY_encrypt_init,
276
663
                                         EVP_PKEY_encrypt>);
277
  env->SetMethod(target, "privateDecrypt",
278
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
279
                                         EVP_PKEY_decrypt_init,
280
663
                                         EVP_PKEY_decrypt>);
281
  env->SetMethod(target, "privateEncrypt",
282
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
283
                                         EVP_PKEY_sign_init,
284
663
                                         EVP_PKEY_sign>);
285
  env->SetMethod(target, "publicDecrypt",
286
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
287
                                         EVP_PKEY_verify_recover_init,
288
663
                                         EVP_PKEY_verify_recover>);
289
290
663
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
291
292
1326
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
293
663
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
294
1989
}
295
1326
296
3260
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
297
2597
  CHECK(args.IsConstructCall());
298
1271
  Environment* env = Environment::GetCurrent(args);
299
3813
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
300
1271
}
301
302
695
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
695
  CHECK(!ctx_);
310
695
  ctx_.reset(EVP_CIPHER_CTX_new());
311
312
695
  const int mode = EVP_CIPHER_mode(cipher);
313
695
  if (mode == EVP_CIPH_WRAP_MODE)
314
18
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
315
316
695
  const bool encrypt = (kind_ == kCipher);
317
695
  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
695
  if (IsSupportedAuthenticatedMode(cipher)) {
324
574
    CHECK_GE(iv_len, 0);
325
574
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
326
72
      return;
327
  }
328
329
623
  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
622
  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
88
void CipherBase::Init(const char* cipher_type,
341
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
342
                      unsigned int auth_tag_len) {
343
176
  HandleScope scope(env()->isolate());
344
176
  MarkPopErrorOnReturn mark_pop_error_on_return;
345
346
#ifdef NODE_FIPS_MODE
347
  if (FIPS_mode()) {
348
    return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
349
        "crypto.createCipher() is not supported in FIPS mode.");
350
  }
351
#endif  // NODE_FIPS_MODE
352
353
88
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
354
88
  if (cipher == nullptr)
355
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
356
357
  unsigned char key[EVP_MAX_KEY_LENGTH];
358
  unsigned char iv[EVP_MAX_IV_LENGTH];
359
360
88
  int key_len = EVP_BytesToKey(cipher,
361
                               EVP_md5(),
362
                               nullptr,
363
                               key_buf.data(),
364
88
                               key_buf.size(),
365
                               1,
366
                               key,
367
88
                               iv);
368
88
  CHECK_NE(key_len, 0);
369
370
88
  const int mode = EVP_CIPHER_mode(cipher);
371

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

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

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

2830
  if (!is_authenticated_mode &&
433

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

4980
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
488
996
    auth_tag_len = kNoAuthTagLength;
489
  }
490
491
1183
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
492
}
493
494
574
bool CipherBase::InitAuthenticated(
495
    const char* cipher_type,
496
    int iv_len,
497
    unsigned int auth_tag_len) {
498
574
  CHECK(IsAuthenticatedMode());
499
1148
  MarkPopErrorOnReturn mark_pop_error_on_return;
500
501
574
  if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
502
                           EVP_CTRL_AEAD_SET_IVLEN,
503
                           iv_len,
504
                           nullptr)) {
505
    THROW_ERR_CRYPTO_INVALID_IV(env());
506
    return false;
507
  }
508
509
574
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
510
574
  if (mode == EVP_CIPH_GCM_MODE) {
511
374
    if (auth_tag_len != kNoAuthTagLength) {
512
24
      if (!IsValidGCMTagLength(auth_tag_len)) {
513
        char msg[50];
514
        snprintf(msg, sizeof(msg),
515
16
            "Invalid authentication tag length: %u", auth_tag_len);
516
16
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env(), msg);
517
16
        return false;
518
      }
519
520
      // Remember the given authentication tag length for later.
521
8
      auth_tag_len_ = auth_tag_len;
522
    }
523
  } else {
524
200
    if (auth_tag_len == kNoAuthTagLength) {
525
      char msg[128];
526
8
      snprintf(msg, sizeof(msg), "authTagLength required for %s", cipher_type);
527
8
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env(), msg);
528
8
      return false;
529
    }
530
531
#ifdef NODE_FIPS_MODE
532
    // TODO(tniessen) Support CCM decryption in FIPS mode
533
    if (mode == EVP_CIPH_CCM_MODE && kind_ == kDecipher && FIPS_mode()) {
534
      THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
535
          "CCM encryption not supported in FIPS mode");
536
      return false;
537
    }
538
#endif
539
540
    // Tell OpenSSL about the desired length.
541
192
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
542
                             nullptr)) {
543
48
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env());
544
48
      return false;
545
    }
546
547
    // Remember the given authentication tag length for later.
548
144
    auth_tag_len_ = auth_tag_len;
549
550
144
    if (mode == EVP_CIPH_CCM_MODE) {
551
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
552

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

376
  if (cipher->ctx_ ||
587

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

293
  if (!cipher->ctx_ ||
603
194
      !cipher->IsAuthenticatedMode() ||
604

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

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

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

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

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

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


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

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

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

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

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

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


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


138
  if (!ctx)
891
    return false;
892


138
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
893
1
    return false;
894


137
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
895
    return false;
896
897


137
  if (digest != nullptr) {
898


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


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


4
    CHECK_NOT_NULL(label);
906


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


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


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


280
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
949


144
  if (!pkey)
950
4
    return;
951
952


416
  ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
953


140
  if (UNLIKELY(!buf.CheckSizeInt32()))
954
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
955
956
  uint32_t padding;
957


560
  if (!args[offset + 1]->Uint32Value(env->context()).To(&padding)) return;
958
959
140
  const EVP_MD* digest = nullptr;
960


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


23
    if (digest == nullptr)
964


2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
965
  }
966
967


274
  ArrayBufferOrViewContents<unsigned char> oaep_label;
968


552
  if (!args[offset + 3]->IsUndefined()) {
969
8
    oaep_label = ArrayBufferOrViewContents<unsigned char>(args[offset + 3]);
970


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


274
  AllocatedBuffer out;
975


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


272
  if (out.ToBuffer().ToLocal(&result))
982


272
    args.GetReturnValue().Set(result);
983
}
984
985
}  // namespace crypto
986

13995
}  // namespace node