Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: add crypto.createMac() #32477

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ const {
} = require('internal/crypto/sig');
const {
Hash,
Hmac
Hmac,
Mac,
} = require('internal/crypto/hash');
const {
getCiphers,
Expand Down Expand Up @@ -142,6 +143,10 @@ function createHmac(hmac, key, options) {
return new Hmac(hmac, key, options);
}

function createMac(mac, key, options) {
return new Mac(mac, key, options);
}

function createSign(algorithm, options) {
return new Sign(algorithm, options);
}
Expand All @@ -159,6 +164,7 @@ module.exports = {
createECDH,
createHash,
createHmac,
createMac,
createPrivateKey,
createPublicKey,
createSecretKey,
Expand Down Expand Up @@ -203,6 +209,7 @@ module.exports = {
Hash,
Hmac,
KeyObject,
Mac,
Sign,
Verify
};
Expand Down
78 changes: 75 additions & 3 deletions lib/internal/crypto/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ const {
} = primordials;

const {
EVP_PKEY_CMAC,
EVP_PKEY_HMAC,
EVP_PKEY_POLY1305,
EVP_PKEY_SIPHASH,
Hash: _Hash,
Hmac: _Hmac
Hmac: _Hmac,
Mac: _Mac,
} = internalBinding('crypto');

const {
Expand All @@ -25,7 +30,8 @@ const { Buffer } = require('buffer');
const {
ERR_CRYPTO_HASH_FINALIZED,
ERR_CRYPTO_HASH_UPDATE_FAILED,
ERR_INVALID_ARG_TYPE
ERR_INVALID_ARG_TYPE,
ERR_INVALID_OPT_VALUE,
} = require('internal/errors').codes;
const { validateEncoding, validateString, validateUint32 } =
require('internal/validators');
Expand Down Expand Up @@ -140,7 +146,73 @@ Hmac.prototype.digest = function digest(outputEncoding) {
Hmac.prototype._flush = Hash.prototype._flush;
Hmac.prototype._transform = Hash.prototype._transform;

class Mac extends LazyTransform {
constructor(mac, key, options) {
validateString(mac, 'mac');

let alg, nid;
switch (mac) {
case 'cmac':
alg = options && options.cipher;
nid = EVP_PKEY_CMAC;
validateString(alg, 'options.cipher');
break;

case 'hmac':
alg = options && options.digest;
nid = EVP_PKEY_HMAC;
validateString(alg, 'options.digest');
break;

case 'poly1305':
nid = EVP_PKEY_POLY1305;
break;

case 'siphash':
nid = EVP_PKEY_SIPHASH;
break;

default:
throw new ERR_INVALID_OPT_VALUE('mac', mac);
}

key = prepareSecretKey(key);
super(options);

bnoordhuis marked this conversation as resolved.
Show resolved Hide resolved
this[kHandle] = new _Mac(nid, toBuf(key), alg);
}

_transform(chunk, encoding, callback) {
this[kHandle].update(chunk, encoding);
bnoordhuis marked this conversation as resolved.
Show resolved Hide resolved
callback();
}

_flush(callback) {
this.push(this[kHandle].final());
callback();
}

update(data, encoding) {
encoding = encoding || getDefaultEncoding();

if (typeof data === 'string') {
validateEncoding(data, encoding);
bnoordhuis marked this conversation as resolved.
Show resolved Hide resolved
} else if (!isArrayBufferView(data)) {
throw new ERR_INVALID_ARG_TYPE(
'data', ['string', 'Buffer', 'TypedArray', 'DataView'], data);
}

this[kHandle].update(data, encoding);
return this;
}

final(outputEncoding) {
return this[kHandle].final(outputEncoding || getDefaultEncoding());
}
}

module.exports = {
Hash,
Hmac
Hmac,
Mac,
};
125 changes: 125 additions & 0 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ using v8::Value;
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
#endif

void CheckThrow(Environment* env, SignBase::Error error);

static const char* const root_certs[] = {
#include "node_root_certs.h" // NOLINT(build/include_order)
};
Expand Down Expand Up @@ -4349,6 +4351,124 @@ void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
}


void Mac::Initialize(Environment* env, Local<Object> target) {
Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
t->InstanceTemplate()->SetInternalFieldCount(Mac::kInternalFieldCount);

env->SetProtoMethod(t, "update", Update);
env->SetProtoMethod(t, "final", Final);

target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(), "Mac"),
t->GetFunction(env->context()).ToLocalChecked()).Check();
}


Mac::Mac(Environment* env, Local<Object> wrap, EVPMDPointer&& mdctx)
: BaseObject(env, wrap)
, mdctx_(std::move(mdctx)) {
MakeWeak();
}


void Mac::New(const FunctionCallbackInfo<Value>& args) {
MarkPopErrorOnReturn mark_pop_error_on_return;
Environment* env = Environment::GetCurrent(args);

CHECK(args[0]->IsInt32());
const int nid = args[0].As<Int32>()->Value();

CHECK(args[1]->IsArrayBufferView());
ByteSource key = ByteSource::FromBuffer(args[1]);

const EVP_MD* md = nullptr;
if (nid == EVP_PKEY_HMAC) {
CHECK(args[2]->IsString());
const node::Utf8Value name(env->isolate(), args[2]);
md = EVP_get_digestbyname(*name);
if (md == nullptr)
return CheckThrow(env, SignBase::Error::kSignUnknownDigest);
}

EVPKeyPointer key_ptr;
if (nid == EVP_PKEY_CMAC) {
CHECK(args[2]->IsString());
const node::Utf8Value name(env->isolate(), args[2]);
const EVP_CIPHER* cipher = EVP_get_cipherbyname(*name);
if (cipher == nullptr) return env->ThrowError("Unknown cipher");
key_ptr.reset(
EVP_PKEY_new_CMAC_key(nullptr,
reinterpret_cast<const unsigned char*>(key.get()),
key.size(), cipher));
} else {
key_ptr.reset(
EVP_PKEY_new_raw_private_key(
nid, nullptr, reinterpret_cast<const unsigned char*>(key.get()),
key.size()));
}

ManagedEVPPKey pkey(std::move(key_ptr));
EVPMDPointer mdctx(EVP_MD_CTX_new());


EVP_PKEY_CTX* pkctx = nullptr;
if (!EVP_DigestSignInit(mdctx.get(), &pkctx, md, nullptr, pkey.get()))
return ThrowCryptoError(env, ERR_get_error(), "EVP_DigestSignInit");

// TODO(bnoordhuis) Call EVP_PKEY_CTX_ctrl() or EVP_PKEY_CTX_ctrl_str().
jasnell marked this conversation as resolved.
Show resolved Hide resolved
// Only necessary for EVP_PKEY algorithms that require additional
// configuration, none of which we currently support.
USE(pkctx);

new Mac(env, args.This(), std::move(mdctx));
}


void Mac::Update(const FunctionCallbackInfo<Value>& args) {
Decode<Mac>(args, [](Mac* mac, const FunctionCallbackInfo<Value>& args,
const char* data, size_t size) {
CHECK_EQ(1, EVP_DigestSignUpdate(mac->mdctx_.get(), data, size));
});
}


void Mac::Final(const FunctionCallbackInfo<Value>& args) {
Mac* mac;
ASSIGN_OR_RETURN_UNWRAP(&mac, args.Holder());

MarkPopErrorOnReturn mark_pop_error_on_return;
Environment* env = Environment::GetCurrent(args);

enum encoding encoding = BUFFER;
if (args.Length() > 0)
encoding = ParseEncoding(env->isolate(), args[0], BUFFER);

size_t size;
if (!EVP_DigestSignFinal(mac->mdctx_.get(), nullptr, &size))
return ThrowCryptoError(env, ERR_get_error(), "EVP_DigestSignFinal");

unsigned char* data = MallocOpenSSL<unsigned char>(size);
ByteSource source =
ByteSource::Allocated(reinterpret_cast<char*>(data), size);

if (!EVP_DigestSignFinal(mac->mdctx_.get(), data, &size))
return ThrowCryptoError(env, ERR_get_error(), "EVP_DigestSignFinal");

Local<Value> error;
MaybeLocal<Value> rc =
StringBytes::Encode(env->isolate(), source.get(), source.size(),
encoding, &error);

if (rc.IsEmpty()) {
CHECK(!error.IsEmpty());
env->isolate()->ThrowException(error);
return;
}

args.GetReturnValue().Set(rc.ToLocalChecked());
bnoordhuis marked this conversation as resolved.
Show resolved Hide resolved
}


SignBase::Error SignBase::Init(const char* sign_type) {
CHECK_NULL(mdctx_);
// Historically, "dss1" and "DSS1" were DSA aliases for SHA-1
Expand Down Expand Up @@ -6864,6 +6984,7 @@ void Initialize(Local<Object> target,
ECDH::Initialize(env, target);
Hmac::Initialize(env, target);
Hash::Initialize(env, target);
Mac::Initialize(env, target);
Sign::Initialize(env, target);
Verify::Initialize(env, target);

Expand Down Expand Up @@ -6893,8 +7014,12 @@ void Initialize(Local<Object> target,
env->SetMethod(target, "generateKeyPairEC", GenerateKeyPairEC);
env->SetMethod(target, "generateKeyPairNid", GenerateKeyPairNid);
env->SetMethod(target, "generateKeyPairDH", GenerateKeyPairDH);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_CMAC);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED25519);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED448);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_HMAC);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_POLY1305);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_SIPHASH);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_X25519);
NODE_DEFINE_CONSTANT(target, EVP_PKEY_X448);
NODE_DEFINE_CONSTANT(target, OPENSSL_EC_NAMED_CURVE);
Expand Down
20 changes: 20 additions & 0 deletions src/node_crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,26 @@ class Hash final : public BaseObject {
unsigned char* md_value_;
};

class Mac : public BaseObject {
public:
static void Initialize(Environment* env, v8::Local<v8::Object> target);

// TODO(joyeecheung): track the memory used by OpenSSL types
SET_NO_MEMORY_INFO()
SET_MEMORY_INFO_NAME(Mac)
SET_SELF_SIZE(Mac)

protected:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Update(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Final(const v8::FunctionCallbackInfo<v8::Value>& args);

Mac(Environment* env, v8::Local<v8::Object> wrap, EVPMDPointer&& mdctx);

private:
EVPMDPointer mdctx_;
};

class SignBase : public BaseObject {
public:
typedef enum {
Expand Down
Loading