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: 28 480 5.8 %
Date: 2021-02-19 04:08:54 Branches: 2 611 0.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
bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
33
  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
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
37
         mode == EVP_CIPH_CCM_MODE ||
38
         mode == EVP_CIPH_GCM_MODE ||
39
         IS_OCB_MODE(mode);
40
}
41
42
bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
43
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
44
  return IsSupportedAuthenticatedMode(cipher);
45
}
46
47
bool IsValidGCMTagLength(unsigned int tag_len) {
48
  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
void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
53
  Environment* env = Environment::GetCurrent(args);
54
  CHECK(args[0]->IsObject());
55
  Local<Object> info = args[0].As<Object>();
56
57
  CHECK(args[1]->IsString() || args[1]->IsInt32());
58
59
  const EVP_CIPHER* cipher;
60
  if (args[1]->IsString()) {
61
    Utf8Value name(env->isolate(), args[1]);
62
    cipher = EVP_get_cipherbyname(*name);
63
  } else {
64
    int nid = args[1].As<Int32>()->Value();
65
    cipher = EVP_get_cipherbyname(OBJ_nid2sn(nid));
66
  }
67
68
  if (cipher == nullptr)
69
    return;
70
71
  int mode = EVP_CIPHER_mode(cipher);
72
  int iv_length = EVP_CIPHER_iv_length(cipher);
73
  int key_length = EVP_CIPHER_key_length(cipher);
74
  int block_length = EVP_CIPHER_block_size(cipher);
75
  const char* mode_label = nullptr;
76
  switch (mode) {
77
    case EVP_CIPH_CBC_MODE: mode_label = "cbc"; break;
78
    case EVP_CIPH_CCM_MODE: mode_label = "ccm"; break;
79
    case EVP_CIPH_CFB_MODE: mode_label = "cfb"; break;
80
    case EVP_CIPH_CTR_MODE: mode_label = "ctr"; break;
81
    case EVP_CIPH_ECB_MODE: mode_label = "ecb"; break;
82
    case EVP_CIPH_GCM_MODE: mode_label = "gcm"; break;
83
    case EVP_CIPH_OCB_MODE: mode_label = "ocb"; break;
84
    case EVP_CIPH_OFB_MODE: mode_label = "ofb"; break;
85
    case EVP_CIPH_WRAP_MODE: mode_label = "wrap"; break;
86
    case EVP_CIPH_XTS_MODE: mode_label = "xts"; break;
87
    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
  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
    CipherCtxPointer ctx(EVP_CIPHER_CTX_new());
100
    if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr, 1))
101
      return;
102
103
    if (args[2]->IsInt32()) {
104
      int check_len = args[2].As<Int32>()->Value();
105
      if (!EVP_CIPHER_CTX_set_key_length(ctx.get(), check_len))
106
        return;
107
      key_length = check_len;
108
    }
109
110
    if (args[3]->IsInt32()) {
111
      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
      switch (mode) {
117
        case EVP_CIPH_CCM_MODE:
118
          if (check_len < 7 || check_len > 13)
119
            return;
120
          break;
121
        case EVP_CIPH_GCM_MODE:
122
          // Fall through
123
        case EVP_CIPH_OCB_MODE:
124
          if (!EVP_CIPHER_CTX_ctrl(
125
                  ctx.get(),
126
                  EVP_CTRL_AEAD_SET_IVLEN,
127
                  check_len,
128
                  nullptr)) {
129
            return;
130
          }
131
          break;
132
        default:
133
          if (check_len != iv_length)
134
            return;
135
      }
136
      iv_length = check_len;
137
    }
138
  }
139
140
  if (mode_label != nullptr &&
141
      info->Set(
142
          env->context(),
143
          FIXED_ONE_BYTE_STRING(env->isolate(), "mode"),
144
          OneByteString(env->isolate(), mode_label)).IsNothing()) {
145
    return;
146
  }
147
148
  if (info->Set(
149
          env->context(),
150
          env->name_string(),
151
          OneByteString(env->isolate(), EVP_CIPHER_name(cipher))).IsNothing()) {
152
    return;
153
  }
