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_hash.cc Lines: 133 159 83.6 %
Date: 2021-04-18 04:12:15 Branches: 64 106 60.4 %

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
23663
Hash::Hash(Environment* env, Local<Object> wrap) : BaseObject(env, wrap) {
28
23663
  MakeWeak();
29
23663
}
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
7
void Hash::GetHashes(const FunctionCallbackInfo<Value>& args) {
37
7
  Environment* env = Environment::GetCurrent(args);
38
14
  CipherPushContext ctx(env);
39
7
  EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &ctx);
40
21
  args.GetReturnValue().Set(ctx.ToJSArray());
41
7
}
42
43
4098
void Hash::Initialize(Environment* env, Local<Object> target) {
44
4098
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
45
46
12294
  t->InstanceTemplate()->SetInternalFieldCount(
47
4098
      Hash::kInternalFieldCount);
48
8196
  t->Inherit(BaseObject::GetConstructorTemplate(env));
49
50
4098
  env->SetProtoMethod(t, "update", HashUpdate);
51
4098
  env->SetProtoMethod(t, "digest", HashDigest);
52
53
4098
  env->SetConstructorFunction(target, "Hash", t);
54
55
4098
  env->SetMethodNoSideEffect(target, "getHashes", GetHashes);
56
57
4098
  HashJob::Initialize(env, target);
58
4098
}
59
60
23663
void Hash::New(const FunctionCallbackInfo<Value>& args) {
61
23663
  Environment* env = Environment::GetCurrent(args);
62
63
23663
  const Hash* orig = nullptr;
64
23663
  const EVP_MD* md = nullptr;
65
66
47326
  if (args[0]->IsObject()) {
67
13
    ASSIGN_OR_RETURN_UNWRAP(&orig, args[0].As<Object>());
68
5
    md = EVP_MD_CTX_md(orig->mdctx_.get());
69
  } else {
70
47316
    const Utf8Value hash_type(env->isolate(), args[0]);
71
23658
    md = EVP_get_digestbyname(*hash_type);
72
  }
73
74
23663
  Maybe<unsigned int> xof_md_len = Nothing<unsigned int>();
75
70989
  if (!args[1]->IsUndefined()) {
76
26
    CHECK(args[1]->IsUint32());
77
39
    xof_md_len = Just<unsigned int>(args[1].As<Uint32>()->Value());
78
  }
79
80
23663
  Hash* hash = new Hash(env, args.This());
81

23663
  if (md == nullptr || !hash->HashInit(md, xof_md_len)) {
82
3
    return ThrowCryptoError(env, ERR_get_error(),
83
3
                            "Digest method not supported");
84
  }
85
86

23665
  if (orig != nullptr &&
87
5
      0 >= EVP_MD_CTX_copy(hash->mdctx_.get(), orig->mdctx_.get())) {
88
    return ThrowCryptoError(env, ERR_get_error(), "Digest copy error");
89
  }
90
}
91
92
23661
bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
93
23661
  mdctx_.reset(EVP_MD_CTX_new());
94

23661
  if (!mdctx_ || EVP_DigestInit_ex(mdctx_.get(), md, nullptr) <= 0) {
95
    mdctx_.reset();
96
    return false;
97
  }
98
99
23661
  md_len_ = EVP_MD_size(md);
100

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

23645
  if (!hash->digest_ && len > 0) {
150
    // Some hash algorithms such as SHA3 do not support calling
151
    // EVP_DigestFinal_ex more than once, however, Hash._flush
152
    // and Hash.digest can both be used to retrieve the digest,
153
    // so we need to cache it.
154
    // See https://github.com/nodejs/node/issues/28245.
155
156
23642
    char* md_value = MallocOpenSSL<char>(len);
157
47284
    ByteSource digest = ByteSource::Allocated(md_value, len);
158
159
23642
    size_t default_len = EVP_MD_CTX_size(hash->mdctx_.get());
160
    int ret;
161
23642
    if (len == default_len) {
162
23636
      ret = EVP_DigestFinal_ex(
163
23636
          hash->mdctx_.get(),
164
          reinterpret_cast<unsigned char*>(md_value),
165
23636
          &len);
166
      // The output length should always equal hash->md_len_
167
23636
      CHECK_EQ(len, hash->md_len_);
168
    } else {
169
12
      ret = EVP_DigestFinalXOF(
170
6
          hash->mdctx_.get(),
171
          reinterpret_cast<unsigned char*>(md_value),
172
6
          len);
173
    }
174
175
23642
    if (ret != 1)
176
      return ThrowCryptoError(env, ERR_get_error());
177
178
23642
    hash->digest_ = std::move(digest);
179
  }
180
181
  Local<Value> error;
182
  MaybeLocal<Value> rc =
