x509: malformed serial number, or The Perils of Bad Error Handling
I was getting this x509: malformed serial number error in my Go application when I tried to read a public key of a specific format. This error was very misleading, and it took me quite a while to figure it out. Most of the time was spent because of bad error handling practices in certain Go libraries. But I’ll get to that later, let’s start from the problem.
The Problem
A typical way to generate a key pair using openssl is to execute the following commands:
openssl ecparam -name secp256k1 -genkey -noout -out private.pem
openssl ec -in private.pem -pubout > public.pem
Let’s break down what’s going on here:
secp256k1is a P-256 key based on the Koblitz (k) elliptic curve. You could also use a random (r) elliptic curve and a longer key, e.g. by usingsecp384r1;- the first line generates a private key and outputs it into the
private.pemfile; - the second line takes the private key from the
private.pemfile and extracts a public key from it.
I needed to read a public part of this key in my Go application.
The Investigation
This is how I was parsing the public key, by using the golang-jwt/jwt library:
parsedPublicKey, err := golangJwt.ParseECPublicKeyFromPEM(publicKey)
if err != nil {
log.Fatalf("Failed to parse the public key: %v", err)
}
If you look at the contents of the ecdsa_utils.go where this ParseECPublicKeyFromPEM function is defined, you’ll notice the following lines. Anything suspicious?
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
Yes, you saw it right. This code tries to parse the public key in the PKIX format, and if it fails, it swallows the initial error and just tries to parse it again as a certificate. If it fails again, it outputs the second error. So the completely misleading error I was receiving might be hiding a totally different problem! This is bad error handling practice number one: swallowing the error and/or returning a different one.
Since I already knew that my key is in the PKIX format, I’ve replaced this ParseECPublicKeyFromPEM function call with my own function with better error handling:
func ParseECPublicKeyFromPEM(publicKey []byte) (pubKey *ecdsa.PublicKey,
err error) {
var pemBlock *pem.Block
// parse the PEM file
if pemBlock, _ = pem.Decode(publicKey); pemBlock == nil {
return nil, fmt.Errorf("Failed to parse the pem file: %w", err)
}
// parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParsePKIXPublicKey(pemBlock.Bytes); err != nil {
return nil, fmt.Errorf("Failed to parse the public key: %w", err)
}
// make sure it's of the proper type
switch parsedKey.(type) {
case *ecdsa.PublicKey:
return parsedKey.(*ecdsa.PublicKey), nil
default:
return nil, fmt.Errorf("The public key has incorrect type: %v."+
" *ecdsa.PublicKey is expected.", reflect.TypeOf(parsedKey))
}
}
Note that this code properly handles the wrong key type by returning an error like The public key has incorrect type: *rsa.PublicKey. *ecdsa.PublicKey is expected.
Now I got a proper error: x509: Unsupported elliptic curve. That’s better. It means that the generated key didn’t have the supported format. But what’s wrong with the curve? This error message came from the Go SDK, but unfortunately, the error didn’t contain any information about which type of curve that is, and what curves are supported. This is bad error handling practice number two: using a generic error message without any parameters.
So what exactly was the problem? By looking at the documentation on the Go’s elliptic package, I’ve figured out that the P256 implementation supports only the secp256r1 key type, not the secp256k1. So I needed to generate my key using the secp256r1 or secp384r1 key type.
The Takeaways
So here’s the takeaway number one: whenever you see that your public key can’t be parsed in a Go application with an error like x509: Unsupported elliptic curve or x509: malformed serial number, this may be because you’ve used the type secp256k1 to generate it. Don’t use this key type in Go programs.
And the takeaway number two: avoid bad error handling practices. Do not swallow any error messages, make sure you output them at least as warnings. Ideally, chain the errors. Try to output an exhaustive error message with parameters (what did the caller do wrong, what was actually expected) to save cumulative hundreds of hours of investigation for your users.