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 158 84.2 %
Date: 2021-05-01 04:12:26 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
25645
Hash::Hash(Environment* env, Local<Object> wrap) : BaseObject(env, wrap) {
28
25645
  MakeWeak();
29
25645
}
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
4154
void Hash::Initialize(Environment* env, Local<Object> target) {
44
4154
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
45
46
12462
  t->InstanceTemplate()->SetInternalFieldCount(
47
4154
      Hash::kInternalFieldCount);
48
8308
  t->Inherit(BaseObject::GetConstructorTemplate(env));
49
50
4154
  env->SetProtoMethod(t, "update", HashUpdate);
51
4154
  env->SetProtoMethod(t, "digest", HashDigest);
52
53
4154
  env->SetConstructorFunction(target, "Hash", t);
54
55
4154
  env->SetMethodNoSideEffect(target, "getHashes", GetHashes);
56
57
4154
  HashJob::Initialize(env, target);
58
4154
}
59
60
25645
void Hash::New(const FunctionCallbackInfo<Value>& args) {
61
25645
  Environment* env = Environment::GetCurrent(args);
62
63
25645
  const Hash* orig = nullptr;
64
25645
  const EVP_MD* md = nullptr;
65
66
51290
  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
51280
    const Utf8Value hash_type(env->isolate(), args[0]);
71
25640
    md = EVP_get_digestbyname(*hash_type);
72
  }
73
74
25645
  Maybe<unsigned int> xof_md_len = Nothing<unsigned int>();
75
76935
  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
25645
  Hash* hash = new Hash(env, args.This());
81

25645
  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

25647
  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
25643
bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
93
25643
  mdctx_.reset(EVP_MD_CTX_new());
94

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

25656
  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
25642
  return true;
111
}
112
113
25851
bool Hash::HashUpdate(const char* data, size_t len) {
114
25851
  if (!mdctx_)
115
    return false;
116
25851
  EVP_DigestUpdate(mdctx_.get(), data, len);
117
25851
  return true;
118
}
119
120
25851
void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
121
51702
  Decode<Hash>(args, [](Hash* hash, const FunctionCallbackInfo<Value>& args,
122
77553
                        const char* data, size_t size) {
123
25851
    Environment* env = Environment::GetCurrent(args);
124
25851
    if (UNLIKELY(size > INT_MAX))
125
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
126
25851
    bool r = hash->HashUpdate(data, size);
127
77553
    args.GetReturnValue().Set(r);
128
77553
  });
129
25851
}
130
131
25627
void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
132
25627
  Environment* env = Environment::GetCurrent(args);
133
134
  Hash* hash;
135
25627
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
136
137
25627
  enum encoding encoding = BUFFER;
138
25627
  if (args.Length() >= 1) {
139
25615
    encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
140
  }
141
142
25627
  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

25627
  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
25624
    char* md_value = MallocOpenSSL<char>(len);
157
51248
    ByteSource digest = ByteSource::Allocated(md_value, len);
158
159
25624
    size_t default_len = EVP_MD_CTX_size(hash->mdctx_.get());
160
    int ret;
161
25624
    if (len == default_len) {
162
25618
      ret = EVP_DigestFinal_ex(
163
25618
          hash->mdctx_.get(),
164
          reinterpret_cast<unsigned char*>(md_value),
165
25618
          &len);
166
      // The output length should always equal hash->md_len_
167
25618
      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
25624
    if (ret != 1)
176
      return ThrowCryptoError(env, ERR_get_error());
177
178
25624
    hash->digest_ = std::move(digest);
179
  }
180
181
  Local<Value> error;
182
  MaybeLocal<Value> rc =
183
      StringBytes::Encode(env->isolate(),
184
25627
                          hash->digest_.get(),
185
                          len,
186
                          encoding,
187
51254
                          &error);
188
25627
  if (rc.IsEmpty()) {
189
    CHECK(!error.IsEmpty());
190
    env->isolate()->ThrowException(error);
191
    return;
192
  }
193
51254
  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
    THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Invalid digest: %s", *digest);
237
    return Nothing<bool>();
238
  }
239
240
222
  ArrayBufferOrViewContents<char> data(args[offset + 1]);
241
74
  if (UNLIKELY(!data.CheckSizeInt32())) {
242
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
243
    return Nothing<bool>();
244
  }
245
  params->in = mode == kCryptoJobAsync
246
148
      ? data.ToCopy()
247
74
      : data.ToByteSource();
248
249
74
  unsigned int expected = EVP_MD_size(params->digest);
250
74
  params->length = expected;
251
222
  if (UNLIKELY(args[offset + 2]->IsUint32())) {
252
    // length is expressed in terms of bits
253
5
    params->length =
254
15
        static_cast<uint32_t>(args[offset + 2]
255
15
            .As<Uint32>()->Value()) / CHAR_BIT;
256
5
    if (params->length != expected) {
257
1
      if ((EVP_MD_flags(params->digest) & EVP_MD_FLAG_XOF) == 0) {
258
1
        THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Digest method not supported");
259
1
        return Nothing<bool>();
260
      }
261
    }
262
  }
263
264
73
  return Just(true);
265
}
266
267
73
bool HashTraits::DeriveBits(
268
    Environment* env,
269
    const HashConfig& params,
270
    ByteSource* out) {
271
146
  EVPMDPointer ctx(EVP_MD_CTX_new());
272
273


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

14487
}  // namespace node