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_hmac.cc Lines: 117 144 81.2 %
Date: 2021-06-04 04:12:13 Branches: 44 83 53.0 %

Line Branch Exec Source
1
#include "crypto/crypto_hmac.h"
2
#include "crypto/crypto_keys.h"
3
#include "crypto/crypto_sig.h"
4
#include "crypto/crypto_util.h"
5
#include "allocated_buffer-inl.h"
6
#include "async_wrap-inl.h"
7
#include "base_object-inl.h"
8
#include "env-inl.h"
9
#include "memory_tracker-inl.h"
10
#include "node_buffer.h"
11
#include "string_bytes.h"
12
#include "threadpoolwork-inl.h"
13
#include "v8.h"
14
15
namespace node {
16
17
using v8::FunctionCallbackInfo;
18
using v8::FunctionTemplate;
19
using v8::HandleScope;
20
using v8::Just;
21
using v8::Local;
22
using v8::Maybe;
23
using v8::MaybeLocal;
24
using v8::Nothing;
25
using v8::Object;
26
using v8::Uint32;
27
using v8::Value;
28
29
namespace crypto {
30
164
Hmac::Hmac(Environment* env, Local<Object> wrap)
31
    : BaseObject(env, wrap),
32
164
      ctx_(nullptr) {
33
164
  MakeWeak();
34
164
}
35
36
void Hmac::MemoryInfo(MemoryTracker* tracker) const {
37
  tracker->TrackFieldWithSize("context", ctx_ ? kSizeOf_HMAC_CTX : 0);
38
}
39
40
4169
void Hmac::Initialize(Environment* env, Local<Object> target) {
41
4169
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
42
43
12507
  t->InstanceTemplate()->SetInternalFieldCount(
44
4169
      Hmac::kInternalFieldCount);
45
8338
  t->Inherit(BaseObject::GetConstructorTemplate(env));
46
47
4169
  env->SetProtoMethod(t, "init", HmacInit);
48
4169
  env->SetProtoMethod(t, "update", HmacUpdate);
49
4169
  env->SetProtoMethod(t, "digest", HmacDigest);
50
51
4169
  env->SetConstructorFunction(target, "Hmac", t);
52
53
4169
  HmacJob::Initialize(env, target);
54
4169
}
55
56
164
void Hmac::New(const FunctionCallbackInfo<Value>& args) {
57
164
  Environment* env = Environment::GetCurrent(args);
58
164
  new Hmac(env, args.This());
59
164
}
60
61
164
void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
62
327
  HandleScope scope(env()->isolate());
63
64
164
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
65
164
  if (md == nullptr)
66
1
    return THROW_ERR_CRYPTO_INVALID_DIGEST(env());
67
163
  if (key_len == 0) {
68
6
    key = "";
69
  }
70
163
  ctx_.reset(HMAC_CTX_new());
71

163
  if (!ctx_ || !HMAC_Init_ex(ctx_.get(), key, key_len, md, nullptr)) {
72
    ctx_.reset();
73
    return ThrowCryptoError(env(), ERR_get_error());
74
  }
75
}
76
77
164
void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
78
  Hmac* hmac;
79
164
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
80
164
  Environment* env = hmac->env();
81
82
328
  const node::Utf8Value hash_type(env->isolate(), args[0]);
83
328
  ByteSource key = ByteSource::FromSecretKeyBytes(env, args[1]);
84
164
  hmac->HmacInit(*hash_type, key.get(), key.size());
85
}
86
87
162
bool Hmac::HmacUpdate(const char* data, size_t len) {
88

162
  return ctx_ && HMAC_Update(ctx_.get(),
89
                             reinterpret_cast<const unsigned char*>(data),
90
324
                             len) == 1;
91
}
92
93
162
void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
94
324
  Decode<Hmac>(args, [](Hmac* hmac, const FunctionCallbackInfo<Value>& args,
95
486
                        const char* data, size_t size) {
96
162
    Environment* env = Environment::GetCurrent(args);
97
162
    if (UNLIKELY(size > INT_MAX))
98
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
99
162
    bool r = hmac->HmacUpdate(data, size);
100
486
    args.GetReturnValue().Set(r);
101
486
  });
102
162
}
103
104
157
void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
105
157
  Environment* env = Environment::GetCurrent(args);
106
107
  Hmac* hmac;
108
157
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
109
110
157
  enum encoding encoding = BUFFER;
111
157
  if (args.Length() >= 1) {
112
129
    encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
113
  }
114
115
  unsigned char md_value[EVP_MAX_MD_SIZE];
116
157
  unsigned int md_len = 0;
117
118
157
  if (hmac->ctx_) {
119
157
    HMAC_Final(hmac->ctx_.get(), md_value, &md_len);
120
157
    hmac->ctx_.reset();
121
  }
122
123
  Local<Value> error;
124
  MaybeLocal<Value> rc =
125
      StringBytes::Encode(env->isolate(),
126
                          reinterpret_cast<const char*>(md_value),
127
                          md_len,
128
                          encoding,
129
157
                          &error);
130
157
  if (rc.IsEmpty()) {
131
    CHECK(!error.IsEmpty());
132
    env->isolate()->ThrowException(error);
133
    return;
134
  }
135
314
  args.GetReturnValue().Set(rc.FromMaybe(Local<Value>()));
