GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_hash.cc Lines: 133 157 84.7 %
Date: 2022-06-15 16:51:59 Branches: 68 110 61.8 %

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

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

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

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

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

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

462
  CHECK(args[offset]->IsString());  // Hash algorithm
242
462
  Utf8Value digest(env->isolate(), args[offset]);
243
154
  params->digest = EVP_get_digestbyname(*digest);
244
154
  if (UNLIKELY(params->digest == nullptr)) {
245
12
    THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Invalid digest: %s", *digest);
246
12
    return Nothing<bool>();
247
  }
248
249
426
  ArrayBufferOrViewContents<char> data(args[offset + 1]);
250
142
  if (UNLIKELY(!data.CheckSizeInt32())) {
251
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
252
    return Nothing<bool>();
253
  }
254
  params->in = mode == kCryptoJobAsync
255
284
      ? data.ToCopy()
256
142
      : data.ToByteSource();
257
258
142
  unsigned int expected = EVP_MD_size(params->digest);
259
142
  params->length = expected;
260

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


423
                   ctx.get(), params.in.data<char>(), params.in.size()) <= 0)) {
286
    return false;
287
  }
288
289
141
  if (LIKELY(params.length > 0)) {
290
141
    unsigned int length = params.length;
291
141
    ByteSource::Builder buf(length);
292
293
141
    size_t expected = EVP_MD_CTX_size(ctx.get());
294
295
    int ret =
296
141
        (length == expected)
297
141
            ? EVP_DigestFinal_ex(ctx.get(), buf.data<unsigned char>(), &length)
298
            : EVP_DigestFinalXOF(ctx.get(), buf.data<unsigned char>(), length);
299
300
141
    if (UNLIKELY(ret != 1))
301
      return false;
302
303
141
    *out = std::move(buf).release();
304
  }
305
306
141
  return true;
307
}
308
309
}  // namespace crypto
310
}  // namespace node