GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_hmac.cc Lines: 123 151 81.5 %
Date: 2021-11-16 04:13:57 Branches: 49 93 52.7 %

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
4318
void Hmac::Initialize(Environment* env, Local<Object> target) {
41
4318
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
42
43
8636
  t->InstanceTemplate()->SetInternalFieldCount(
44
      Hmac::kInternalFieldCount);
45
4318
  t->Inherit(BaseObject::GetConstructorTemplate(env));
46
47
4318
  env->SetProtoMethod(t, "init", HmacInit);
48
4318
  env->SetProtoMethod(t, "update", HmacUpdate);
49
4318
  env->SetProtoMethod(t, "digest", HmacDigest);
50
51
4318
  env->SetConstructorFunction(target, "Hmac", t);
52
53
4318
  HmacJob::Initialize(env, target);
54
4318
}
55
56
4874
void Hmac::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
57
4874
  registry->Register(New);
58
4874
  registry->Register(HmacInit);
59
4874
  registry->Register(HmacUpdate);
60
4874
  registry->Register(HmacDigest);
61
4874
  HmacJob::RegisterExternalReferences(registry);
62
4874
}
63
64
164
void Hmac::New(const FunctionCallbackInfo<Value>& args) {
65
164
  Environment* env = Environment::GetCurrent(args);
66
164
  new Hmac(env, args.This());
67
164
}
68
69
164
void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
70
164
  HandleScope scope(env()->isolate());
71
72
164
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
73
164
  if (md == nullptr)
74
1
    return THROW_ERR_CRYPTO_INVALID_DIGEST(env());
75
163
  if (key_len == 0) {
76
6
    key = "";
77
  }
78
163
  ctx_.reset(HMAC_CTX_new());
79

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

162
  return ctx_ && HMAC_Update(ctx_.get(),
97
                             reinterpret_cast<const unsigned char*>(data),
98
324
                             len) == 1;
99
}
100
101
162
void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
102
162
  Decode<Hmac>(args, [](Hmac* hmac, const FunctionCallbackInfo<Value>& args,
103
162
                        const char* data, size_t size) {
104
162
    Environment* env = Environment::GetCurrent(args);
105
162
    if (UNLIKELY(size > INT_MAX))
106
      return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
107
162
    bool r = hmac->HmacUpdate(data, size);
108
324
    args.GetReturnValue().Set(r);
109
  });
110
162
}
111
112
157
void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
113
157
  Environment* env = Environment::GetCurrent(args);
114
115
  Hmac* hmac;
116
157
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
117
118
157
  enum encoding encoding = BUFFER;
119
157
  if (args.Length() >= 1) {
120
129
    encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
121
  }
122
123
  unsigned char md_value[EVP_MAX_MD_SIZE];
124
157
  unsigned int md_len = 0;
125
126
157
  if (hmac->ctx_) {
127
157
    HMAC_Final(hmac->ctx_.get(), md_value, &md_len);
128
157
    hmac->ctx_.reset();
129
  }
130
131
  Local<Value> error;
132
  MaybeLocal<Value> rc =
133
      StringBytes::Encode(env->isolate(),
134
                          reinterpret_cast<const char*>(md_value),
135
                          md_len,
136
                          encoding,
137
157
                          &error);
138
157
  if (rc.IsEmpty()) {
139
    CHECK(!error.IsEmpty());
140
    env->isolate()->ThrowException(error);
141
    return;
142
  }
143
471
  args.GetReturnValue().Set(rc.FromMaybe(Local<Value>()));
144
}
145
146
102
HmacConfig::HmacConfig(HmacConfig&& other) noexcept
147
102
    : job_mode(other.job_mode),
148
102
      mode(other.mode),
149
102
      key(std::move(other.key)),
150
102
      data(std::move(other.data)),
151
102
      signature(std::move(other.signature)),
152
102
      digest(other.digest) {}