154
155
  if (info->Set(
156
          env->context(),
157
          FIXED_ONE_BYTE_STRING(env->isolate(), "nid"),
158
          Int32::New(env->isolate(), EVP_CIPHER_nid(cipher))).IsNothing()) {
159
    return;
160
  }
161
162
  // Stream ciphers do not have a meaningful block size
163
  if (mode != EVP_CIPH_STREAM_CIPHER &&
164
      info->Set(
165
          env->context(),
166
          FIXED_ONE_BYTE_STRING(env->isolate(), "blockSize"),
167
          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
  if (iv_length != 0 &&
173
      info->Set(
174
          env->context(),
175
          FIXED_ONE_BYTE_STRING(env->isolate(), "ivLength"),
176
          Int32::New(env->isolate(), iv_length)).IsNothing()) {
177
    return;
178
  }
179
180
  if (info->Set(
181
          env->context(),
182
          FIXED_ONE_BYTE_STRING(env->isolate(), "keyLength"),
183
          Int32::New(env->isolate(), key_length)).IsNothing()) {
184
    return;
185
  }
186
187
  args.GetReturnValue().Set(info);
188
}
189
}  // namespace
190
191
void CipherBase::GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
192
  Environment* env = Environment::GetCurrent(args);
193
194
  SSLCtxPointer ctx(SSL_CTX_new(TLS_method()));
195
  CHECK(ctx);
196
197
  SSLPointer ssl(SSL_new(ctx.get()));
198
  CHECK(ssl);
199
200
  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
  const int n = sk_SSL_CIPHER_num(ciphers);
215
  std::vector<Local<Value>> arr(n + arraysize(TLS13_CIPHERS));
216
217
  for (int i = 0; i < n; ++i) {
218
    const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
219
    arr[i] = OneByteString(env->isolate(), SSL_CIPHER_get_name(cipher));
220
  }
221
222
  for (unsigned i = 0; i < arraysize(TLS13_CIPHERS); ++i) {
223
    const char* name = TLS13_CIPHERS[i];
224
    arr[n + i] = OneByteString(env->isolate(), name);
225
  }
226
227
  args.GetReturnValue().Set(Array::New(env->isolate(), arr.data(), arr.size()));
228
}
229
230
void CipherBase::GetCiphers(const FunctionCallbackInfo<Value>& args) {
231
  Environment* env = Environment::GetCurrent(args);
232
  CipherPushContext ctx(env);
233
  EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &ctx);
234
  args.GetReturnValue().Set(ctx.ToJSArray());
235
}
236
237
CipherBase::CipherBase(Environment* env,
238
                       Local<Object> wrap,
239
                       CipherKind kind)
240
    : BaseObject(env, wrap),
241
      ctx_(nullptr),
242
      kind_(kind),
243
      auth_tag_state_(kAuthTagUnknown),
244
      auth_tag_len_(kNoAuthTagLength),
245
      pending_auth_failed_(false) {
246
  MakeWeak();
247
}
248
249
void CipherBase::MemoryInfo(MemoryTracker* tracker) const {
250
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_EVP_CIPHER_CTX : 0);
251
}
252
253
2
void CipherBase::Initialize(Environment* env, Local<Object> target) {
254
2
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
255
256
6
  t->InstanceTemplate()->SetInternalFieldCount(
257
2
      CipherBase::kInternalFieldCount);
258
4
  t->Inherit(BaseObject::GetConstructorTemplate(env));
259
260
2
  env->SetProtoMethod(t, "init", Init);
261
2
  env->SetProtoMethod(t, "initiv", InitIv);
262
2
  env->SetProtoMethod(t, "update", Update);
263
2
  env->SetProtoMethod(t, "final", Final);
264
2
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
265
2
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
266
2
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
267
2
  env->SetProtoMethod(t, "setAAD", SetAAD);
268
2
  env->SetConstructorFunction(target, "CipherBase", t);
269
270
2
  env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers);
