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: 447 486 92.0 %
Date: 2020-11-21 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
654
void CipherBase::Initialize(Environment* env, Local<Object> target) {
254
654
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
255
256
1962
  t->InstanceTemplate()->SetInternalFieldCount(
257
654
      CipherBase::kInternalFieldCount);
258
1308
  t->Inherit(BaseObject::GetConstructorTemplate(env));
259
260
654
  env->SetProtoMethod(t, "init", Init);
261
654
  env->SetProtoMethod(t, "initiv", InitIv);
262
654
  env->SetProtoMethod(t, "update", Update);
263
654
  env->SetProtoMethod(t, "final", Final);
264
654
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
265
654
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
266
654
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
267
654
  env->SetProtoMethod(t, "setAAD", SetAAD);
268
269
1308
  target->Set(env->context(),
270
              FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
271
3924
              t->GetFunction(env->context()).ToLocalChecked()).Check();
272
273
654
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
274
654
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
275
276
  env->SetMethod(target, "publicEncrypt",
277
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
278
                                         EVP_PKEY_encrypt_init,
279
654
                                         EVP_PKEY_encrypt>);
280
  env->SetMethod(target, "privateDecrypt",
281
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
282
                                         EVP_PKEY_decrypt_init,
283
654
                                         EVP_PKEY_decrypt>);
284
  env->SetMethod(target, "privateEncrypt",
285
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
286
                                         EVP_PKEY_sign_init,
287
654
                                         EVP_PKEY_sign>);
288
  env->SetMethod(target, "publicDecrypt",
289
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
290
                                         EVP_PKEY_verify_recover_init,
291
654
                                         EVP_PKEY_verify_recover>);
292
293
654
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
294
295
1308
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
296
654
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
297
1962
}
298
1308
299
3233
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
300
2579
  CHECK(args.IsConstructCall());
301
1271
  Environment* env = Environment::GetCurrent(args);
302
3813
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
303
1271
}
304
305
695
void CipherBase::CommonInit(const char* cipher_type,
306
                            const EVP_CIPHER* cipher,
307
                            const unsigned char* key,
308
                            int key_len,
309
                            const unsigned char* iv,
310
                            int iv_len,
311
                            unsigned int auth_tag_len) {
312
695
  CHECK(!ctx_);
313
695
  ctx_.reset(EVP_CIPHER_CTX_new());
314
315
695
  const int mode = EVP_CIPHER_mode(cipher);
316
695
  if (mode == EVP_CIPH_WRAP_MODE)
317
18
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
318
319
695
  const bool encrypt = (kind_ == kCipher);
320
695
  if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr,
321
                             nullptr, nullptr, encrypt)) {
322
    return ThrowCryptoError(env(), ERR_get_error(),
323
                            "Failed to initialize cipher");
324
  }
325
326
695
  if (IsSupportedAuthenticatedMode(cipher)) {
327
574
    CHECK_GE(iv_len, 0);
328
574
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
329
72
      return;
330
  }
331
332
623
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
333
1
    ctx_.reset();
334
1
    return THROW_ERR_CRYPTO_INVALID_KEYLEN(env());
335
  }
336
337
622
  if (1 != EVP_CipherInit_ex(ctx_.get(), nullptr, nullptr, key, iv, encrypt)) {
338
    return ThrowCryptoError(env(), ERR_get_error(),
339
                            "Failed to initialize cipher");
340
  }
341
}
342
343
88
void CipherBase::Init(const char* cipher_type,
344
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
345
                      unsigned int auth_tag_len) {
346
176
  HandleScope scope(env()->isolate());
347
176
  MarkPopErrorOnReturn mark_pop_error_on_return;
348
349
#ifdef NODE_FIPS_MODE
350
  if (FIPS_mode()) {
351
    return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env(),
352
        "crypto.createCipher() is not supported in FIPS mode.");
353
  }
354
#endif  // NODE_FIPS_MODE
355
356
88
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
357
88
  if (cipher == nullptr)
358
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
359
360
  unsigned char key[EVP_MAX_KEY_LENGTH];
361
  unsigned char iv[EVP_MAX_IV_LENGTH];
362
363
88
  int key_len = EVP_BytesToKey(cipher,
364
                               EVP_md5(),
365
                               nullptr,
366
                               key_buf.data(),
367
88
                               key_buf.size(),
368
                               1,
369
                               key,
370
88
                               iv);
371
88
  CHECK_NE(key_len, 0);
372
373
88
  const int mode = EVP_CIPHER_mode(cipher);
374

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

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

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

2830
  if (!is_authenticated_mode &&
436

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

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

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

376
  if (cipher->ctx_ ||
590

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

293
  if (!cipher->ctx_ ||
606
194
      !cipher->IsAuthenticatedMode() ||
607

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

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

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

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

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

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


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

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

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

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

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

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


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


138
  if (!ctx)
894
    return false;
895


138
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
896
1
    return false;
897


137
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
898
    return false;
899
900


137
  if (digest != nullptr) {
901


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


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


4
    CHECK_NOT_NULL(label);
909


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


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


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


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


144
  if (!pkey)
953
4
    return;
954
955


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


140
  if (UNLIKELY(!buf.CheckSizeInt32()))
957
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
958
959
  uint32_t padding;
960


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


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


23
    if (digest == nullptr)
967


2
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
968
  }
969
970


274
  ArrayBufferOrViewContents<unsigned char> oaep_label;
971


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


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


274
  AllocatedBuffer out;
978


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


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


272
    args.GetReturnValue().Set(result);
986
}
987
988
}  // namespace crypto
989

14034
}  // namespace node