153
154
HmacConfig& HmacConfig::operator=(HmacConfig&& other) noexcept {
155
  if (&other == this) return *this;
156
  this->~HmacConfig();
157
  return *new (this) HmacConfig(std::move(other));
158
}
159
160
void HmacConfig::MemoryInfo(MemoryTracker* tracker) const {
161
  tracker->TrackField("key", key.get());
162
  // If the job is sync, then the HmacConfig does not own the data
163
  if (job_mode == kCryptoJobAsync) {
164
    tracker->TrackFieldWithSize("data", data.size());
165
    tracker->TrackFieldWithSize("signature", signature.size());
166
  }
167
}
168
169
102
Maybe<bool> HmacTraits::AdditionalConfig(
170
    CryptoJobMode mode,
171
    const FunctionCallbackInfo<Value>& args,
172
    unsigned int offset,
173
    HmacConfig* params) {
174
102
  Environment* env = Environment::GetCurrent(args);
175
176
102
  params->job_mode = mode;
177
178

204
  CHECK(args[offset]->IsUint32());  // SignConfiguration::Mode
179
102
  params->mode =
180
408
    static_cast<SignConfiguration::Mode>(args[offset].As<Uint32>()->Value());
181
182

306
  CHECK(args[offset + 1]->IsString());  // Hash
183

204
  CHECK(args[offset + 2]->IsObject());  // Key
184
185
306
  Utf8Value digest(env->isolate(), args[offset + 1]);
186
102
  params->digest = EVP_get_digestbyname(*digest);
187
102
  if (params->digest == nullptr) {
188
    THROW_ERR_CRYPTO_INVALID_DIGEST(env);
189
    return Nothing<bool>();
190
  }
191
192
  KeyObjectHandle* key;
193

204
  ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 2], Nothing<bool>());
194
102
  params->key = key->Data();
195
196
306
  ArrayBufferOrViewContents<char> data(args[offset + 3]);
197
102
  if (UNLIKELY(!data.CheckSizeInt32())) {
198
    THROW_ERR_OUT_OF_RANGE(env, "data is too big");
199
    return Nothing<bool>();
200
  }
201
  params->data = mode == kCryptoJobAsync
202
204
      ? data.ToCopy()
203
102
      : data.ToByteSource();
204
205

306
  if (!args[offset + 4]->IsUndefined()) {
206
148
    ArrayBufferOrViewContents<char> signature(args[offset + 4]);
207
74
    if (UNLIKELY(!signature.CheckSizeInt32())) {
208
      THROW_ERR_OUT_OF_RANGE(env, "signature is too big");
209
      return Nothing<bool>();
210
    }
211
    params->signature = mode == kCryptoJobAsync
212
148
        ? signature.ToCopy()
213
74
        : signature.ToByteSource();
214
  }
215
216
102
  return Just(true);
217
}
218
219
102
bool HmacTraits::DeriveBits(
220
    Environment* env,
221
    const HmacConfig& params,
222
    ByteSource* out) {
223
204
  HMACCtxPointer ctx(HMAC_CTX_new());
224
225

204
  if (!ctx ||
226
102
      !HMAC_Init_ex(
227
          ctx.get(),
228
102
          params.key->GetSymmetricKey(),
229
102
          params.key->GetSymmetricKeySize(),
230
102
          params.digest,
231
          nullptr)) {
232
    return false;
233
  }
234
235
102
  if (!HMAC_Update(
236
          ctx.get(),
237
          params.data.data<unsigned char>(),
238
          params.data.size())) {
239
    return false;
240
  }
241
242
102
  char* data = MallocOpenSSL<char>(EVP_MAX_MD_SIZE);
243
204
  ByteSource buf = ByteSource::Allocated(data, EVP_MAX_MD_SIZE);
244
102
  unsigned char* ptr = reinterpret_cast<unsigned char*>(data);
245
  unsigned int len;
246
247
102
  if (!HMAC_Final(ctx.get(), ptr, &len)) {
248
    return false;
249
  }
250
251
102
  buf.Resize(len);
252
102
  *out = std::move(buf);
253
254
102
  return true;
255
}
256
257
102
Maybe<bool> HmacTraits::EncodeOutput(
258
    Environment* env,
259
    const HmacConfig& params,
260
    ByteSource* out,
261
    Local<Value>* result) {
262
102
  switch (params.mode) {
263
28
    case SignConfiguration::kSign:
264
28
      *result = out->ToArrayBuffer(env);
265
28
      break;
266
74
    case SignConfiguration::kVerify:
267
120
      *result =
268
148
          out->size() > 0 &&
269
74
          out->size() == params.signature.size() &&
270
66
          memcmp(out->get(), params.signature.get(), out->size()) == 0
271
46
              ? v8::True(env->isolate())
272
28
              : v8::False(env->isolate());
273
74
      break;
274
    default:
275
      UNREACHABLE();
276
  }
277
102
  return Just(!result->IsEmpty());
278
}
279
280
}  // namespace crypto
281
}  // namespace node