271
2
  env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers);
272
273
  env->SetMethod(target, "publicEncrypt",
274
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
275
                                         EVP_PKEY_encrypt_init,
276
2
                                         EVP_PKEY_encrypt>);
277
  env->SetMethod(target, "privateDecrypt",
278
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
279
                                         EVP_PKEY_decrypt_init,
280
2
                                         EVP_PKEY_decrypt>);
281
  env->SetMethod(target, "privateEncrypt",
282
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
283
                                         EVP_PKEY_sign_init,
284
2
                                         EVP_PKEY_sign>);
285
  env->SetMethod(target, "publicDecrypt",
286
                 PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
287
                                         EVP_PKEY_verify_recover_init,
288
2
                                         EVP_PKEY_verify_recover>);
289
290
2
  env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo);
291
292
4
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt);
293
2
  NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt);
294
6
}
295
4
296
6
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
297
4
  CHECK(args.IsConstructCall());
298
  Environment* env = Environment::GetCurrent(args);
299
  new CipherBase(env, args.This(), args[0]->IsTrue() ? kCipher : kDecipher);
300
}
301
302
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
  CHECK(!ctx_);
310
  ctx_.reset(EVP_CIPHER_CTX_new());
311
312
  const int mode = EVP_CIPHER_mode(cipher);
313
  if (mode == EVP_CIPH_WRAP_MODE)
314
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
315
316
  const bool encrypt = (kind_ == kCipher);
317
  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
  if (IsSupportedAuthenticatedMode(cipher)) {
324
    CHECK_GE(iv_len, 0);
325
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
326
      return;
327
  }
328
329
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
330
    ctx_.reset();
331
    return THROW_ERR_CRYPTO_INVALID_KEYLEN(env());
332
  }
333
334
  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
void CipherBase::Init(const char* cipher_type,
341
                      const ArrayBufferOrViewContents<unsigned char>& key_buf,
342
                      unsigned int auth_tag_len) {
343
  HandleScope scope(env()->isolate());
344
  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
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
354
  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
  int key_len = EVP_BytesToKey(cipher,
361
                               EVP_md5(),
362
                               nullptr,
363
                               key_buf.data(),
364
                               key_buf.size(),
365
                               1,
366
                               key,
367
                               iv);
368
  CHECK_NE(key_len, 0);
369
370
  const int mode = EVP_CIPHER_mode(cipher);
371
  if (kind_ == kCipher && (mode == EVP_CIPH_CTR_MODE ||
372
                           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
                       cipher_type);
379
  }
380
381
  CommonInit(cipher_type, cipher, key, key_len, iv,
382
             EVP_CIPHER_iv_length(cipher), auth_tag_len);
383
}
384
385
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
386
  CipherBase* cipher;
387
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
388
  Environment* env = Environment::GetCurrent(args);
389
390
  CHECK_GE(args.Length(), 3);
391
392
  const Utf8Value cipher_type(args.GetIsolate(), args[0]);
393
  ArrayBufferOrViewContents<unsigned char> key_buf(args[1]);
394
  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
  if (args[2]->IsUint32()) {
401
    auth_tag_len = args[2].As<Uint32>()->Value();
402
  } else {
403
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
404
    auth_tag_len = kNoAuthTagLength;
405
  }
406
407
  cipher->Init(*cipher_type, key_buf, auth_tag_len);
408
}
409
410
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
  HandleScope scope(env()->isolate());
415
  MarkPopErrorOnReturn mark_pop_error_on_return;
416
417
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
418
  if (cipher == nullptr)
419
    return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env());
420
421
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
422
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
423
  const bool has_iv = iv_buf.size() > 0;
424
425
  // Throw if no IV was passed and the cipher requires an IV
426
  if (!has_iv && expected_iv_len != 0)
427
    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
  if (!is_authenticated_mode &&
433
      has_iv &&
434
      static_cast<int>(iv_buf.size()) != expected_iv_len) {
435
    return THROW_ERR_CRYPTO_INVALID_IV(env());
436
  }