183
      StringBytes::Encode(env->isolate(),
184
23645
                          hash->digest_.get(),
185
                          len,
186
                          encoding,
187
47290
                          &error);
188
23645
  if (rc.IsEmpty()) {
189
    CHECK(!error.IsEmpty());
190
    env->isolate()->ThrowException(error);
191
    return;
192
  }
193
47290
  args.GetReturnValue().Set(rc.FromMaybe(Local<Value>()));
194
}
195
196
73
HashConfig::HashConfig(HashConfig&& other) noexcept
197
73
    : mode(other.mode),
198
73
      in(std::move(other.in)),
199
73
      digest(other.digest),
200
292
      length(other.length) {}
201
202
HashConfig& HashConfig::operator=(HashConfig&& other) noexcept {
203
  if (&other == this) return *this;
204
  this->~HashConfig();
205
  return *new (this) HashConfig(std::move(other));
206
}
207
208
void HashConfig::MemoryInfo(MemoryTracker* tracker) const {
209
  // If the Job is sync, then the HashConfig does not own the data.
210
  if (mode == kCryptoJobAsync)
211
    tracker->TrackFieldWithSize("in", in.size());
212
}
213
214
73
Maybe<bool> HashTraits::EncodeOutput(
215
    Environment* env,
216
    const HashConfig& params,
217
    ByteSource* out,
218
    v8::Local<v8::Value>* result) {
219
146
  *result = out->ToArrayBuffer(env);
220
73
  return Just(!result->IsEmpty());
221
}
222
223
74
Maybe<bool> HashTraits::AdditionalConfig(
224
    CryptoJobMode mode,
225
    const FunctionCallbackInfo<Value>& args,
226
    unsigned int offset,
227
    HashConfig* params) {
228
74
  Environment* env = Environment::GetCurrent(args);
229
230
74
  params->mode = mode;
231
232
296
  CHECK(args[offset]->IsString());  // Hash algorithm
233
222
  Utf8Value digest(env->isolate(), args[offset]);
234
74
  params->digest = EVP_get_digestbyname(*digest);
235
74
  if (UNLIKELY(params->digest == nullptr)) {
236
    char msg[1024];
237
    snprintf(msg, sizeof(msg), "Invalid digest: %s", *digest);
238
    THROW_ERR_CRYPTO_INVALID_DIGEST(env);
239
    return Nothing<bool>();
240
  }
241
242
222
  ArrayBufferOrViewContents<char> data(args[offset + 1]);
243
74
  if (UNLIKELY(!data.CheckSizeInt32())) {
244
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
245
    return Nothing<bool>();
246
  }
247
  params->in = mode == kCryptoJobAsync
248
148
      ? data.ToCopy()
249
74
      : data.ToByteSource();
250
251
74
  unsigned int expected = EVP_MD_size(params->digest);
252
74
  params->length = expected;
253
222
  if (UNLIKELY(args[offset + 2]->IsUint32())) {
254
    // length is expressed in terms of bits
255
5
    params->length =
256
15
        static_cast<uint32_t>(args[offset + 2]
257
15
            .As<Uint32>()->Value()) / CHAR_BIT;
258
5
    if (params->length != expected) {
259
1
      if ((EVP_MD_flags(params->digest) & EVP_MD_FLAG_XOF) == 0) {
260
1
        THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Digest method not supported");
261
1
        return Nothing<bool>();
262
      }
263
    }
264
  }
265
266
73
  return Just(true);
267
}
268
269
73
bool HashTraits::DeriveBits(
270
    Environment* env,
271
    const HashConfig& params,
272
    ByteSource* out) {
273
146
  EVPMDPointer ctx(EVP_MD_CTX_new());
274
275


73
  if (UNLIKELY(!ctx ||
276
               EVP_DigestInit_ex(ctx.get(), params.digest, nullptr) <= 0 ||
277
               EVP_DigestUpdate(
278
                   ctx.get(),
279
                   params.in.get(),
280
                   params.in.size()) <= 0)) {
281
    return false;
282
  }
283
284
73
  if (LIKELY(params.length > 0)) {
285
73
    unsigned int length = params.length;
286
73
    char* data = MallocOpenSSL<char>(length);
287
146
    ByteSource buf = ByteSource::Allocated(data, length);
288
73
    unsigned char* ptr = reinterpret_cast<unsigned char*>(data);
289
290
73
    size_t expected = EVP_MD_CTX_size(ctx.get());
291
292
73
    int ret = (length == expected)
293
73
        ? EVP_DigestFinal_ex(ctx.get(), ptr, &length)
294
73
        : EVP_DigestFinalXOF(ctx.get(), ptr, length);
295
296
73
    if (UNLIKELY(ret != 1))
297
      return false;
298
299
73
    *out = std::move(buf);
300
  }
301
302
73
  return true;
303
}
304
305
}  // namespace crypto
306

14310
}  // namespace node