GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_hash.cc Lines: 137 161 85.1 %
Date: 2022-03-07 04:14:56 Branches: 68 110 61.8 %

Line Branch Exec Source
1
#include "crypto/crypto_hash.h"
2
#include "allocated_buffer-inl.h"
3
#include "async_wrap-inl.h"
4
#include "base_object-inl.h"
5
#include "env-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "string_bytes.h"
8
#include "threadpoolwork-inl.h"
9
#include "v8.h"
10
11
#include <cstdio>
12
13
namespace node {
14
15
using v8::FunctionCallbackInfo;
16
using v8::FunctionTemplate;
17
using v8::Just;
18
using v8::Local;
19
using v8::Maybe;
20
using v8::MaybeLocal;
21
using v8::Nothing;
22
using v8::Object;
23
using v8::Uint32;
24
using v8::Value;
25
26
namespace crypto {
27
1296
Hash::Hash(Environment* env, Local<Object> wrap) : BaseObject(env, wrap) {
28
1296
  MakeWeak();
29
1296
}
30
31
void Hash::MemoryInfo(MemoryTracker* tracker) const {
32
  tracker->TrackFieldWithSize("mdctx", mdctx_ ? kSizeOf_EVP_MD_CTX : 0);
33
  tracker->TrackFieldWithSize("md", digest_ ? md_len_ : 0);
34
}
35
36
4
void Hash::GetHashes(const FunctionCallbackInfo<Value>& args) {
37
4
  Environment* env = Environment::GetCurrent(args);
38
8
  MarkPopErrorOnReturn mark_pop_error_on_return;
39
4
  CipherPushContext ctx(env);
40
4
  EVP_MD_do_all_sorted(
41
#if OPENSSL_VERSION_MAJOR >= 3
42
    array_push_back<EVP_MD,
43
                    EVP_MD_fetch,
44
                    EVP_MD_free,
45
                    EVP_get_digestbyname,
46
                    EVP_MD_get0_name>,
47
#else
48
    array_push_back<EVP_MD>,
49
#endif
50
    &ctx);
51
8
  args.GetReturnValue().Set(ctx.ToJSArray());
52
4
}
53
54
4394
void Hash::Initialize(Environment* env, Local<Object> target) {
55
4394
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
56
57
8788
  t->InstanceTemplate()->SetInternalFieldCount(
58
      Hash::kInternalFieldCount);
59
4394
  t->Inherit(BaseObject::GetConstructorTemplate(env));
60
61
4394
  env->SetProtoMethod(t, "update", HashUpdate);
62
4394
  env->SetProtoMethod(t, "digest", HashDigest);
63
64
4394
  env->SetConstructorFunction(target, "Hash", t);
65
66
4394
  env->SetMethodNoSideEffect(target, "getHashes", GetHashes);
67
68
4394
  HashJob::Initialize(env, target);
69
4394
}
70
71
4955
void Hash::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
72
4955
  registry->Register(New);
73
4955
  registry->Register(HashUpdate);
74
4955
  registry->Register(HashDigest);
75
4955
  registry->Register(GetHashes);
76
77
4955
  HashJob::RegisterExternalReferences(registry);
78
4955
}
79
80
1296
void Hash::New(const FunctionCallbackInfo<Value>& args) {
81
1296
  Environment* env = Environment::GetCurrent(args);
82
83
1296
  const Hash* orig = nullptr;
84
1296
  const EVP_MD* md = nullptr;
85
86
1296
  if (args[0]->IsObject()) {
87
13
    ASSIGN_OR_RETURN_UNWRAP(&orig, args[0].As<Object>());
88
5
    md = EVP_MD_CTX_md(orig->mdctx_.get());
89
  } else {
90
2582
    const Utf8Value hash_type(env->isolate(), args[0]);
91
1291
    md = EVP_get_digestbyname(*hash_type);
92
  }
93
94
1296
  Maybe<unsigned int> xof_md_len = Nothing<unsigned int>();
95
2592
  if (!args[1]->IsUndefined()) {
96
13
    CHECK(args[1]->IsUint32());
97
26
    xof_md_len = Just<unsigned int>(args[1].As<Uint32>()->Value());
98
  }
99
100
1296
  Hash* hash = new Hash(env, args.This());
101

1296
  if (md == nullptr || !hash->HashInit(md, xof_md_len)) {
102
3
    return ThrowCryptoError(env, ERR_get_error(),
103
3
                            "Digest method not supported");
104
  }
105
106

1298
  if (orig != nullptr &&
107
5
      0 >= EVP_MD_CTX_copy(hash->mdctx_.get(), orig->mdctx_.get())) {
108
    return ThrowCryptoError(env, ERR_get_error(), "Digest copy error");
109
  }
110
}
111
112
1294
bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
113
1294
  mdctx_.reset(EVP_MD_CTX_new());
114

1294
  if (!mdctx_ || EVP_DigestInit_ex(mdctx_.get(), md, nullptr) <= 0) {
115
    mdctx_.reset();
116
    return false;
117
  }
118
119
1294
  md_len_ = EVP_MD_size(md);
120

1307
  if (xof_md_len.IsJust() && xof_md_len.FromJust() != md_len_) {
121
    // This is a little hack to cause createHash to fail when an incorrect
122
    // hashSize option was passed for a non-XOF hash function.
123
12
    if ((EVP_MD_flags(md) & EVP_MD_FLAG_XOF) == 0) {
124
1
      EVPerr(EVP_F_EVP_DIGESTFINALXOF, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
125
1
      return false;
126
    }
127
11
    md_len_ = xof_md_len.FromJust();
128
  }
129
130
1293
  return true;
131
}
132
133
1413
bool Hash::HashUpdate(const char* data, size_t len) {
134
1413
  if (!mdctx_)
135
    return false;
136
1413
  return EVP_DigestUpdate(mdctx_.get(), data, len) == 1;
137
}
138
139
1413
void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
140
1413
  Decode<Hash>(args, [](Hash* hash, const FunctionCallbackInfo<Value>& args,
141
1413
                        const char* data, size_t size) {
142
1413
    Environment* env = Environment::GetCurrent(args);
143
1413
    if (UNLIKELY(size > INT_MAX))
144
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
145
1413
    bool r = hash->HashUpdate(data, size);
146
2826
    args.GetReturnValue().Set(r);
147
  });
148
1413
}
149
150
1230
void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
151
1230
  Environment* env = Environment::GetCurrent(args);
