GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_hash.cc Lines: 137 161 85.1 %
Date: 2022-02-02 04:14:51 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
1246
Hash::Hash(Environment* env, Local<Object> wrap) : BaseObject(env, wrap) {
28
1246
  MakeWeak();
29
1246
}
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
4
  CipherPushContext ctx(env);
39
4
  EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &ctx);
40
8
  args.GetReturnValue().Set(ctx.ToJSArray());
41
4
}
42
43
4370
void Hash::Initialize(Environment* env, Local<Object> target) {
44
4370
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
45
46
8740
  t->InstanceTemplate()->SetInternalFieldCount(
47
      Hash::kInternalFieldCount);
48
4370
  t->Inherit(BaseObject::GetConstructorTemplate(env));
49
50
4370
  env->SetProtoMethod(t, "update", HashUpdate);
51
4370
  env->SetProtoMethod(t, "digest", HashDigest);
52
53
4370
  env->SetConstructorFunction(target, "Hash", t);
54
55
4370
  env->SetMethodNoSideEffect(target, "getHashes", GetHashes);
56
57
4370
  HashJob::Initialize(env, target);
58
4370
}
59
60
4927
void Hash::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
61
4927
  registry->Register(New);
62
4927
  registry->Register(HashUpdate);
63
4927
  registry->Register(HashDigest);
64
4927
  registry->Register(GetHashes);
65
66
4927
  HashJob::RegisterExternalReferences(registry);
67
4927
}
68
69
1246
void Hash::New(const FunctionCallbackInfo<Value>& args) {
70
1246
  Environment* env = Environment::GetCurrent(args);
71
72
1246
  const Hash* orig = nullptr;
73
1246
  const EVP_MD* md = nullptr;
74
75
1246
  if (args[0]->IsObject()) {
76
13
    ASSIGN_OR_RETURN_UNWRAP(&orig, args[0].As<Object>());
77
5
    md = EVP_MD_CTX_md(orig->mdctx_.get());
78
  } else {
79
2482
    const Utf8Value hash_type(env->isolate(), args[0]);
80
1241
    md = EVP_get_digestbyname(*hash_type);
81
  }
82
83
1246
  Maybe<unsigned int> xof_md_len = Nothing<unsigned int>();
84
2492
  if (!args[1]->IsUndefined()) {
85
13
    CHECK(args[1]->IsUint32());
86
26
    xof_md_len = Just<unsigned int>(args[1].As<Uint32>()->Value());
87
  }
88
89
1246
  Hash* hash = new Hash(env, args.This());
90

1246
  if (md == nullptr || !hash->HashInit(md, xof_md_len)) {
91
3
    return ThrowCryptoError(env, ERR_get_error(),
92
3
                            "Digest method not supported");
93
  }
94
95

1248
  if (orig != nullptr &&
96
5
      0 >= EVP_MD_CTX_copy(hash->mdctx_.get(), orig->mdctx_.get())) {
97
    return ThrowCryptoError(env, ERR_get_error(), "Digest copy error");
98
  }
99
}
100
101
1244
bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
102
1244
  mdctx_.reset(EVP_MD_CTX_new());
103

1244
  if (!mdctx_ || EVP_DigestInit_ex(mdctx_.get(), md, nullptr) <= 0) {
104
    mdctx_.reset();
105
    return false;
106
  }
107
108
1244
  md_len_ = EVP_MD_size(md);
109

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

1227
  if (!hash->digest_ && len > 0) {
159
    // Some hash algorithms such as SHA3 do not support calling
160
    // EVP_DigestFinal_ex more than once, however, Hash._flush
161
    // and Hash.digest can both be used to retrieve the digest,
162
    // so we need to cache it.
163
    // See https://github.com/nodejs/node/issues/28245.
164
165
1224
    char* md_value = MallocOpenSSL<char>(len);
166
1224
    ByteSource digest = ByteSource::Allocated(md_value, len);
167
168
1224
    size_t default_len = EVP_MD_CTX_size(hash->mdctx_.get());
169
    int ret;
170
1224
    if (len == default_len) {
171
1218
      ret = EVP_DigestFinal_ex(
172
1218
          hash->mdctx_.get(),
173
          reinterpret_cast<unsigned char*>(md_value),
174
          &len);
175
      // The output length should always equal hash->md_len_
176
1218
      CHECK_EQ(len, hash->md_len_);
177
    } else {
178
6
      ret = EVP_DigestFinalXOF(
179
6
          hash->mdctx_.get(),
180
          reinterpret_cast<unsigned char*>(md_value),
181
          len);
182
    }
183
184
1224
    if (ret != 1)
185
      return ThrowCryptoError(env, ERR_get_error());
186
187
1224
    hash->digest_ = std::move(digest);
188
  }
189
190
  Local<Value> error;
191
  MaybeLocal<Value> rc =
192
      StringBytes::Encode(env->isolate(),
193
1227
                          hash->digest_.get(),
194
                          len,
195
                          encoding,
196
1227
                          &error);
197
1227
  if (rc.IsEmpty()) {
198
    CHECK(!error.IsEmpty());
199
    env->isolate()->ThrowException(error);
200
    return;
201
  }
202
3681
  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
                   ctx.get(),
286
                   params.in.get(),
287


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