136
}
137
138
44
HmacConfig::HmacConfig(HmacConfig&& other) noexcept
139
44
    : job_mode(other.job_mode),
140
44
      mode(other.mode),
141
44
      key(std::move(other.key)),
142
44
      data(std::move(other.data)),
143
44
      signature(std::move(other.signature)),
144
264
      digest(other.digest) {}
145
146
HmacConfig& HmacConfig::operator=(HmacConfig&& other) noexcept {
147
  if (&other == this) return *this;
148
  this->~HmacConfig();
149
  return *new (this) HmacConfig(std::move(other));
150
}
151
152
void HmacConfig::MemoryInfo(MemoryTracker* tracker) const {
153
  tracker->TrackField("key", key.get());
154
  // If the job is sync, then the HmacConfig does not own the data
155
  if (job_mode == kCryptoJobAsync) {
156
    tracker->TrackFieldWithSize("data", data.size());
157
    tracker->TrackFieldWithSize("signature", signature.size());
158
  }
159
}
160
161
44
Maybe<bool> HmacTraits::AdditionalConfig(
162
    CryptoJobMode mode,
163
    const FunctionCallbackInfo<Value>& args,
164
    unsigned int offset,
165
    HmacConfig* params) {
166
44
  Environment* env = Environment::GetCurrent(args);
167
168
44
  params->job_mode = mode;
169
170
132
  CHECK(args[offset]->IsUint32());  // SignConfiguration::Mode
171
44
  params->mode =
172
220
    static_cast<SignConfiguration::Mode>(args[offset].As<Uint32>()->Value());
173
174
176
  CHECK(args[offset + 1]->IsString());  // Hash
175
132
  CHECK(args[offset + 2]->IsObject());  // Key
176
177
132
  Utf8Value digest(env->isolate(), args[offset + 1]);
178
44
  params->digest = EVP_get_digestbyname(*digest);
179
44
  if (params->digest == nullptr) {
180
    THROW_ERR_CRYPTO_INVALID_DIGEST(env);
181
    return Nothing<bool>();
182
  }
183
184
  KeyObjectHandle* key;
185
88
  ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 2], Nothing<bool>());
186
44
  params->key = key->Data();
187
188
132
  ArrayBufferOrViewContents<char> data(args[offset + 3]);
189
44
  if (UNLIKELY(!data.CheckSizeInt32())) {
190
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
191
    return Nothing<bool>();
192
  }
193
  params->data = mode == kCryptoJobAsync
194
88
      ? data.ToCopy()
195
44
      : data.ToByteSource();
196
197
176
  if (!args[offset + 4]->IsUndefined()) {
198
99
    ArrayBufferOrViewContents<char> signature(args[offset + 4]);
199
33
    if (UNLIKELY(!signature.CheckSizeInt32())) {
200
      THROW_ERR_OUT_OF_RANGE(env, "signature is too big");
201
      return Nothing<bool>();
202
    }
203
    params->signature = mode == kCryptoJobAsync
204

66
        ? signature.ToCopy()
205
33
        : signature.ToByteSource();
206
  }
207
208
44
  return Just(true);
209
}
210
211
44
bool HmacTraits::DeriveBits(
212
    Environment* env,
213
    const HmacConfig& params,
214
    ByteSource* out) {
215
88
  HMACCtxPointer ctx(HMAC_CTX_new());
216
217

88
  if (!ctx ||
218
88
      !HMAC_Init_ex(
219
          ctx.get(),
220
44
          params.key->GetSymmetricKey(),
221
44
          params.key->GetSymmetricKeySize(),
222
44
          params.digest,
223
          nullptr)) {
224
    return false;
225
  }
226
227
44
  if (!HMAC_Update(
228
          ctx.get(),
229
          params.data.data<unsigned char>(),
230
          params.data.size())) {
231
    return false;
232
  }
233
234
44
  char* data = MallocOpenSSL<char>(EVP_MAX_MD_SIZE);
235
88
  ByteSource buf = ByteSource::Allocated(data, EVP_MAX_MD_SIZE);
236
44
  unsigned char* ptr = reinterpret_cast<unsigned char*>(data);
237
  unsigned int len;
238
239
44
  if (!HMAC_Final(ctx.get(), ptr, &len)) {
240
    return false;
241
  }
242
243
44
  buf.Resize(len);
244
44
  *out = std::move(buf);
245
246
44
  return true;
247
}
248
249
44
Maybe<bool> HmacTraits::EncodeOutput(
250
    Environment* env,
251
    const HmacConfig& params,
252
    ByteSource* out,
253
    Local<Value>* result) {
254
44
  switch (params.mode) {
255
    case SignConfiguration::kSign:
256
22
      *result = out->ToArrayBuffer(env);
257
11
      break;
258
    case SignConfiguration::kVerify:
259
33
      *result =
260
66
          out->size() > 0 &&
261
62
          out->size() == params.signature.size() &&
262
29
          memcmp(out->get(), params.signature.get(), out->size()) == 0
263
17
              ? v8::True(env->isolate())
264
83
              : v8::False(env->isolate());
265
33
      break;
266
    default:
267
      UNREACHABLE();
268
  }
269
44
  return Just(!result->IsEmpty());
270
}
271
272
}  // namespace crypto
273

14532
}  // namespace node