Skip to content

Commit bd08ba3

Browse files
authored
crypto: throw on X509Certificate operation errors
X509Certificate can report failed operations as missing fields or negative checks. Invalid validity times return "Bad time value" or Invalid Date, making relational date comparisons return false. Throw when required fields cannot be converted, certificate encoding or fingerprint calculation fails, or a present AIA or EKU extension cannot be decoded. Apply this to getters and explicit toLegacyObject() calls. Report failed or unsupported private-key comparisons as exceptions. For verify(), return true for 1 and false for 0. Also return false for a wrong key type or invalid unused bits in the signature BIT STRING. Throw for other negative results. Use the existing conversion behavior for legacy TLS certificate objects, which are also constructed internally during handshakes. Formatting unrelated metadata must not cause an uncaught exception or reject an otherwise valid connection. Fixes: #67285 Signed-off-by: Filip Skokan <panva.ip@gmail.com> Assisted-by: Codex PR-URL: #67408 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 0b4d0ac commit bd08ba3

10 files changed

Lines changed: 972 additions & 217 deletions

File tree

‎deps/ncrypto/ncrypto.cc‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <openssl/rand.h>
1010
#include <openssl/x509v3.h>
1111
#if NCRYPTO_USE_OPENSSL_PROVIDER
12+
#include <openssl/asn1err.h>
1213
#include <openssl/decoder.h>
1314
#endif
1415
#if NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK
@@ -1484,13 +1485,15 @@ BIOPointer X509View::getIssuer() const {
14841485
return bio;
14851486
}
14861487