437
438
  if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305) {
439
    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
    if (iv_buf.size() > 12)
444
      return THROW_ERR_CRYPTO_INVALID_IV(env());
445
  }
446
447
  CommonInit(
448
      cipher_type,
449
      cipher,
450
      key_buf.data<unsigned char>(),
451
      key_buf.size(),
452
      iv_buf.data(),
453
      iv_buf.size(),
454
      auth_tag_len);
455
}
456
457
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
458
  CipherBase* cipher;
459
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
460
  Environment* env = cipher->env();
461
462
  CHECK_GE(args.Length(), 4);
463
464
  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
  const ByteSource key_buf = ByteSource::FromSecretKeyBytes(env, args[1]);
470
471
  if (UNLIKELY(key_buf.size() > INT_MAX))
472
    return THROW_ERR_OUT_OF_RANGE(env, "key is too big");
473
474
  ArrayBufferOrViewContents<unsigned char> iv_buf;
475
  if (!args[2]->IsNull())
476
    iv_buf = ArrayBufferOrViewContents<unsigned char>(args[2]);
477
478
  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
  if (args[3]->IsUint32()) {
485
    auth_tag_len = args[3].As<Uint32>()->Value();
486
  } else {
487
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
488
    auth_tag_len = kNoAuthTagLength;
489
  }
490
491
  cipher->InitIv(*cipher_type, key_buf, iv_buf, auth_tag_len);
492
}
493
494
bool CipherBase::InitAuthenticated(
495
    const char* cipher_type,
496
    int iv_len,
497
    unsigned int auth_tag_len) {
498
  CHECK(IsAuthenticatedMode());
499
  MarkPopErrorOnReturn mark_pop_error_on_return;
500
501
  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
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
510
  if (mode == EVP_CIPH_GCM_MODE) {
511
    if (auth_tag_len != kNoAuthTagLength) {
512
      if (!IsValidGCMTagLength(auth_tag_len)) {
513
        char msg[50];
514
        snprintf(msg, sizeof(msg),
515
            "Invalid authentication tag length: %u", auth_tag_len);
516
        THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env(), msg);
517
        return false;
518
      }
519
520
      // Remember the given authentication tag length for later.
521
      auth_tag_len_ = auth_tag_len;
522
    }
523
  } else {
524
    if (auth_tag_len == kNoAuthTagLength) {
525
      char msg[128];
526
      snprintf(msg, sizeof(msg), "authTagLength required for %s", cipher_type);
527
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env(), msg);
528
      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
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len,
542
                             nullptr)) {
543
      THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env());
544
      return false;
545
    }
546
547
    // Remember the given authentication tag length for later.
548
    auth_tag_len_ = auth_tag_len;
549
550
    if (mode == EVP_CIPH_CCM_MODE) {
551
      // Restrict the message length to min(INT_MAX, 2^(8*(15-iv_len))-1) bytes.
552
      CHECK(iv_len >= 7 && iv_len <= 13);
553
      max_message_size_ = INT_MAX;
554
      if (iv_len == 12) max_message_size_ = 16777215;
555
      if (iv_len == 13) max_message_size_ = 65535;
556
    }
557
  }
558
559
  return true;
560
}
561
562
bool CipherBase::CheckCCMMessageLength(int message_len) {
563
  CHECK(ctx_);
564
  CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE);
565
566
  if (message_len > max_message_size_) {
567
    THROW_ERR_CRYPTO_INVALID_MESSAGELEN(env());
568
    return false;
569
  }
570
571
  return true;
572
}
573
574
bool CipherBase::IsAuthenticatedMode() const {
575
  // Check if this cipher operates in an AEAD mode that we support.
576
  CHECK(ctx_);
577
  return IsSupportedAuthenticatedMode(ctx_.get());
578
}
579
580
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
581
  Environment* env = Environment::GetCurrent(args);
582
  CipherBase* cipher;
583
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
584
585
  // Only callable after Final and if encrypting.
