smx509: don't panic marshaling invalid ECDSA keys #81

This commit is contained in:
Sun Yimin 2022-08-30 10:35:57 +08:00 committed by GitHub
parent fb7041acbc
commit 6a556b26d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 1 deletions

View File

@ -64,6 +64,9 @@ func MarshalSM2PrivateKey(key *sm2.PrivateKey) ([]byte, error) {
// marshalECPrivateKey marshals an EC private key into ASN.1, DER format and // marshalECPrivateKey marshals an EC private key into ASN.1, DER format and
// sets the curve ID to the given OID, or omits it if OID is nil. // sets the curve ID to the given OID, or omits it if OID is nil.
func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) { func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) {
if !key.Curve.IsOnCurve(key.X, key.Y) {
return nil, errors.New("invalid elliptic key public key")
}
privateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8) privateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8)
return asn1.Marshal(ecPrivateKey{ return asn1.Marshal(ecPrivateKey{
Version: 1, Version: 1,

View File

@ -75,11 +75,14 @@ func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorith
// RFC 3279, Section 2.3.1. // RFC 3279, Section 2.3.1.
publicKeyAlgorithm.Parameters = asn1.NullRawValue publicKeyAlgorithm.Parameters = asn1.NullRawValue
case *ecdsa.PublicKey: case *ecdsa.PublicKey:
publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
oid, ok := oidFromNamedCurve(pub.Curve) oid, ok := oidFromNamedCurve(pub.Curve)
if !ok { if !ok {
return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
} }
if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
}
publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
var paramBytes []byte var paramBytes []byte
paramBytes, err = asn1.Marshal(oid) paramBytes, err = asn1.Marshal(oid)

View File

@ -3104,3 +3104,17 @@ func TestDuplicateExtensionsCSR(t *testing.T) {
t.Fatal("ParseCertificate should fail when parsing certificate with duplicate extensions") t.Fatal("ParseCertificate should fail when parsing certificate with duplicate extensions")
} }
} }
func TestMarshalInvalidPublicKey(t *testing.T) {
_, err := MarshalPKIXPublicKey(&ecdsa.PublicKey{})
if err == nil {
t.Errorf("expected error, got MarshalPKIXPublicKey success")
}
_, err = MarshalPKIXPublicKey(&ecdsa.PublicKey{
Curve: elliptic.P256(),
X: big.NewInt(1), Y: big.NewInt(2),
})
if err == nil {
t.Errorf("expected error, got MarshalPKIXPublicKey success")
}
}