152
153
  Hash* hash;
154
1230
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
155
156
1230
  enum encoding encoding = BUFFER;
157
1230
  if (args.Length() >= 1) {
158
1218
    encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
159
  }
160
161
1230
  unsigned int len = hash->md_len_;
162
163
  // TODO(tniessen): SHA3_squeeze does not work for zero-length outputs on all
164
  // platforms and will cause a segmentation fault if called. This workaround
165
  // causes hash.digest() to correctly return an empty buffer / string.
166
  // See https://github.com/openssl/openssl/issues/9431.
167
168

1230
  if (!hash->digest_ && len > 0) {
169
    // Some hash algorithms such as SHA3 do not support calling
170
    // EVP_DigestFinal_ex more than once, however, Hash._flush
171
    // and Hash.digest can both be used to retrieve the digest,
172
    // so we need to cache it.
173
    // See https://github.com/nodejs/node/issues/28245.
174
175
1227
    char* md_value = MallocOpenSSL<char>(len);
176
1227
    ByteSource digest = ByteSource::Allocated(md_value, len);
177
178
1227
    size_t default_len = EVP_MD_CTX_size(hash->mdctx_.get());
179
    int ret;
180
1227
    if (len == default_len) {
181
1221
      ret = EVP_DigestFinal_ex(
182
1221
          hash->mdctx_.get(),
183
          reinterpret_cast<unsigned char*>(md_value),
184
          &len);
185
      // The output length should always equal hash->md_len_
186
1221
      CHECK_EQ(len, hash->md_len_);
187
    } else {
188
6
      ret = EVP_DigestFinalXOF(
189
6
          hash->mdctx_.get(),
190
          reinterpret_cast<unsigned char*>(md_value),
191
          len);
192
    }
193
194
1227
    if (ret != 1)
195
      return ThrowCryptoError(env, ERR_get_error());
196
197
1227
    hash->digest_ = std::move(digest);
198
  }
199
200
  Local<Value> error;
201
  MaybeLocal<Value> rc =
202
      StringBytes::Encode(env->isolate(),
203
1230
                          hash->digest_.get(),
204
                          len,
205
                          encoding,
206
1230
                          &error);
207
1230
  if (rc.IsEmpty()) {
208
    CHECK(!error.IsEmpty());
209
    env->isolate()->ThrowException(error);
210
    return;
211
  }