1487-
BIOPointer X509View::getInfoAccess() const {
1488+
BIOPointer X509View::getInfoAccess(bool* has_extension) const {
14881489
MarkPopErrorOnReturn mark_pop_error_on_return;
1490+
if (has_extension != nullptr) *has_extension = false;
14891491
if (cert_ == nullptr) return {};
1492+
const int index = X509_get_ext_by_NID(cert_, NID_info_access, -1);
1493+
if (index < 0) return {};
1494+
if (has_extension != nullptr) *has_extension = true;
14901495
BIOPointer bio(BIO_new(BIO_s_mem()));
14911496
if (!bio) return {};
1492-
int index = X509_get_ext_by_NID(cert_, NID_info_access, -1);
1493-
if (index < 0) return {};
14941497
const X509_EXTENSION* extension = X509_get_ext(cert_, index);
14951498
if (extension == nullptr || !SafeX509InfoAccessPrint(bio, extension)) {
14961499
return {};
@@ -1850,10 +1853,22 @@ X509View::CheckKeyResult X509View::checkPrivateKey(
18501853
}
18511854
}
18521855

1853-
bool X509View::checkPublicKey(const EVPKeyPointer& pkey) const {
1856+
Result<bool, int> X509View::checkPublicKey(const EVPKeyPointer& pkey) const {
18541857
ClearErrorOnReturn clearErrorOnReturn;
1855-
if (cert_ == nullptr || pkey == nullptr) return false;
1856-
return X509_verify(const_cast<X509*>(cert_), pkey.get()) == 1;
1858+
if (cert_ == nullptr || pkey == nullptr) return Result<bool, int>(-1);
1859+
const int result = X509_verify(const_cast<X509*>(cert_), pkey.get());
1860+
if (result >= 0) return Result<bool, int>(result == 1);
1861+
1862+
const auto error = ERR_peek_last_error();
1863+
#if NCRYPTO_USE_OPENSSL_PROVIDER
1864+
// A wrong key type or malformed signature BIT STRING cannot verify.
1865+
if (ERR_GET_LIB(error) == ERR_LIB_ASN1 &&
1866+
(ERR_GET_REASON(error) == ASN1_R_WRONG_PUBLIC_KEY_TYPE ||
1867+
ERR_GET_REASON(error) == ASN1_R_INVALID_BIT_STRING_BITS_LEFT)) {
1868+
return Result<bool, int>(false);
1869+
}
1870+
#endif
1871+
return Result<bool, int>(int{result}, error);
18571872
}
18581873

18591874
X509View::CheckMatch X509View::checkHost(const std::string_view host,
@@ -1972,15 +1987,19 @@ Result<X509Pointer, int> X509Pointer::Parse(
19721987
return Result<X509Pointer, int>(ERR_get_error());
19731988
}
19741989

1975-
bool X509View::enumUsages(UsageCallback callback) const {
1976-
if (cert_ == nullptr) return false;
1990+
X509View::UsageResult X509View::enumUsages(UsageCallback callback) const {
1991+
if (cert_ == nullptr) return UsageResult::OPERATION_FAILED;
19771992
StackOfASN1 eku;
1993+
int critical = -1;
19781994
{
19791995
MarkPopErrorOnReturn mark_pop_error_on_return;
19801996
eku.reset(static_cast<STACK_OF(ASN1_OBJECT)*>(
1981-
X509_get_ext_d2i(cert_, NID_ext_key_usage, nullptr, nullptr)));
1997+
X509_get_ext_d2i(cert_, NID_ext_key_usage, &critical, nullptr)));
1998+
}
1999+
if (!eku) {
2000+
// The decoder reports absence as -1 and duplicate extensions as -2.
2001+
return critical == -1 ? UsageResult::ABSENT : UsageResult::OPERATION_FAILED;
19822002
}
1983-
if (!eku) return false;
19842003
const int count = sk_ASN1_OBJECT_num(eku.get());
19852004

19862005
for (int i = 0; i < count; i++) {
@@ -1989,10 +2008,10 @@ bool X509View::enumUsages(UsageCallback callback) const {
19892008
MarkPopErrorOnReturn mark_pop_error_on_return;
19902009
usage = ObjectToText(sk_ASN1_OBJECT_value(eku.get(), i), true);
19912010
}
1992-
if (!usage.has_value()) return false;
2011+
if (!usage.has_value()) return UsageResult::OPERATION_FAILED;
19932012
callback(usage->c_str());
19942013
}
1995-
return true;
2014+
return UsageResult::PRESENT;
19962015
}
19972016

19982017
bool X509View::ifRsa(KeyCallback<Rsa> callback) const {

‎deps/ncrypto/ncrypto.h‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1731,7 +1731,7 @@ class X509View final {
17311731
BIOPointer getSubject() const;
17321732
BIOPointer getSubjectAltName(bool* has_extension = nullptr) const;
17331733
BIOPointer getIssuer() const;
1734-
BIOPointer getInfoAccess() const;
1734+
BIOPointer getInfoAccess(bool* has_extension = nullptr) const;
17351735
BIOPointer getValidFrom() const;
17361736
BIOPointer getValidTo() const;
17371737
std::optional<std::string_view> getSignatureAlgorithm() const;
@@ -1750,7 +1750,7 @@ class X509View final {
17501750
bool isCA() const;
17511751
bool isIssuedBy(const X509View& other) const;
17521752
CheckKeyResult checkPrivateKey(const EVPKeyPointer& pkey) const;
1753-
bool checkPublicKey(const EVPKeyPointer& pkey) const;
1753+
Result<bool, int> checkPublicKey(const EVPKeyPointer& pkey) const;
17541754

17551755
std::optional<std::string> getFingerprint(const Digest& method) const;
17561756

@@ -1768,8 +1768,13 @@ class X509View final {
17681768
CheckMatch checkEmail(std::string_view email, int flags) const;
17691769
CheckMatch checkIp(const Buffer<const unsigned char>& ip, int flags) const;
17701770

1771+
enum class UsageResult {
1772+
ABSENT,
1773+
PRESENT,
1774+
OPERATION_FAILED,
1775+
};
17711776
using UsageCallback = std::function<void(const char*)>;
1772-
bool enumUsages(UsageCallback callback) const;
1777+
UsageResult enumUsages(UsageCallback callback) const;
17731778

17741779
template <typename T>
17751780
using KeyCallback = std::function<bool(const T& t)>;

‎doc/api/crypto.md‎

Lines changed: 63 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2967,6 +2967,11 @@ be passed instead of a public key.
29672967

29682968
<!-- YAML
29692969
added: v15.6.0
2970+
changes:
2971+
- version: REPLACEME
2972+
pr-url: https://github.com/nodejs/node/pull/67408
2973+
description: Required field conversion, certificate encoding, fingerprint
2974+
calculation, and AIA or EKU decoding failures now throw.
29702975
-->
29712976

29722977
Encapsulates an X509 certificate and provides read-only access to
@@ -3144,6 +3149,10 @@ if (!x509.verify(otherCert.publicKey)) {
31443149

31453150
<!-- YAML
31463151
added: v15.6.0
3152+
changes:
3153+
- version: REPLACEME
3154+
pr-url: https://github.com/nodejs/node/pull/67408
3155+
description: Unsupported key comparisons and comparison errors now throw.
31473156
-->
31483157

31493158
* `privateKey` {KeyObject} A private key.
@@ -3152,6 +3161,10 @@ added: v15.6.0
31523161
Checks whether the public key for this certificate is consistent with
31533162
the given private key.
31543163

3164+
Returns `false` if the keys do not match. Throws
3165+
`ERR_CRYPTO_UNSUPPORTED_OPERATION` if the keys cannot be compared,
3166+
or `ERR_CRYPTO_OPERATION_FAILED` if the comparison cannot be completed.
3167+
31553168
### `x509.extensions`
31563169

31573170
<!-- YAML
@@ -3203,6 +3216,8 @@ added: v15.6.0
32033216

32043217
The SHA-1 fingerprint of this certificate.
32053218

3219+
Throws if the fingerprint cannot be calculated.
3220+
32063221
Because SHA-1 is cryptographically broken and because the security of SHA-1 is
32073222
significantly worse than that of algorithms that are commonly used to sign
32083223
certificates, consider using [`x509.fingerprint256`][] instead.
@@ -3217,6 +3232,8 @@ added: v15.6.0
32173232

32183233
The SHA-256 fingerprint of this certificate.
32193234

3235+
Throws if the fingerprint cannot be calculated.
3236+
32203237
### `x509.fingerprint512`
32213238

32223239
<!-- YAML
@@ -3229,6 +3246,8 @@ added:
32293246

32303247
The SHA-512 fingerprint of this certificate.
32313248

3249+
Throws if the fingerprint cannot be calculated.
3250+
32323251
Because computing the SHA-256 fingerprint is usually faster and because it is
32333252
only half the size of the SHA-512 fingerprint, [`x509.fingerprint256`][] may be
32343253
a better choice. While SHA-512 presumably provides a higher level of security in
@@ -3248,10 +3267,11 @@ changes:
32483267
in response to CVE-2021-44532.
32493268
-->
32503269

3251-
* Type: {string}
3270+
* Type: {string|undefined}
32523271

32533272
A textual representation of the certificate's authority information access
3254-
extension.
3273+
extension, or `undefined` if the extension is absent. Throws if the extension
3274+
cannot be decoded or formatted.
32553275

32563276
This is a line feed separated list of access descriptions. Each line begins with
32573277
the access method and the kind of the access location, followed by a colon and
@@ -3273,6 +3293,8 @@ added: v15.6.0
32733293

32743294
The issuer identification included in this certificate.
32753295

3296+
Throws if the issuer name cannot be formatted.
3297+
32763298
### `x509.issuerCertificate`
32773299

32783300
<!-- YAML
@@ -3330,9 +3352,10 @@ issuer name cannot be inspected.
33303352
added: v15.6.0
33313353
-->
33323354

3333-
* Type: {string\[]}
3355+
* Type: {string\[]|undefined}
33343356

3335-
An array detailing the key extended usages for this certificate.
3357+
An array of extended key usage OIDs, or `undefined` if the extension is absent.
3358+
Throws if the extension cannot be decoded or an OID cannot be formatted.
33363359

33373360
### `x509.publicKey`
33383361

@@ -3354,6 +3377,8 @@ added: v15.6.0
33543377

33553378
A `Buffer` containing the DER encoding of this certificate.
33563379

3380+
Throws if the certificate cannot be encoded.
3381+
33573382
### `x509.serialNumber`
33583383

33593384
<!-- YAML
@@ -3364,6 +3389,8 @@ added: v15.6.0
33643389

33653390
The serial number of this certificate.
33663391

3392+
Throws if the serial number cannot be formatted.
3393+
33673394
Serial numbers are assigned by certificate authorities and do not uniquely
33683395
identify certificates. Consider using [`x509.fingerprint256`][] as a unique
33693396
identifier instead.
@@ -3378,6 +3405,8 @@ added: v15.6.0
33783405

33793406
The complete subject of this certificate.
33803407

3408+
Throws if the subject name cannot be formatted.
3409+
33813410
### `x509.subjectAltName`
33823411

33833412
<!-- YAML
@@ -3486,6 +3515,8 @@ There is no standard JSON encoding for X509 certificates. The
34863515
`toJSON()` method returns a string containing the PEM encoded
34873516
certificate.
34883517

3518+
Throws if the certificate cannot be encoded.
3519+
34893520
### `x509.toLegacyObject()`
34903521

34913522
<!-- YAML
@@ -3497,6 +3528,15 @@ added: v15.6.0
34973528
Returns information about this certificate using the legacy
34983529
[certificate object][] encoding.
34993530

3531+
Throws if a required field conversion, Authority Information Access or Extended
3532+
Key Usage decoding, fingerprint calculation, or certificate encoding fails.
3533+
Optional public key fields may be omitted as described in the legacy encoding.
3534+
3535+
The TLS methods [`tlsSocket.getPeerCertificate()`][] and
3536+
[`tlsSocket.getCertificate()`][] use the legacy conversion behavior:
3537+
unconvertible AIA and EKU extensions are omitted, and invalid validity times
3538+
are returned as `'Bad time value'`.
3539+
35003540
### `x509.toString()`
35013541

35023542
<!-- YAML
@@ -3507,6 +3547,8 @@ added: v15.6.0
35073547

35083548
Returns the PEM-encoded certificate.
35093549

3550+
Throws if the certificate cannot be encoded.
3551+
35103552
### `x509.validFrom`
35113553

35123554
<!-- YAML
@@ -3517,8 +3559,7 @@ added: v15.6.0
35173559

35183560
The date/time from which this certificate is valid.
35193561

3520-
If the certificate's `notBefore` time cannot be parsed, this is the string
3521-
`'Bad time value'`.
3562+
Throws if the time cannot be converted or formatted.
35223563

35233564
### `x509.validFromDate`
35243565

@@ -3532,15 +3573,7 @@ added:
35323573

35333574
The date/time from which this certificate is valid, encapsulated in a `Date` object.
35343575

3535-
If the certificate's `notBefore` time cannot be parsed, this property is an
3536-
invalid `Date` whose `getTime()` method returns `NaN`.
3537-
3538-
Relational comparisons with an invalid `Date` evaluate to `false`. To check
3539-
whether the current time is within the certificate's validity period, use
3540-
`now >= x509.validFromDate && now <= x509.validToDate`. This expression
3541-
evaluates to `false` if either date is invalid. Checking
3542-
`now < x509.validFromDate || now > x509.validToDate` instead can fail to
3543-
reject certificates with invalid dates.
3576+
Throws if the time cannot be converted.
35443577

35453578
### `x509.validTo`
35463579

@@ -3552,8 +3585,7 @@ added: v15.6.0
35523585

35533586
The date/time until which this certificate is valid.
35543587

3555-
If the certificate's `notAfter` time cannot be parsed, this is the string
3556-
`'Bad time value'`.
3588+
Throws if the time cannot be converted or formatted.
35573589

35583590
### `x509.validToDate`
35593591

@@ -3567,15 +3599,7 @@ added:
35673599

35683600
The date/time until which this certificate is valid, encapsulated in a `Date` object.
35693601

3570-
If the certificate's `notAfter` time cannot be parsed, this property is an
3571-
invalid `Date` whose `getTime()` method returns `NaN`.
3572-
3573-
Relational comparisons with an invalid `Date` evaluate to `false`. To check
3574-
whether the current time is within the certificate's validity period, use
3575-
`now >= x509.validFromDate && now <= x509.validToDate`. This expression
3576-
evaluates to `false` if either date is invalid. Checking
3577-
`now < x509.validFromDate || now > x509.validToDate` instead can fail to
3578-
reject certificates with invalid dates.
3602+
Throws if the time cannot be converted.
35793603

35803604
### `x509.signature`
35813605

@@ -3641,6 +3665,8 @@ added: v24.9.0
36413665

36423666
The OID of the algorithm used to sign the certificate.
36433667

3668+
Throws if the OID cannot be formatted.
3669+
36443670
### `x509.version`
36453671

36463672
<!-- YAML
@@ -3656,6 +3682,10 @@ v3. A certificate with no encoded version field has version `1`.
36563682

36573683
<!-- YAML
36583684
added: v15.6.0
3685+
changes:
3686+
- version: REPLACEME
3687+
pr-url: https://github.com/nodejs/node/pull/67408
3688+
description: Errors reported separately from verification failure now throw.
36593689
-->
36603690

36613691
* `publicKey` {KeyObject} A public key.
@@ -3664,6 +3694,11 @@ added: v15.6.0
36643694
Verifies that this certificate was signed by the given public key.
36653695
Does not perform any other validation checks on the certificate.
36663696

3697+
Returns `true` for a valid signature and `false` for a verification failure or
3698+
an incompatible key type. A signature BIT STRING with invalid unused bits also
3699+
returns `false`. Throws for other errors reported separately from verification
3700+
failure.
3701+
36673702
## `node:crypto` module methods and properties
36683703

36693704
### `crypto.argon2(algorithm, parameters, callback)`
@@ -8118,6 +8153,8 @@ See the [list of SSL OP Flags][] for details.
81188153
[`stream.Transform`]: stream.md#class-streamtransform
81198154
[`stream.Writable` options]: stream.md#new-streamwritableoptions
81208155
[`stream.transform` options]: stream.md#new-streamtransformoptions
8156+
[`tlsSocket.getCertificate()`]: tls.md#tlssocketgetcertificate
8157+
[`tlsSocket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed
81218158
[`util.promisify()`]: util.md#utilpromisifyoriginal
81228159
[`verify.update()`]: #verifyupdatedata-inputencoding
81238160
[`verify.verify()`]: #verifyverifykey-signature-signatureencoding

0 commit comments

Comments
 (0)