586
  if (cipher->ctx_ ||
587
      cipher->kind_ != kCipher ||
588
      cipher->auth_tag_len_ == kNoAuthTagLength) {
589
    return;
590
  }
591
592
  args.GetReturnValue().Set(
593
      Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
594
          .FromMaybe(Local<Value>()));
595
}
596
597
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
598
  CipherBase* cipher;
599
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
600
  Environment* env = Environment::GetCurrent(args);
601
602
  if (!cipher->ctx_ ||
603
      !cipher->IsAuthenticatedMode() ||
604
      cipher->kind_ != kDecipher ||
605
      cipher->auth_tag_state_ != kAuthTagUnknown) {
606
    return args.GetReturnValue().Set(false);
607
  }
608
609
  ArrayBufferOrViewContents<char> auth_tag(args[0]);
610
  if (UNLIKELY(!auth_tag.CheckSizeInt32()))
611
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
612
613
  unsigned int tag_len = auth_tag.size();
614
615
  const int mode = EVP_CIPHER_CTX_mode(cipher->ctx_.get());
616
  bool is_valid;
617
  if (mode == EVP_CIPH_GCM_MODE) {
618
    // Restrict GCM tag lengths according to NIST 800-38d, page 9.
619
    is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
620
                cipher->auth_tag_len_ == tag_len) &&
621
               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
    CHECK(IsSupportedAuthenticatedMode(cipher->ctx_.get()));
626
    CHECK_NE(cipher->auth_tag_len_, kNoAuthTagLength);
627
    is_valid = cipher->auth_tag_len_ == tag_len;
628
  }
629
630
  if (!is_valid) {
631
    char msg[50];
632
    snprintf(msg, sizeof(msg),
633
        "Invalid authentication tag length: %u", tag_len);
634
    return THROW_ERR_CRYPTO_INVALID_AUTH_TAG(env, msg);
635
  }
636
637
  cipher->auth_tag_len_ = tag_len;
638
  cipher->auth_tag_state_ = kAuthTagKnown;
639
  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
640
641
  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
642
  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
643
644
  args.GetReturnValue().Set(true);
645
}
646
647
bool CipherBase::MaybePassAuthTagToOpenSSL() {
648
  if (auth_tag_state_ == kAuthTagKnown) {
649
    if (!EVP_CIPHER_CTX_ctrl(ctx_.get(),
650
                             EVP_CTRL_AEAD_SET_TAG,
651
                             auth_tag_len_,
652
                             reinterpret_cast<unsigned char*>(auth_tag_))) {
653
      return false;
654
    }
655
    auth_tag_state_ = kAuthTagPassedToOpenSSL;
656
  }
657
  return true;
658
}
659
660
bool CipherBase::SetAAD(
661
    const ArrayBufferOrViewContents<unsigned char>& data,
662
    int plaintext_len) {
663
  if (!ctx_ || !IsAuthenticatedMode())
664
    return false;
665
  MarkPopErrorOnReturn mark_pop_error_on_return;
666
667
  int outlen;
668
  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
  if (mode == EVP_CIPH_CCM_MODE) {
673
    if (plaintext_len < 0) {
674
      THROW_ERR_MISSING_ARGS(env(),
675
          "options.plaintextLength required for CCM mode with AAD");
676
      return false;
677
    }
678
679
    if (!CheckCCMMessageLength(plaintext_len))
680
      return false;
681
682
    if (kind_ == kDecipher) {
683
      if (!MaybePassAuthTagToOpenSSL())
684
        return false;
685
    }
686
687
    // Specify the plaintext length.
688
    if (!EVP_CipherUpdate(ctx_.get(), nullptr, &outlen, nullptr, plaintext_len))
689
      return false;
690
  }
691
692
  return 1 == EVP_CipherUpdate(ctx_.get(),
693
                               nullptr,
694
                               &outlen,
695
                               data.data(),
696
                               data.size());
697
}
698
699
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
700
  CipherBase* cipher;
701
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
702
  Environment* env = Environment::GetCurrent(args);
703
704
  CHECK_EQ(args.Length(), 2);
705
  CHECK(args[1]->IsInt32());