212
3690
  args.GetReturnValue().Set(rc.FromMaybe(Local<Value>()));
213
}
214
215
141
HashConfig::HashConfig(HashConfig&& other) noexcept
216
141
    : mode(other.mode),
217
141
      in(std::move(other.in)),
218
141
      digest(other.digest),
219
141
      length(other.length) {}
220
221
HashConfig& HashConfig::operator=(HashConfig&& other) noexcept {
222
  if (&other == this) return *this;
223
  this->~HashConfig();
224
  return *new (this) HashConfig(std::move(other));
225
}
226
227
void HashConfig::MemoryInfo(MemoryTracker* tracker) const {
228
  // If the Job is sync, then the HashConfig does not own the data.
229
  if (mode == kCryptoJobAsync)
230
    tracker->TrackFieldWithSize("in", in.size());
231
}
232
233
141
Maybe<bool> HashTraits::EncodeOutput(
234
    Environment* env,
235
    const HashConfig& params,
236
    ByteSource* out,
237
    v8::Local<v8::Value>* result) {
238
282
  *result = out->ToArrayBuffer(env);
239
141
  return Just(!result->IsEmpty());
240
}
241
242
154
Maybe<bool> HashTraits::AdditionalConfig(
243
    CryptoJobMode mode,
244
    const FunctionCallbackInfo<Value>& args,
245
    unsigned int offset,
246
    HashConfig* params) {
247
154
  Environment* env = Environment::GetCurrent(args);
248
249
154
  params->mode = mode;
250
251

462
  CHECK(args[offset]->IsString());  // Hash algorithm
252
462
  Utf8Value digest(env->isolate(), args[offset]);
253
154
  params->digest = EVP_get_digestbyname(*digest);
254
154
  if (UNLIKELY(params->digest == nullptr)) {
255
12
    THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Invalid digest: %s", *digest);
256
12
    return Nothing<bool>();
257
  }
258
259
426
  ArrayBufferOrViewContents<char> data(args[offset + 1]);
260
142
  if (UNLIKELY(!data.CheckSizeInt32())) {
261
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
262
    return Nothing<bool>();
263
  }
264
  params->in = mode == kCryptoJobAsync
265
284
      ? data.ToCopy()
266
142
      : data.ToByteSource();
267
268
142
  unsigned int expected = EVP_MD_size(params->digest);
269
142
  params->length = expected;
270

284
  if (UNLIKELY(args[offset + 2]->IsUint32())) {
271
    // length is expressed in terms of bits
272
5
    params->length =
273
10
        static_cast<uint32_t>(args[offset + 2]
274
5
            .As<Uint32>()->Value()) / CHAR_BIT;
275
5
    if (params->length != expected) {
276
1
      if ((EVP_MD_flags(params->digest) & EVP_MD_FLAG_XOF) == 0) {
277
1
        THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Digest method not supported");
278
1
        return Nothing<bool>();
279
      }
280
    }
281
  }
282
283
141
  return Just(true);
284
}
285
286
141
bool HashTraits::DeriveBits(
287
    Environment* env,
288
    const HashConfig& params,
289
    ByteSource* out) {
290
282
  EVPMDPointer ctx(EVP_MD_CTX_new());
291
292
423
  if (UNLIKELY(!ctx ||
293
               EVP_DigestInit_ex(ctx.get(), params.digest, nullptr) <= 0 ||
294
               EVP_DigestUpdate(
295
                   ctx.get(),
296
                   params.in.get(),
297


423
                   params.in.size()) <= 0)) {
298
    return false;
299
  }
300
301
141
  if (LIKELY(params.length > 0)) {
302
141
    unsigned int length = params.length;
303
141
    char* data = MallocOpenSSL<char>(length);
304
141
    ByteSource buf = ByteSource::Allocated(data, length);
305
141
    unsigned char* ptr = reinterpret_cast<unsigned char*>(data);
306
307
141
    size_t expected = EVP_MD_CTX_size(ctx.get());
308
309
141
    int ret = (length == expected)
310
141
        ? EVP_DigestFinal_ex(ctx.get(), ptr, &length)
311
        : EVP_DigestFinalXOF(ctx.get(), ptr, length);
312
313
141
    if (UNLIKELY(ret != 1))
314
      return false;
315
316
141
    *out = std::move(buf);
317
  }
318
319
141
  return true;
320
}
321
322
}  // namespace crypto
323
}  // namespace node