diff --git a/btcutil/wif.go b/btcutil/wif.go index 4ea06aa5..36600bd3 100644 --- a/btcutil/wif.go +++ b/btcutil/wif.go @@ -118,6 +118,22 @@ func DecodeWIF(wif string) (*WIF, error) { netID := decoded[0] privKeyBytes := decoded[1 : 1+btcec.PrivKeyBytesLen] + + // Ensure the private key is within the valid range for a secp256k1 + // private key, that is [1, N-1]. Without this check, a WIF encoding a + // key of zero or one greater than or equal to the group order N is + // silently accepted: btcec.PrivKeyFromBytes reduces the scalar modulo + // N, so DecodeWIF would otherwise return a private key that differs from + // the one actually encoded in the WIF (or the all-zero key) without + // reporting an error. + var keyScalar btcec.ModNScalar + defer keyScalar.Zero() + if overflow := keyScalar.SetByteSlice(privKeyBytes); overflow || + keyScalar.IsZero() { + + return nil, ErrMalformedPrivateKey + } + privKey, _ := btcec.PrivKeyFromBytes(privKeyBytes) return &WIF{privKey, compress, netID}, nil } diff --git a/btcutil/wif_test.go b/btcutil/wif_test.go index 37d3e46e..93b950aa 100644 --- a/btcutil/wif_test.go +++ b/btcutil/wif_test.go @@ -122,6 +122,30 @@ func TestEncodeDecodeWIF(t *testing.T) { wif: "5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTj", err: address.ErrChecksumMismatch, }, + { + // A WIF encoding a private key of zero, which is + // outside the valid range [1, N-1] for a secp256k1 + // private key. + name: "decodeZeroPrivKeyWif", + wif: "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAbuatmU", + err: ErrMalformedPrivateKey, + }, + { + // A WIF encoding a private key equal to the group order + // N, which is outside the valid range [1, N-1]. + name: "decodeOrderNPrivKeyWif", + wif: "5Km2kuu7vtFDPpxywn4u3NLpbr5jKpTB3jsuDU2KYEqetwr388P", + err: ErrMalformedPrivateKey, + }, + { + // A WIF encoding a private key of N+5, which is outside + // the valid range [1, N-1]. Before validation was + // added, this was silently reduced modulo N and decoded + // to a different private key (5) without any error. + name: "decodeAboveOrderNPrivKeyWif", + wif: "5Km2kuu7vtFDPpxywn4u3NLpbr5jKpTB3jsuDU2KYEqeuVhzTbv", + err: ErrMalformedPrivateKey, + }, } for _, invalidCase := range invalidDecodeCases {