706
  int plaintext_len = args[1].As<Int32>()->Value();
707
  ArrayBufferOrViewContents<unsigned char> buf(args[0]);
708
709
  if (UNLIKELY(!buf.CheckSizeInt32()))
710
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too big");
711
  args.GetReturnValue().Set(cipher->SetAAD(buf, plaintext_len));
712
}
713
714
CipherBase::UpdateResult CipherBase::Update(
715
    const char* data,
716
    size_t len,
717
    AllocatedBuffer* out) {
718
  if (!ctx_ || len > INT_MAX)
719
    return kErrorState;
720
  MarkPopErrorOnReturn mark_pop_error_on_return;
721
722
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
723
724
  if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
725
    return kErrorMessageSize;
726
727
  // Pass the authentication tag to OpenSSL if possible. This will only happen
728
  // once, usually on the first update.
729
  if (kind_ == kDecipher && IsAuthenticatedMode())
730
    CHECK(MaybePassAuthTagToOpenSSL());
731
732
  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
  if (kind_ == kCipher && mode == EVP_CIPH_WRAP_MODE &&
736
      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
  *out = AllocatedBuffer::AllocateManaged(env(), buf_len);
745
  int r = EVP_CipherUpdate(ctx_.get(),
746
                           reinterpret_cast<unsigned char*>(out->data()),
747
                           &buf_len,
748
                           reinterpret_cast<const unsigned char*>(data),
749
                           len);
750
751
  CHECK_LE(static_cast<size_t>(buf_len), out->size());
752
  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
  if (!r && kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
757
    pending_auth_failed_ = true;
758
    return kSuccess;
759
  }
760
  return r == 1 ? kSuccess : kErrorState;
761
}
762
763
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
764
  Decode<CipherBase>(args, [](CipherBase* cipher,
765
                              const FunctionCallbackInfo<Value>& args,
766
                              const char* data, size_t size) {
767
    AllocatedBuffer out;
768
    Environment* env = Environment::GetCurrent(args);
769
770
    if (UNLIKELY(size > INT_MAX))
771
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
772
773
    UpdateResult r = cipher->Update(data, size, &out);
774
775
    if (r != kSuccess) {
776
      if (r == kErrorState) {
777
        ThrowCryptoError(env, ERR_get_error(),
778
                         "Trying to add data in unsupported state");
779
      }
780
      return;
781
    }
782
783
    CHECK(out.data() != nullptr || out.size() == 0);
784
    args.GetReturnValue().Set(out.ToBuffer().FromMaybe(Local<Value>()));
785
  });
786
}
787
788
bool CipherBase::SetAutoPadding(bool auto_padding) {
789
  if (!ctx_)
790
    return false;
791
  MarkPopErrorOnReturn mark_pop_error_on_return;
792
  return EVP_CIPHER_CTX_set_padding(ctx_.get(), auto_padding);
793
}
794
795
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
796
  CipherBase* cipher;
797
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
798
799
  bool b = cipher->SetAutoPadding(args.Length() < 1 || args[0]->IsTrue());
800
  args.GetReturnValue().Set(b);  // Possibly report invalid state failure
