Skip to content

Commit c63af4f

Browse files
committed
crypto: add support for IEEE-P1363 DSA signatures
PR-URL: #29292 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Daniel Bevenius <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 80efb80 commit c63af4f

File tree

5 files changed

+277
-24
lines changed

5 files changed

+277
-24
lines changed

doc/api/crypto.md

+18
Original file line numberDiff line numberDiff line change
@@ -1405,6 +1405,7 @@ changes:
14051405
-->
14061406

14071407
* `privateKey` {Object | string | Buffer | KeyObject}
1408+
* `dsaEncoding` {string}
14081409
* `padding` {integer}
14091410
* `saltLength` {integer}
14101411
* `outputEncoding` {string} The [encoding][] of the return value.
@@ -1417,6 +1418,10 @@ If `privateKey` is not a [`KeyObject`][], this function behaves as if
14171418
`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
14181419
object, the following additional properties can be passed:
14191420

1421+
* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
1422+
format of the generated signature. It can be one of the following:
1423+
* `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
1424+
* `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
14201425
* `padding` {integer} Optional padding value for RSA, one of the following:
14211426
* `crypto.constants.RSA_PKCS1_PADDING` (default)
14221427
* `crypto.constants.RSA_PKCS1_PSS_PADDING`
@@ -1513,6 +1518,7 @@ changes:
15131518
-->
15141519

15151520
* `object` {Object | string | Buffer | KeyObject}
1521+
* `dsaEncoding` {string}
15161522
* `padding` {integer}
15171523
* `saltLength` {integer}
15181524
* `signature` {string | Buffer | TypedArray | DataView}
@@ -1526,6 +1532,10 @@ If `object` is not a [`KeyObject`][], this function behaves as if
15261532
`object` had been passed to [`crypto.createPublicKey()`][]. If it is an
15271533
object, the following additional properties can be passed:
15281534

1535+
* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
1536+
format of the generated signature. It can be one of the following:
1537+
* `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
1538+
* `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
15291539
* `padding` {integer} Optional padding value for RSA, one of the following:
15301540
* `crypto.constants.RSA_PKCS1_PADDING` (default)
15311541
* `crypto.constants.RSA_PKCS1_PSS_PADDING`
@@ -2891,6 +2901,10 @@ If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
28912901
passed to [`crypto.createPrivateKey()`][]. If it is an object, the following
28922902
additional properties can be passed:
28932903

2904+
* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
2905+
format of the generated signature. It can be one of the following:
2906+
* `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
2907+
* `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
28942908
* `padding` {integer} Optional padding value for RSA, one of the following:
28952909
* `crypto.constants.RSA_PKCS1_PADDING` (default)
28962910
* `crypto.constants.RSA_PKCS1_PSS_PADDING`
@@ -2944,6 +2958,10 @@ If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
29442958
passed to [`crypto.createPublicKey()`][]. If it is an object, the following
29452959
additional properties can be passed:
29462960

2961+
* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
2962+
format of the generated signature. It can be one of the following:
2963+
* `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
2964+
* `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
29472965
* `padding` {integer} Optional padding value for RSA, one of the following:
29482966
* `crypto.constants.RSA_PKCS1_PADDING` (default)
29492967
* `crypto.constants.RSA_PKCS1_PSS_PADDING`

lib/internal/crypto/sig.js

+32-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ const { validateString } = require('internal/validators');
1111
const {
1212
Sign: _Sign,
1313
Verify: _Verify,
14+
kSigEncDER,
15+
kSigEncP1363,
1416
signOneShot: _signOneShot,
1517
verifyOneShot: _verifyOneShot
1618
} = internalBinding('crypto');
@@ -59,6 +61,20 @@ function getSaltLength(options) {
5961
return getIntOption('saltLength', options);
6062
}
6163

64+
function getDSASignatureEncoding(options) {
65+
if (typeof options === 'object') {
66+
const { dsaEncoding = 'der' } = options;
67+
if (dsaEncoding === 'der')
68+
return kSigEncDER;
69+
else if (dsaEncoding === 'ieee-p1363')
70+
return kSigEncP1363;
71+
else
72+
throw new ERR_INVALID_OPT_VALUE('dsaEncoding', dsaEncoding);
73+
}
74+
75+
return kSigEncDER;
76+
}
77+
6278
function getIntOption(name, options) {
6379
const value = options[name];
6480
if (value !== undefined) {
@@ -81,8 +97,11 @@ Sign.prototype.sign = function sign(options, encoding) {
8197
const rsaPadding = getPadding(options);
8298
const pssSaltLength = getSaltLength(options);
8399

100+
// Options specific to (EC)DSA
101+
const dsaSigEnc = getDSASignatureEncoding(options);
102+
84103
const ret = this[kHandle].sign(data, format, type, passphrase, rsaPadding,
85-
pssSaltLength);
104+
pssSaltLength, dsaSigEnc);
86105

87106
encoding = encoding || getDefaultEncoding();
88107
if (encoding && encoding !== 'buffer')
@@ -117,8 +136,11 @@ function signOneShot(algorithm, data, key) {
117136
const rsaPadding = getPadding(key);
118137
const pssSaltLength = getSaltLength(key);
119138

139+
// Options specific to (EC)DSA
140+
const dsaSigEnc = getDSASignatureEncoding(key);
141+
120142
return _signOneShot(keyData, keyFormat, keyType, keyPassphrase, data,
121-
algorithm, rsaPadding, pssSaltLength);
143+
algorithm, rsaPadding, pssSaltLength, dsaSigEnc);
122144
}
123145

124146
function Verify(algorithm, options) {
@@ -149,13 +171,15 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) {
149171

150172
// Options specific to RSA
151173
const rsaPadding = getPadding(options);
152-
153174
const pssSaltLength = getSaltLength(options);
154175

176+
// Options specific to (EC)DSA
177+
const dsaSigEnc = getDSASignatureEncoding(options);
178+
155179
signature = getArrayBufferView(signature, 'signature', sigEncoding);
156180

157181
return this[kHandle].verify(data, format, type, passphrase, signature,
158-
rsaPadding, pssSaltLength);
182+
rsaPadding, pssSaltLength, dsaSigEnc);
159183
};
160184

161185
function verifyOneShot(algorithm, data, key, signature) {
@@ -181,6 +205,9 @@ function verifyOneShot(algorithm, data, key, signature) {
181205
const rsaPadding = getPadding(key);
182206
const pssSaltLength = getSaltLength(key);
183207

208+
// Options specific to (EC)DSA
209+
const dsaSigEnc = getDSASignatureEncoding(key);
210+
184211
if (!isArrayBufferView(signature)) {
185212
throw new ERR_INVALID_ARG_TYPE(
186213
'signature',
@@ -190,7 +217,7 @@ function verifyOneShot(algorithm, data, key, signature) {
190217
}
191218

192219
return _verifyOneShot(keyData, keyFormat, keyType, keyPassphrase, signature,
193-
data, algorithm, rsaPadding, pssSaltLength);
220+
data, algorithm, rsaPadding, pssSaltLength, dsaSigEnc);
194221
}
195222

196223
module.exports = {

src/node_crypto.cc

+132-4
Original file line numberDiff line numberDiff line change
@@ -4910,6 +4910,9 @@ void CheckThrow(Environment* env, SignBase::Error error) {
49104910
case SignBase::Error::kSignNotInitialised:
49114911
return env->ThrowError("Not initialised");
49124912

4913+
case SignBase::Error::kSignMalformedSignature:
4914+
return env->ThrowError("Malformed signature");
4915+
49134916
case SignBase::Error::kSignInit:
49144917
case SignBase::Error::kSignUpdate:
49154918
case SignBase::Error::kSignPrivateKey:
@@ -5007,6 +5010,89 @@ static int GetDefaultSignPadding(const ManagedEVPPKey& key) {
50075010
RSA_PKCS1_PADDING;
50085011
}
50095012

5013+
static const unsigned int kNoDsaSignature = static_cast<unsigned int>(-1);
5014+
5015+
// Returns the maximum size of each of the integers (r, s) of the DSA signature.
5016+
static unsigned int GetBytesOfRS(const ManagedEVPPKey& pkey) {
5017+
int bits, base_id = EVP_PKEY_base_id(pkey.get());
5018+
5019+
if (base_id == EVP_PKEY_DSA) {
5020+
DSA* dsa_key = EVP_PKEY_get0_DSA(pkey.get());
5021+
// Both r and s are computed mod q, so their width is limited by that of q.
5022+
bits = BN_num_bits(DSA_get0_q(dsa_key));
5023+
} else if (base_id == EVP_PKEY_EC) {
5024+
EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(pkey.get());
5025+
const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key);
5026+
bits = EC_GROUP_order_bits(ec_group);
5027+
} else {
5028+
return kNoDsaSignature;
5029+
}
5030+
5031+
return (bits + 7) / 8;
5032+
}
5033+
5034+
static AllocatedBuffer ConvertSignatureToP1363(Environment* env,
5035+
const ManagedEVPPKey& pkey,
5036+
AllocatedBuffer&& signature) {
5037+
unsigned int n = GetBytesOfRS(pkey);
5038+
if (n == kNoDsaSignature)
5039+
return std::move(signature);
5040+
5041+
const unsigned char* sig_data =
5042+
reinterpret_cast<unsigned char*>(signature.data());
5043+
5044+
ECDSA_SIG* asn1_sig = d2i_ECDSA_SIG(nullptr, &sig_data, signature.size());
5045+
if (asn1_sig == nullptr)
5046+
return AllocatedBuffer();
5047+
5048+
AllocatedBuffer buf = env->AllocateManaged(2 * n);
5049+
unsigned char* data = reinterpret_cast<unsigned char*>(buf.data());
5050+
5051+
const BIGNUM* r = ECDSA_SIG_get0_r(asn1_sig);
5052+
const BIGNUM* s = ECDSA_SIG_get0_s(asn1_sig);
5053+
CHECK_EQ(n, BN_bn2binpad(r, data, n));
5054+
CHECK_EQ(n, BN_bn2binpad(s, data + n, n));
5055+
5056+
ECDSA_SIG_free(asn1_sig);
5057+
5058+
return buf;
5059+
}
5060+
5061+
static ByteSource ConvertSignatureToDER(
5062+
const ManagedEVPPKey& pkey,
5063+
const ArrayBufferViewContents<char>& signature) {
5064+
unsigned int n = GetBytesOfRS(pkey);
5065+
if (n == kNoDsaSignature)
5066+
return ByteSource::Foreign(signature.data(), signature.length());
5067+
5068+
const unsigned char* sig_data =
5069+
reinterpret_cast<const unsigned char*>(signature.data());
5070+
5071+
if (signature.length() != 2 * n)
5072+
return ByteSource();
5073+
5074+
ECDSA_SIG* asn1_sig = ECDSA_SIG_new();
5075+
CHECK_NOT_NULL(asn1_sig);
5076+
BIGNUM* r = BN_new();
5077+
CHECK_NOT_NULL(r);
5078+
BIGNUM* s = BN_new();
5079+
CHECK_NOT_NULL(s);
5080+
CHECK_EQ(r, BN_bin2bn(sig_data, n, r));
5081+
CHECK_EQ(s, BN_bin2bn(sig_data + n, n, s));
5082+
CHECK_EQ(1, ECDSA_SIG_set0(asn1_sig, r, s));
5083+
5084+
unsigned char* data = nullptr;
5085+
int len = i2d_ECDSA_SIG(asn1_sig, &data);
5086+
ECDSA_SIG_free(asn1_sig);
5087+
5088+
if (len <= 0)
5089+
return ByteSource();
5090+
5091+
CHECK_NOT_NULL(data);
5092+
5093+
return ByteSource::Allocated(reinterpret_cast<char*>(data), len);
5094+
}
5095+
50105096
static AllocatedBuffer Node_SignFinal(Environment* env,
50115097
EVPMDPointer&& mdctx,
50125098
const ManagedEVPPKey& pkey,
@@ -5066,7 +5152,8 @@ static inline bool ValidateDSAParameters(EVP_PKEY* key) {
50665152
Sign::SignResult Sign::SignFinal(
50675153
const ManagedEVPPKey& pkey,
50685154
int padding,
5069-
const Maybe<int>& salt_len) {
5155+
const Maybe<int>& salt_len,
5156+
DSASigEnc dsa_sig_enc) {
50705157
if (!mdctx_)
50715158
return SignResult(kSignNotInitialised);
50725159

@@ -5078,6 +5165,10 @@ Sign::SignResult Sign::SignFinal(
50785165
AllocatedBuffer buffer =
50795166
Node_SignFinal(env(), std::move(mdctx), pkey, padding, salt_len);
50805167
Error error = buffer.data() == nullptr ? kSignPrivateKey : kSignOk;
5168+
if (error == kSignOk && dsa_sig_enc == kSigEncP1363) {
5169+
buffer = ConvertSignatureToP1363(env(), pkey, std::move(buffer));
5170+
CHECK_NOT_NULL(buffer.data());
5171+
}
50815172
return SignResult(error, std::move(buffer));
50825173
}
50835174

@@ -5105,10 +5196,15 @@ void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
51055196
salt_len = Just<int>(args[offset + 1].As<Int32>()->Value());
51065197
}
51075198

5199+
CHECK(args[offset + 2]->IsInt32());
5200+
DSASigEnc dsa_sig_enc =
5201+
static_cast<DSASigEnc>(args[offset + 2].As<Int32>()->Value());
5202+
51085203
SignResult ret = sign->SignFinal(
51095204
key,
51105205
padding,
5111-
salt_len);
5206+
salt_len,
5207+
dsa_sig_enc);
51125208

51135209
if (ret.error != kSignOk)
51145210
return sign->CheckThrow(ret.error);
@@ -5152,6 +5248,10 @@ void SignOneShot(const FunctionCallbackInfo<Value>& args) {
51525248
rsa_salt_len = Just<int>(args[offset + 3].As<Int32>()->Value());
51535249
}
51545250

5251+
CHECK(args[offset + 4]->IsInt32());
5252+
DSASigEnc dsa_sig_enc =
5253+
static_cast<DSASigEnc>(args[offset + 4].As<Int32>()->Value());
5254+
51555255
EVP_PKEY_CTX* pkctx = nullptr;
51565256
EVPMDPointer mdctx(EVP_MD_CTX_new());
51575257
if (!mdctx ||
@@ -5179,6 +5279,10 @@ void SignOneShot(const FunctionCallbackInfo<Value>& args) {
51795279

51805280
signature.Resize(sig_len);
51815281

5282+
if (dsa_sig_enc == kSigEncP1363) {
5283+
signature = ConvertSignatureToP1363(env, key, std::move(signature));
5284+
}
5285+
51825286
args.GetReturnValue().Set(signature.ToBuffer().ToLocalChecked());
51835287
}
51845288

@@ -5284,6 +5388,17 @@ void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
52845388
salt_len = Just<int>(args[offset + 2].As<Int32>()->Value());
52855389
}
52865390

5391+
CHECK(args[offset + 3]->IsInt32());
5392+
DSASigEnc dsa_sig_enc =
5393+
static_cast<DSASigEnc>(args[offset + 3].As<Int32>()->Value());
5394+
5395+
ByteSource signature = ByteSource::Foreign(hbuf.data(), hbuf.length());
5396+
if (dsa_sig_enc == kSigEncP1363) {
5397+
signature = ConvertSignatureToDER(pkey, hbuf);
5398+
if (signature.get() == nullptr)
5399+
return verify->CheckThrow(Error::kSignMalformedSignature);
5400+
}
5401+
52875402
bool verify_result;
52885403
Error err = verify->VerifyFinal(pkey, hbuf.data(), hbuf.length(), padding,
52895404
salt_len, &verify_result);
@@ -5327,6 +5442,10 @@ void VerifyOneShot(const FunctionCallbackInfo<Value>& args) {
53275442
rsa_salt_len = Just<int>(args[offset + 4].As<Int32>()->Value());
53285443
}
53295444

5445+
CHECK(args[offset + 5]->IsInt32());
5446+
DSASigEnc dsa_sig_enc =
5447+
static_cast<DSASigEnc>(args[offset + 5].As<Int32>()->Value());
5448+
53305449
EVP_PKEY_CTX* pkctx = nullptr;
53315450
EVPMDPointer mdctx(EVP_MD_CTX_new());
53325451
if (!mdctx ||
@@ -5337,11 +5456,18 @@ void VerifyOneShot(const FunctionCallbackInfo<Value>& args) {
53375456
if (!ApplyRSAOptions(key, pkctx, rsa_padding, rsa_salt_len))
53385457
return CheckThrow(env, SignBase::Error::kSignPublicKey);
53395458

5459+
ByteSource sig_bytes = ByteSource::Foreign(sig.data(), sig.length());
5460+
if (dsa_sig_enc == kSigEncP1363) {
5461+
sig_bytes = ConvertSignatureToDER(key, sig);
5462+
if (!sig_bytes)
5463+
return CheckThrow(env, SignBase::Error::kSignMalformedSignature);
5464+
}
5465+
53405466
bool verify_result;
53415467
const int r = EVP_DigestVerify(
53425468
mdctx.get(),
5343-
reinterpret_cast<const unsigned char*>(sig.data()),
5344-
sig.length(),
5469+
reinterpret_cast<const unsigned char*>(sig_bytes.get()),
5470+
sig_bytes.size(),
53455471
reinterpret_cast<const unsigned char*>(data.data()),
53465472
data.length());
53475473
switch (r) {
@@ -7129,6 +7255,8 @@ void Initialize(Local<Object> target,
71297255
NODE_DEFINE_CONSTANT(target, kKeyTypeSecret);
71307256
NODE_DEFINE_CONSTANT(target, kKeyTypePublic);
71317257
NODE_DEFINE_CONSTANT(target, kKeyTypePrivate);
7258+
NODE_DEFINE_CONSTANT(target, kSigEncDER);
7259+
NODE_DEFINE_CONSTANT(target, kSigEncP1363);
71327260
env->SetMethod(target, "randomBytes", RandomBytes);
71337261
env->SetMethod(target, "signOneShot", SignOneShot);
71347262
env->SetMethod(target, "verifyOneShot", VerifyOneShot);

0 commit comments

Comments
 (0)