801
}
802
803
bool CipherBase::Final(AllocatedBuffer* out) {
804
  if (!ctx_)
805
    return false;
806
807
  const int mode = EVP_CIPHER_CTX_mode(ctx_.get());
808
809
  *out = AllocatedBuffer::AllocateManaged(
810
      env(),
811
      static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
812
813
  if (kind_ == kDecipher && IsSupportedAuthenticatedMode(ctx_.get())) {
814
    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
  if (kind_ == kDecipher && mode == EVP_CIPH_CCM_MODE) {
821
    ok = !pending_auth_failed_;
822
    *out = AllocatedBuffer::AllocateManaged(env(), 0);  // Empty buffer.
823
  } else {
824
    int out_len = out->size();
825
    ok = EVP_CipherFinal_ex(ctx_.get(),
826
                            reinterpret_cast<unsigned char*>(out->data()),
827
                            &out_len) == 1;
828
829
    if (out_len >= 0)
830
      out->Resize(out_len);
831
    else
832
      *out = AllocatedBuffer();  // *out will not be used.
833
834
    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
      if (auth_tag_len_ == kNoAuthTagLength) {
839
        CHECK(mode == EVP_CIPH_GCM_MODE);
840
        auth_tag_len_ = sizeof(auth_tag_);
841
      }
842
      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
  ctx_.reset();
849
850
  return ok;
851
}
852
853
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
854
  Environment* env = Environment::GetCurrent(args);
855
856
  CipherBase* cipher;
857
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
858
  if (cipher->ctx_ == nullptr)
859
    return THROW_ERR_CRYPTO_INVALID_STATE(env);
860
861
  AllocatedBuffer out;
862
863
  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
864
  const bool is_auth_mode = cipher->IsAuthenticatedMode();
865
  bool r = cipher->Final(&out);
866
867
  if (!r) {
868
    const char* msg = is_auth_mode
869
                          ? "Unsupported state or unable to authenticate data"
870
                          : "Unsupported state";
871
872
    return ThrowCryptoError(env, ERR_get_error(), msg);
873
  }
874
875
  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
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
  EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(pkey.get(), nullptr));
890
  if (!ctx)
891
    return false;
892
  if (EVP_PKEY_cipher_init(ctx.get()) <= 0)
893
    return false;
894
  if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0)
895
    return false;
896
897
  if (digest != nullptr) {
898
    if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), digest) <= 0)
899
      return false;
900
  }
901
902
  if (oaep_label.size() != 0) {
903
    // OpenSSL takes ownership of the label, so we need to create a copy.
904
    void* label = OPENSSL_memdup(oaep_label.data(), oaep_label.size());
905
    CHECK_NOT_NULL(label);
906
    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
  size_t out_len = 0;
915
  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
  *out = AllocatedBuffer::AllocateManaged(env, out_len);
925
926
  if (EVP_PKEY_cipher(
927
          ctx.get(),
928
          reinterpret_cast<unsigned char*>(out->data()),
929
          &out_len,
930
          data.data(),
931
          data.size()) <= 0) {
932
    return false;
933
  }
934
935
  out->Resize(out_len);
936
  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
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
943
  MarkPopErrorOnReturn mark_pop_error_on_return;
944
  Environment* env = Environment::GetCurrent(args);
945
946
  unsigned int offset = 0;
947
  ManagedEVPPKey pkey =
948
      ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
949
  if (!pkey)
950
    return;
951
952
  ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
953
  if (UNLIKELY(!buf.CheckSizeInt32()))
954
    return THROW_ERR_OUT_OF_RANGE(env, "buffer is too long");
955
956
  uint32_t padding;
957
  if (!args[offset + 1]->Uint32Value(env->context()).To(&padding)) return;
958
959
  const EVP_MD* digest = nullptr;
960
  if (args[offset + 2]->IsString()) {
961
    const Utf8Value oaep_str(env->isolate(), args[offset + 2]);
962
    digest = EVP_get_digestbyname(*oaep_str);
963
    if (digest == nullptr)
964
      return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
965
  }
966
967
  ArrayBufferOrViewContents<unsigned char> oaep_label;
968
  if (!args[offset + 3]->IsUndefined()) {
969
    oaep_label = ArrayBufferOrViewContents<unsigned char>(args[offset + 3]);
970
    if (UNLIKELY(!oaep_label.CheckSizeInt32()))
971
      return THROW_ERR_OUT_OF_RANGE(env, "oaep_label is too big");
972
  }
973
974
  AllocatedBuffer out;
975
  if (!Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
976
          env, pkey, padding, digest, oaep_label, buf, &out)) {
977
    return ThrowCryptoError(env, ERR_get_error());
978
  }
979
980
  Local<Value> result;
981
  if (out.ToBuffer().ToLocal(&result))
982
    args.GetReturnValue().Set(result);
983
}
984
985
}  // namespace crypto
986

366
}  // namespace node